Request / Response Design
Request Payload Structure
Use a structured format like JSON or XML for request payloads.
Use camelCase for field names to align with JavaScript conventions.
Define required fields and optional fields explicitly in API documentation.
Use
PATCHfor partial updates with only the fields that need to be changed.Validate the input request properly
Use proper validation messages and handle exceptions .
Response Design
Flat Response:
Use for simple resources with minimal metadata.
{
"id": 1,
"title": "Product A",
"price": 100.0
}Envelope Response:
Use for more complex responses with metadata, pagination, or additional information.
Specific Response Objects
Paginated Response
Offset-Based Pagination:
Use offset (starting point) and limit (number of items to return).
Example:
/products?offset=10&limit=20
Page-Based Pagination:
Use page and size.
Example Request:
/products?page=2&size=20
Cursor-Based Pagination:
Use a cursor (e.g., unique ID or timestamp) for fetching the next set of records.
Example Request:
/products?cursor=abc123&limit=20
Metadata
Include metadata to provide additional context:
total: Total number of items in the collection.
currentPage: Current page number.
totalPages: Total number of pages.
nextCursor: For cursor-based pagination, the token for the next set of records.
Error Response Standardization
Standardizing error responses makes troubleshooting easier for API clients.
Code: Unique error identifier (e.g., HTTP status code or custom code).
Message: Human-readable description of the error.
Details: Additional information, such as invalid fields or suggested fixes (optional).
Timestamp: The time the error occurred (optional).
Using Problem Detail
Async Operation Response
Streaming Response
Best Practices Summary:
Request Design:
Use DTOs for request/response objects
Implement validation at multiple levels
Include tracking information
Support idempotency for non-idempotent operations
Response Design:
Use consistent response envelope
Include metadata when necessary
Support pagination for collections
Include relevant links (HATEOAS)
Error Handling:
Consistent error format
Appropriate error codes
Meaningful error messages
Validation error details
Performance:
Use sparse fieldsets
Support pagination
Consider streaming for large datasets
Implement caching headers
Last updated