build-json-api
Use this skill when building JSON API endpoints in Hanami 2.x Actions.
End-to-End Workflow: Creating a JSON Endpoint
- Create the action and set
response.format = :json - Add a dedicated serializer for the entity being returned
- Write a round-trip test asserting serialize → parse produces correct fields
- Verify: run the test; fix serializer if fields are missing or misformatted
Core Rules
Set the response format to JSON:
def handle(request, response) response.format = :json # ... endUse dedicated serializers to encode response bodies. For implementation details and conventions, see SERIALIZERS.md.
def handle(request, response) response.format = :json user = user_repo.by_id(request.params[:id]).one response.body = MyApp::Serializers::UserSerializer.new(user).to_json endVerify round-trip serialization: Always assert that a serialized object can be parsed back into equivalent data. Format all date/time fields with
.iso8601. If the assertion fails, check that the serializer maps all fields and that timestamps use.iso8601.# In tests: serialized = UserSerializer.new(user).to_json parsed = JSON.parse(serialized, symbolize_names: true) assert_equal user.email, parsed[:email] assert_equal user.created_at.iso8601, parsed[:created_at] # If assertion fails: verify serializer field mapping and timestamp formattingHandle request body parsing via
request.params:def handle(request, response) response.format = :json attrs = request.params[:user] result = user_repo.create(attrs) response.status = 201 response.body = UserSerializer.new(result).to_json endReturn consistent error shapes: Ensure all error responses conform to a unified structure:
halt 422, { error: { message: "Validation failed", details: [...] } }.to_jsonInclude pagination metadata for collections: Expose pagination fields inside a
metablock sibling todata:{ data: users.map { |u| UserSerializer.new(u).to_h }, meta: { page: request.params[:page] || 1, per_page: request.params[:per_page] || 20, total: user_repo.count } }.to_jsonRescue parse errors and return bad request (400) status:
rescue JSON::ParserError halt 400, { error: "Invalid JSON body" }.to_json end