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:

amber g api Post title:string entry:integer

And it will generate the following files:

04:09:54 Generate   | (INFO) Generating Amber::CLI::Api
04:09:54 Generate   | (INFO) new       spec/models/post_spec.cr
04:09:54 Generate   | (INFO) identical spec/models/spec_helper.cr
04:09:54 Generate   | (INFO) new       src/models/post.cr
04:09:54 Generate   | (INFO) new       db/migrations/20191031160954280_create_post.sql
Format ./config/routes.cr
04:09:54 Generate   | (INFO) new       spec/controllers/post_controller_spec.cr
04:09:54 Generate   | (INFO) identical spec/controllers/spec_helper.cr
04:09:54 Generate   | (INFO) new       src/controllers/post_controller.cr

This is a fully scaffolded JSON API.

Custom

If you don't need full CRUD, you can also create a custom JSON API.

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:

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

For a full CRUD example, see JSON API full CRUD.

Also see Respond With and Response & Request.

Last updated