### Build HTTP Response with Data using HttpResponse in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README[ES].md Demonstrates how to construct an HTTP response using the `HttpResponse` struct in Rust. This example shows setting a 'Created' status, a success message, and embedding serialized user data in the response body. It's useful for returning successful resource creation or retrieval. ```rust use axum_responses::http::HttpResponse; use serde::Serialize; #[derive(Serialize)] struct User { id: u32, username: String, } async fn handler() -> HttpResponse { let user_data = User { id: 1, username: "example_user".to_string(), }; HttpResponse::Created() .message("Datos de usuario obtenidos exitosamente") .data(user_data) } ``` -------------------------------- ### HttpResponse::Ok() - 200 Success Response Source: https://context7.com/mrrevillod/axumresponses/llms.txt Creates a standard 200 OK response with an optional data payload and a custom message. This is typically used for successful GET requests or other operations that return data. ```APIDOC ## POST /api/users ### Description Creates a standard 200 OK response with an optional data payload and a custom message. ### Method GET ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for this operation" } ``` ### Response #### Success Response (200) - **code** (integer) - The HTTP status code (200). - **success** (boolean) - Indicates the success of the operation (true). - **message** (string) - A human-readable message describing the outcome. - **timestamp** (string) - The ISO 8601 timestamp when the response was generated. - **data** (object) - The payload containing the requested resource or data. #### Response Example ```json { "code": 200, "success": true, "message": "User retrieved successfully", "timestamp": "2025-10-19T18:30:00Z", "data": { "id": 42, "username": "john_doe", "email": "john@example.com" } } ``` ``` -------------------------------- ### Handle HTTP Bad Request Error with HttpResponse in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Illustrates how to create an HTTP error response (400 Bad Request) using `HttpResponse`. This example shows how to attach a detailed error payload, such as validation errors, to the response, which is crucial for informing clients about request issues. ```rust use axum_responses::http::HttpResponse; use serde_json::json; async fn error_handler() -> HttpResponse { let validation_error = json!({ "type": "ValidationError", "errors": [ { "field": "username", "message": "Username is required" }, { "field": "email", "message": "Email must be a valid email address" } ] }); HttpResponse::BadRequest() .message("Invalid request data") .error(validation_error) } ``` -------------------------------- ### Handle HTTP Error Responses with HttpResponse in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README[ES].md Illustrates how to generate an HTTP error response, specifically a 'Bad Request', using the `HttpResponse` struct in Rust. This example includes a custom JSON error payload detailing validation issues, suitable for API endpoints requiring input validation. ```rust use axum_responses::http::HttpResponse; use serde_json::json; async fn error_handler() -> HttpResponse { let validation_error = json!({ "type": "ValidationError", "errors": [ { "field": "username", "message": "El nombre de usuario es requerido" }, { "field": "email", "message": "El email debe ser una dirección de email válida" } ] }); HttpResponse::BadRequest() .message("Datos de solicitud inválidos") .error(validation_error) } ``` -------------------------------- ### Untitled No description -------------------------------- ### response! Macro - Quick Response Creation Source: https://context7.com/mrrevillod/axumresponses/llms.txt A macro for simplifying the creation of HTTP responses with inline JSON syntax, ideal for rapid development and prototyping. ```APIDOC ## response! Macro - Quick Response Creation ### Description Simplifies response creation with inline JSON syntax for rapid development and prototyping. It allows specifying the status code and the response body directly. ### Method Assumed POST/GET/PUT/DELETE based on handler context ### Endpoint Assumed based on handler context ### Parameters None directly on the macro, but handler parameters apply. ### Request Body None ### Request Example (200 OK) ```rust use axum_responses::{response, http::HttpResponse}; use serde::Serialize; async fn paginated_list_handler() -> HttpResponse { response!(200, { "page": 1, "per_page": 20, "total": 156, "total_pages": 8, "message": "Data retrieved successfully" }) } ``` ### Request Example (201 Created) ```rust use axum_responses::{response, http::HttpResponse}; use serde::Serialize; #[derive(Serialize)] struct OrderSummary { order_id: String, total: f64, items_count: u32, } async fn create_order_handler() -> HttpResponse { let order = OrderSummary { order_id: "ORD-2025-001".to_string(), total: 299.99, items_count: 5, }; response!(201, { order }) } ``` ### Response #### Success Response (200/201) - **code** (integer) - The HTTP status code (e.g., 200, 201). - **success** (boolean) - Always true for successful responses. - **message** (string) - A human-readable message describing the outcome. - **timestamp** (string) - The ISO 8601 timestamp of when the response was generated. - **data** (object) - The actual data payload of the response, matching the structure provided to the macro. #### Response Example (200 OK) ```json { "code": 200, "success": true, "message": "Data retrieved successfully", "timestamp": "2025-10-19T18:30:00Z", "data": { "page": 1, "per_page": 20, "total": 156, "total_pages": 8 } } ``` #### Response Example (201 Created) ```json { "code": 201, "success": true, "message": "Created", "timestamp": "2025-10-19T18:30:00Z", "data": { "order_id": "ORD-2025-001", "total": 299.99, "items_count": 5 } } ``` ``` -------------------------------- ### response! Macro for Simple Responses Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Explains the usage of the `response!` macro for creating straightforward HTTP responses with custom status codes and JSON bodies. ```APIDOC ## response! Macro for Simple Responses ### Description This section details the `response!` macro, a convenient way to generate `HttpResponse` objects. It allows specifying the status code and a JSON body directly, simplifying response creation for common scenarios. ### Method N/A (Illustrative) ### Endpoint N/A (Illustrative) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200 OK) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A message describing the outcome. - **timestamp** (string) - The timestamp when the response was generated. - **data** (object) - The payload containing the response data. #### Response Example ```json { "code": 200, "success": true, "message": "Success Response (OK)", "timestamp": "2023-10-01T12:00:00Z", "data": { "page": 10, "total": 100 } } ``` ``` -------------------------------- ### response! Macro for Single Resource Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Demonstrates using the `response!` macro to return a single resource or entity within the `data` field of the response. ```APIDOC ## response! Macro for Single Resource ### Description This section explains how the `response!` macro can be used to return a single object within the `data` field of the HTTP response. This is particularly useful for returning a single resource or entity, mimicking JavaScript notation. ### Method N/A (Illustrative) ### Endpoint N/A (Illustrative) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (201 Created) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A message describing the outcome. - **timestamp** (string) - The timestamp when the response was generated. - **data** (object) - The single resource object. #### Response Example ```json { "code": 201, "success": true, "message": "Created", "timestamp": "2023-10-01T12:00:00Z", "data": { "id": "prod_123", "name": "Example Product", "price": 99.99 } } ``` ``` -------------------------------- ### HttpResponse Structure Usage Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Demonstrates how to use the HttpResponse structure to build custom success responses with status codes, messages, and data. ```APIDOC ## HttpResponse Structure Usage ### Description This section illustrates how to construct a successful HTTP response using the `HttpResponse` builder pattern. It includes setting the status code, a descriptive message, and embedding serializable data. ### Method N/A (Illustrative) ### Endpoint N/A (Illustrative) ### Parameters N/A ### Request Example N/A ### Response #### Success Response (201 Created) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A message describing the outcome. - **timestamp** (string) - The timestamp when the response was generated. - **data** (object) - The payload containing the requested or created resource. #### Response Example ```json { "code": 201, "success": true, "message": "User data retrieved successfully", "timestamp": "2023-10-01T12:00:00Z", "data": { "id": 1, "username": "example_user" } } ``` ``` -------------------------------- ### Create HTTP Responses with response! Macro in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README[ES].md Shows how to use the `response!` macro in Rust to create a standard HTTP response with a status code and a JSON body containing multiple key-value pairs. This is a concise way to generate successful responses for API endpoints. ```rust use axum_responses::{response, http::HttpResponse}; async fn example_handler() -> HttpResponse { response!(200, { "page": 10, "total": 100, "message": "Respuesta Exitosa (OK)" }) } ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Build Success HTTP Response with HttpResponse in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Demonstrates creating a successful HTTP response (201 Created) using the `HttpResponse` struct from the `axum_responses` crate. It includes setting a message and embedding serializable data. This is useful for returning newly created resources. ```rust use axum_responses::http::HttpResponse; use serde::Serialize; #[derive(Serialize)] struct User { id: u32, username: String, } async fn handler() -> HttpResponse { let user_data = User { id: 1, username: "example_user".to_string(), }; HttpResponse::Created() .message("User data retrieved successfully") .data(user_data) } ``` -------------------------------- ### Create 200 OK HTTP Response with Data in Rust Source: https://context7.com/mrrevillod/axumresponses/llms.txt Demonstrates how to create a standard HTTP 200 OK response using `HttpResponse::Ok()`. This function allows for an optional data payload and a custom message, returning a structured JSON body including status code, success flag, message, timestamp, and the provided data. It's useful for successful data retrieval operations. ```rust use axum_responses::http::HttpResponse; use serde::Serialize; #[derive(Serialize)] struct User { id: u32, username: String, email: String, } async fn get_user_handler() -> HttpResponse { let user = User { id: 42, username: "john_doe".to_string(), email: "john@example.com".to_string(), }; HttpResponse::Ok() .message("User retrieved successfully") .data(user) } ``` -------------------------------- ### HttpResponse for Errors Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Shows how to create HTTP error responses using HttpResponse, including specific error details for issues like data validation. ```APIDOC ## HttpResponse for Errors ### Description This section demonstrates how to create HTTP error responses, specifically focusing on handling bad requests with detailed validation errors. The `HttpResponse::BadRequest()` method is used to set the status code and incorporate an error payload. ### Method N/A (Illustrative) ### Endpoint N/A (Illustrative) ### Parameters N/A ### Request Example N/A ### Response #### Error Response (400 Bad Request) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful (false for errors). - **message** (string) - A message describing the error. - **timestamp** (string) - The timestamp when the response was generated. - **error** (object) - The payload containing detailed error information. #### Response Example ```json { "code": 400, "success": false, "message": "Invalid request data", "timestamp": "2023-10-01T12:00:00Z", "error": { "type": "ValidationError", "errors": [ { "field": "username", "message": "Username is required" }, { "field": "email", "message": "Email must be a valid email address" } ] } } ``` ``` -------------------------------- ### Untitled No description -------------------------------- ### Create HTTP Response with response! Macro in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Shows how to use the `response!` macro from the `axum_responses` crate to generate an HTTP response with a specified status code (200 OK) and a JSON body. This macro simplifies response creation by automatically handling serialization for common data structures. ```rust use axum_responses::{response, http::HttpResponse}; async fn example_handler() -> HttpResponse { response!(200, { "page": 10, "total": 100, "message": "Success Response (OK)" }) } ``` -------------------------------- ### Create HTTP Responses with response! Macro in AxumResponses Source: https://context7.com/mrrevillod/axumresponses/llms.txt Utilizes the response! macro for quick and simplified creation of HTTP responses, especially for JSON payloads. This macro is ideal for rapid development and prototyping, allowing inline JSON definitions. ```rust use axum_responses::{response, http::HttpResponse}; use serde::Serialize; async fn paginated_list_handler() -> HttpResponse { response!(200, { "page": 1, "per_page": 20, "total": 156, "total_pages": 8, "message": "Data retrieved successfully" }) } #[derive(Serialize)] struct OrderSummary { order_id: String, total: f64, items_count: u32, } async fn create_order_handler() -> HttpResponse { let order = OrderSummary { order_id: "ORD-2025-001".to_string(), total: 299.99, items_count: 5, }; response!(201, { order }) } ``` -------------------------------- ### Untitled No description -------------------------------- ### HttpResponse::NotFound() - 404 Resource Not Found Source: https://context7.com/mrrevillod/axumresponses/llms.txt Handles cases where the requested resource does not exist on the server. It allows setting a custom message and detailed error information. ```APIDOC ## HttpResponse::NotFound() - 404 Resource Not Found ### Description Indicates that the requested resource does not exist on the server. This method allows for a custom message and structured error details to be returned. ### Method Assumed POST/GET/PUT/DELETE based on handler context ### Endpoint Assumed based on handler context ### Parameters None directly on NotFound(), but handler parameters apply. ### Request Body None ### Request Example ```rust use axum_responses::http::HttpResponse; use serde_json::json; async fn get_resource_handler(id: String) -> HttpResponse { HttpResponse::NotFound() .message("Resource not found") .error(json!({ "type": "NotFoundError", "resource": "User", "identifier": id, "suggestion": "Please verify the resource ID and try again" })) } ``` ### Response #### Success Response (N/A) #### Error Response (404) - **code** (integer) - The HTTP status code, always 404. - **success** (boolean) - Always false for error responses. - **message** (string) - A human-readable message indicating the resource was not found. - **timestamp** (string) - The ISO 8601 timestamp of when the error occurred. - **error** (object) - Contains detailed error information. - **type** (string) - The type of error, e.g., "NotFoundError". - **resource** (string) - The type of resource that was not found. - **identifier** (string) - The identifier of the resource that was not found. - **suggestion** (string) - A suggestion for the user on how to resolve the issue. #### Response Example ```json { "code": 404, "success": false, "message": "Resource not found", "timestamp": "2025-10-19T18:30:00Z", "error": { "type": "NotFoundError", "resource": "User", "identifier": "user_123", "suggestion": "Please verify the resource ID and try again" } } ``` ``` -------------------------------- ### Untitled No description -------------------------------- ### Create 201 Created HTTP Response with Headers in Rust Source: https://context7.com/mrrevillod/axumresponses/llms.txt Illustrates the creation of an HTTP 201 Created response using `HttpResponse::Created()`. This is typically used after successfully creating a resource via a POST request. The function supports adding a data payload, a custom message, and HTTP headers, such as 'Location' to indicate the URI of the newly created resource. ```rust use axum_responses::http::HttpResponse; use serde::Serialize; #[derive(Serialize)] struct Product { id: String, name: String, price: f64, stock: u32, } async fn create_product_handler() -> HttpResponse { let new_product = Product { id: "prod_789".to_string(), name: "Wireless Mouse".to_string(), price: 29.99, stock: 150, }; HttpResponse::Created() .message("Product created successfully") .data(new_product) .add_header("Location", "/api/products/prod_789") } ``` -------------------------------- ### Untitled No description -------------------------------- ### Return Single Resource with response! Macro in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README.md Demonstrates using the `response!` macro to return a single resource as the `data` field in an HTTP response (201 Created). It supports auto-serialization of structs that implement `Serialize`, making it convenient for returning individual entities. ```rust use axum_responses::{response, http::HttpResponse}; use serde::Serialize; #[derive(Serialize)] struct Product { id: String, name: String, price: f64, } async fn product_handler() -> HttpResponse { let product_data = Product { id: "prod_123".to_string(), name: "Example Product".to_string(), price: 99.99, }; response!(201, { product_data }) } ``` -------------------------------- ### Return Single Resource with response! Macro in Rust Source: https://github.com/mrrevillod/axumresponses/blob/master/README[ES].md Demonstrates using the `response!` macro in Rust to return a single serialized resource as the `data` field in an HTTP response. This is useful for API endpoints that return a single object, simplifying the response structure. ```rust use axum_responses::{response, http::HttpResponse}; use serde::Serialize; #[derive(Serialize)] struct Product { id: String, name: String, price: f64, } async fn product_handler() -> HttpResponse { let product_data = Product { id: "prod_123".to_string(), name: "Producto de Ejemplo".to_string(), price: 99.99, }; response!(201, { product_data }) } ``` -------------------------------- ### HttpResponse::builder() - Custom Status Codes Source: https://context7.com/mrrevillod/axumresponses/llms.txt This endpoint demonstrates how to create responses with custom or less common HTTP status codes using the builder pattern. ```APIDOC ## POST /api/response/custom-status ### Description Returns a response with a custom HTTP status code (e.g., 429 Too Many Requests). ### Method POST ### Endpoint /api/response/custom-status ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "Rate limit exceeded" } ``` ### Response #### Success Response (429 Too Many Requests) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A summary message of the operation. - **timestamp** (string) - The time the response was generated. - **error** (object) - An error object detailing the issue. - **type** (string) - The type of error. - **limit** (integer) - The rate limit applied. - **window** (string) - The time window for the rate limit. - **retry_after** (integer) - Seconds to wait before retrying. - **Retry-After** (string) - Header indicating when to retry. #### Response Example ```json { "code": 429, "success": false, "message": "Rate limit exceeded", "timestamp": "2025-10-19T18:30:00Z", "error": { "type": "RateLimitError", "limit": 100, "window": "1 hour", "retry_after": 3600 } } ``` **Headers:** - `Retry-After`: `3600` ``` -------------------------------- ### Custom Headers with add_header() Source: https://context7.com/mrrevillod/axumresponses/llms.txt This endpoint demonstrates how to add custom HTTP headers to responses, which is useful for CORS, caching, content negotiation, and other HTTP features. ```APIDOC ## POST /api/response/custom-headers ### Description Returns a JSON response with custom headers added. ### Method POST ### Endpoint /api/response/custom-headers ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "API response with custom headers" } ``` ### Response #### Success Response (200) - **api_version** (string) - The version of the API. - **data** (object) - The main data payload of the response. - **X-API-Version** (string) - Custom header for API version. - **X-RateLimit-Limit** (string) - Custom header for rate limit. - **X-RateLimit-Remaining** (string) - Custom header for remaining rate limit. - **X-RateLimit-Reset** (string) - Custom header for rate limit reset time. - **Cache-Control** (string) - Cache control directives. - **Access-Control-Allow-Origin** (string) - CORS header. #### Response Example ```json { "api_version": "v1", "data": { "api_version": "1.0.0", "data": "sensitive information" } } ``` **Headers:** - `X-API-Version`: `1.0.0` - `X-RateLimit-Limit`: `1000` - `X-RateLimit-Remaining`: `999` - `X-RateLimit-Reset`: `1729360200` - `Cache-Control`: `no-cache, no-store, must-revalidate` - `Access-Control-Allow-Origin`: `*` - `Content-Type`: `application/json` ``` -------------------------------- ### Untitled No description -------------------------------- ### Create 401 Unauthorized HTTP Response with Headers in Rust Source: https://context7.com/mrrevillod/axumresponses/llms.txt Demonstrates generating an HTTP 401 Unauthorized response using `HttpResponse::Unauthorized()`. This response is used when authentication is required but credentials are missing or invalid. It includes a message and an error object detailing the reason for authentication failure and providing hints, along with the 'WWW-Authenticate' header. ```rust use axum_responses::http::HttpResponse; use serde_json::json; async fn protected_route_handler() -> HttpResponse { HttpResponse::Unauthorized() .message("Authentication required") .error(json!({ "type": "AuthenticationError", "reason": "Missing or invalid authentication token", "hint": "Please provide a valid Bearer token in the Authorization header" })) .add_header("WWW-Authenticate", "Bearer realm=\"api\"") } ``` -------------------------------- ### Create 404 Not Found Response with AxumResponses Source: https://context7.com/mrrevillod/axumresponses/llms.txt Generates a 404 Not Found HTTP response using HttpResponse::NotFound(). This is useful when a requested resource does not exist on the server. It allows custom messages and detailed error payloads. ```rust use axum_responses::http::HttpResponse; use serde_json::json; async fn get_resource_handler(id: String) -> HttpResponse { HttpResponse::NotFound() .message("Resource not found") .error(json!({ "type": "NotFoundError", "resource": "User", "identifier": id, "suggestion": "Please verify the resource ID and try again" })) } ``` -------------------------------- ### Untitled No description -------------------------------- ### Multiple Error Fields with errors() Source: https://context7.com/mrrevillod/axumresponses/llms.txt This endpoint demonstrates how to handle multiple errors or warnings in a single response, which is useful for batch operations or complex validations. ```APIDOC ## POST /api/response/batch-errors ### Description Returns a JSON response with multiple validation errors for a batch operation. ### Method POST ### Endpoint /api/response/batch-errors ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "Batch processing completed with errors" } ``` ### Response #### Success Response (422 Unprocessable Entity) - **code** (integer) - The HTTP status code. - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A summary message of the operation. - **timestamp** (string) - The time the response was generated. - **data** (object) - The data processed successfully. - **processed** (integer) - Total records processed. - **successful** (integer) - Total records processed successfully. - **failed** (integer) - Total records with errors. - **errors** (array) - A list of errors encountered. - **record_id** (integer) - The ID of the record with the error. - **field** (string) - The field that caused the error. - **error** (string) - A description of the error. #### Response Example ```json { "code": 422, "success": false, "message": "Batch processing completed with errors", "timestamp": "2025-10-19T18:30:00Z", "data": { "processed": 10, "successful": 7, "failed": 3 }, "errors": [ { "record_id": 1, "field": "email", "error": "Email already exists" }, { "record_id": 3, "field": "age", "error": "Age must be 18 or older" }, { "record_id": 5, "field": "phone", "error": "Invalid phone number format" } ] } ``` ``` -------------------------------- ### Create Axum Responses with Custom Status Codes (Rust) Source: https://context7.com/mrrevillod/axumresponses/llms.txt Creates Axum responses with custom or less common HTTP status codes using `HttpResponse::builder()` with `axum::http::StatusCode`. This allows for responses with status codes like 429 (Too Many Requests) when standard convenience methods are insufficient. Custom headers like 'Retry-After' can also be added. ```rust use axum_responses::http::HttpResponse; use axum::http::StatusCode; use serde_json::json; async fn custom_status_handler() -> HttpResponse { HttpResponse::builder(StatusCode::from_u16(429).unwrap()) .message("Rate limit exceeded") .error(json!({ "type": "RateLimitError", "limit": 100, "window": "1 hour", "retry_after": 3600 })) .add_header("Retry-After", "3600") } // Or using convenience method: async fn rate_limit_handler() -> HttpResponse { HttpResponse::TooManyRequests() .message("Too many requests") .error(json!({ "message": "You have exceeded the rate limit", "retry_after_seconds": 3600 })) .add_header("Retry-After", "3600") } ``` -------------------------------- ### HttpResponse::Created() - 201 Resource Created Source: https://context7.com/mrrevillod/axumresponses/llms.txt Returns a 201 Created response, indicating that a new resource has been successfully created. This is commonly used after a POST request. ```APIDOC ## POST /api/products ### Description Returns a 201 Created response indicating successful resource creation, typically used in POST endpoints. ### Method POST ### Endpoint /api/products ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the product. - **price** (number) - Required - The price of the product. - **stock** (integer) - Required - The initial stock quantity. ### Request Example ```json { "name": "Wireless Mouse", "price": 29.99, "stock": 150 } ``` ### Response #### Success Response (201) - **code** (integer) - The HTTP status code (201). - **success** (boolean) - Indicates the success of the operation (true). - **message** (string) - A human-readable message describing the outcome. - **timestamp** (string) - The ISO 8601 timestamp when the response was generated. - **data** (object) - The newly created resource. #### Response Example ```json { "code": 201, "success": true, "message": "Product created successfully", "timestamp": "2025-10-19T18:30:00Z", "data": { "id": "prod_789", "name": "Wireless Mouse", "price": 29.99, "stock": 150 } } ``` ``` -------------------------------- ### Handle Errors with Result in AxumResponses Source: https://context7.com/mrrevillod/axumresponses/llms.txt Demonstrates the use of the Result type alias for integrating Rust's error handling mechanisms with Axum responses. This allows the use of the `?` operator to automatically convert errors into appropriate HTTP responses, simplifying error propagation. ```rust use axum_responses::{http::HttpResponse, Result}; use serde_json::json; async fn fetch_user_data(user_id: u32) -> Result { if user_id == 0 { return Err(HttpResponse::BadRequest() .message("Invalid user ID") .error(json!({ "field": "user_id", "message": "User ID must be greater than 0" })) ); } // Simulate database lookup let user_exists = user_id < 1000; if !user_exists { return Err(HttpResponse::NotFound() .message("User not found") .error(json!({ "user_id": user_id, "message": "No user exists with this ID" })) ); } Ok(HttpResponse::Ok() .message("User found") .data(json!({ "id": user_id, "username": "example_user", "status": "active" })) ) } ```