{"title":"JSON API","description":"","section":"cookbook","version":"v1.5","path":"cookbook/json-api","canonical_url":"https://amberframework.org/docs/v1.5/cookbook/json-api","markdown_url":"https://amberframework.org/docs/v1.5/cookbook/json-api.md","inherited":true,"content_markdown":"# JSON API\n\nThis recipe will help you to setup a basic JSON API response in your application.\n\n{% hint style=\"warning\" %}\nFirst you need an amber project generated with [Amber CLI](../guides/create-new-app.md) or [from scratch](from-scratch.md).\n{% endhint %}\n\nTo create a JSON API from the command line, you simply need to use the [API generator](../cli/generate.md#api). Or for quick reference, run:\n\n```bash\namber g api Post title:string entry:integer\n```\n\nAnd it will generate the following files:\n\n```bash\n04:09:54 Generate   | (INFO) Generating Amber::CLI::Api\n04:09:54 Generate   | (INFO) new       spec/models/post_spec.cr\n04:09:54 Generate   | (INFO) identical spec/models/spec_helper.cr\n04:09:54 Generate   | (INFO) new       src/models/post.cr\n04:09:54 Generate   | (INFO) new       db/migrations/20191031160954280_create_post.sql\nFormat ./config/routes.cr\n04:09:54 Generate   | (INFO) new       spec/controllers/post_controller_spec.cr\n04:09:54 Generate   | (INFO) identical spec/controllers/spec_helper.cr\n04:09:54 Generate   | (INFO) new       src/controllers/post_controller.cr\n```\n\nThis is a fully scaffolded JSON API.\n\n### Custom\n\nIf you don't need full CRUD, you can also create a custom JSON API.\n\n```crystal\nclass SomeController < ApplicationController\n  def json_api\n    # You can easily access the context\n    # and set content_type like 'application/json'.\n    # Look how easy to build a JSON serving API.\n    context.response.content_type = \"application/json\"\n    data = {name: \"Amber\", age: 1}\n    data.to_json\n  end\nend\n```\n\nThen in your routes file:\n\n{% code-tabs %}\n{% code-tabs-item title=\"config/routes.cr\" %}\n```crystal\nAmber::Server.configure do |app|\n  pipeline :api do\n    # pipelines...\n  end\n\n  routes :api do\n    # other routes,,,\n    get \"/json_api\", SomeController, :json_api\n  end\nend\n```\n{% endcode-tabs-item %}\n{% endcode-tabs %}\n\nAlternatively you can use [`respond_with`](../guides/controllers/respond-with.md) helper. Here you don't need to setup `content_type`, however the requested path requires a `.json` extension, by example `/json_api.json`\n\n```crystal\nclass SomeController < ApplicationController\n  def json_api\n    data = {name: \"Amber\", age: 1}\n    respond_with do\n      json data.to_json\n    end\n  end\nend\n```\n\nFor a full CRUD example, see [JSON API full CRUD](../examples/json-api-full-crud.md).\n\nAlso see [Respond With](../guides/controllers/respond-with.md) and [Response & Request](../guides/controllers/request-and-response-objects.md)."}