JSON API

Last updated 6 months ago

This recipe will help you to setup a basic JSON API response in your application.

First you need an amber project generated with Amber CLI or from scratch.

class SomeController < ApplicationController
def json_api
# You can easily access the context
# and set content_type like 'application/json'.
# Look how easy to build a JSON serving API.
context.response.content_type = "application/json"
data = {name: "Amber", age: 1}
data.to_json
end
end

Then in your routes file:

config/routes.cr
Amber::Server.configure do |app|
pipeline :web do
# pipelines...
end
‚Äč
routes :web do
# other routes,,,
get "/json_api", SomeController, :json_api
end
end

Alternatively you can use respond_with helper. Here you don't need to setup content_type, however the requested path requires a .json extension, by example /json_api.json

class SomeController < ApplicationController
def json_api
data = {name: "Amber", age: 1}
respond_with do
json data.to_json
end
end
end

Also see Respond With and Response & Request.