JSON API
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.
To create a JSON API from the command line, you simply need to use the API generator. Or for quick reference, run:
1
amber g api Post title:string entry:integer
Copied!
And it will generate the following files:
1
04:09:54 Generate | (INFO) Generating Amber::CLI::Api
2
04:09:54 Generate | (INFO) new spec/models/post_spec.cr
3
04:09:54 Generate | (INFO) identical spec/models/spec_helper.cr
4
04:09:54 Generate | (INFO) new src/models/post.cr
5
04:09:54 Generate | (INFO) new db/migrations/20191031160954280_create_post.sql
6
Format ./config/routes.cr
7
04:09:54 Generate | (INFO) new spec/controllers/post_controller_spec.cr
8
04:09:54 Generate | (INFO) identical spec/controllers/spec_helper.cr
9
04:09:54 Generate | (INFO) new src/controllers/post_controller.cr
Copied!
This is a fully scaffolded JSON API.

Custom

If you don't need full CRUD, you can also create a custom JSON API.
1
class SomeController < ApplicationController
2
def json_api
3
# You can easily access the context
4
# and set content_type like 'application/json'.
5
# Look how easy to build a JSON serving API.
6
context.response.content_type = "application/json"
7
data = {name: "Amber", age: 1}
8
data.to_json
9
end
10
end
Copied!
Then in your routes file:
config/routes.cr
1
Amber::Server.configure do |app|
2
pipeline :api do
3
# pipelines...
4
end
5
6
routes :api do
7
# other routes,,,
8
get "/json_api", SomeController, :json_api
9
end
10
end
Copied!
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
1
class SomeController < ApplicationController
2
def json_api
3
data = {name: "Amber", age: 1}
4
respond_with do
5
json data.to_json
6
end
7
end
8
end
Copied!
For a full CRUD example, see JSON API full CRUD.
Last modified 1yr ago
Copy link
Contents
Custom