Expand description
§Chapter 2: Request Building
This chapter covers building more complex requests with POST, path parameters, and query parameters.
§POST Requests with JSON Body
To send JSON data, use the .json() method. Your request type needs
Serialize and ToSchema:
use clawspec_core::ApiClient;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Serialize, ToSchema)]
struct CreateUser {
name: String,
email: String,
}
#[derive(Deserialize, ToSchema)]
struct User {
id: u64,
name: String,
email: String,
}
let mut client = ApiClient::builder()
.with_host("api.example.com")
.build()?;
let new_user = CreateUser {
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
};
let created: User = client
.post("/users")?
.json(&new_user)? // Serialize as JSON
.await?
.as_json()
.await?;
println!("Created user with ID: {}", created.id);Both request and response schemas are captured automatically.
§Path Parameters
Use CallPath for templated paths with parameters:
use clawspec_core::{ApiClient, CallPath, ParamValue};
// Define path with parameter placeholder
let path = CallPath::from("/users/{user_id}")
.add_param("user_id", ParamValue::new(123));
let user: User = client
.get(path)?
.await?
.as_json()
.await?;The generated OpenAPI will show /users/{user_id} with the parameter documented.
§Query Parameters
Use CallQuery for query string parameters:
use clawspec_core::{ApiClient, CallQuery};
let query = CallQuery::new()
.add_param("page", 1)
.add_param("limit", 20)
.add_param("sort", "name");
let users: UserList = client
.get("/users")?
.with_query(query)
.await?
.as_json()
.await?;This generates a request to /users?page=1&limit=20&sort=name.
§Combining Path and Query Parameters
You can use both together:
use clawspec_core::{ApiClient, CallPath, CallQuery, ParamValue};
let path = CallPath::from("/users/{user_id}/posts")
.add_param("user_id", ParamValue::new(42));
let query = CallQuery::new()
.add_param("status", "published")
.add_param("limit", 10);
let posts: Posts = client
.get(path)?
.with_query(query)
.await?
.as_json()
.await?;§Other HTTP Methods
All standard HTTP methods are supported:
use clawspec_core::{ApiClient, CallPath, ParamValue};
let path = CallPath::from("/users/{id}").add_param("id", ParamValue::new(1));
// PUT - Full replacement
client.put(path.clone())?
.json(&UpdateUser { name: "Bob".to_string() })?
.await?
.as_empty()
.await?;
// PATCH - Partial update
let updated: User = client.patch(path.clone())?
.json(&PatchUser { name: Some("Robert".to_string()) })?
.await?
.as_json()
.await?;
// DELETE
client.delete(path)?
.await?
.as_empty()
.await?;§Key Points
- Use
.json(&data)?to send JSON request bodies CallPathhandles path parameters like/users/{id}CallQueryhandles query parameters- All HTTP methods are available:
get,post,put,patch,delete
Next: Chapter 3: Response Handling - Learn about different response handling strategies.