Responses
Response objects structure and format the output of your Azu endpoints. They provide type-safe, consistent responses with proper serialization and content type handling.
What are Response Objects?
A response object is a type-safe container that:
Structures Data: Organizes response data in a consistent format
Handles Serialization: Converts data to appropriate formats (JSON, XML, HTML)
Sets Content Types: Specifies the response content type
Provides Type Safety: Ensures compile-time type safety for responses
Basic Response Object
struct UserResponse
include Azu::Response
def initialize(@user : User)
end
def render
{
id: @user.id,
name: @user.name,
email: @user.email,
created_at: @user.created_at.to_rfc3339
}.to_json
end
endKey Components
Module Include:
include Azu::ResponseInitializer: Accept data to be serialized
Render Method: Define how to serialize the data
Built-in Response Types
Azu provides several built-in response types for common use cases:
JSON Response
HTML Response
Text Response
Empty Response
Custom Response Objects
Create custom response objects for your specific needs:
Single Resource Response
Collection Response
Error Response
Content Type Handling
Set appropriate content types for your responses:
Status Code Handling
Set appropriate HTTP status codes:
Header Management
Set custom headers in your responses:
Pagination Support
Handle paginated responses:
Template Integration
Use templates for HTML responses:
Streaming Responses
Handle large responses with streaming:
File Downloads
Handle file downloads:
Response Caching
Implement response caching:
Error Response Format
Standardize error responses:
Testing Response Objects
Test your response objects:
Best Practices
1. Use Consistent Structure
2. Handle Null Values
3. Use Appropriate Content Types
4. Include Metadata
5. Handle Errors Gracefully
Performance Considerations
1. Lazy Loading
2. Caching
Next Steps
Now that you understand response objects:
Endpoints - Use response objects in your endpoints
Templates - Learn about template rendering
Caching - Implement response caching
Testing - Test your response objects
Performance - Optimize response performance
Response objects provide the foundation for structured, type-safe output in Azu applications. With proper serialization, content type handling, and error management, they ensure consistent and reliable API responses.
Last updated
Was this helpful?
