I'm working on a web application that requires a few API endpoints for AJAX calls. I've recently discovered the jbuilder gem that is included when creating a Rails application (I had no clue of it before my search on returning structured JSON.).
I wanted a route structure similar to the following:
- /api [namespace]
- /api/coupons [get]
- /api/:controller [other controllers for added functionality]
The functionality overview is the coupon endpoint should return JSON data on whether the coupon is valid or expired. If it's valid we should also get a value returned. With jbuilder we can created and structure our JSON however we'd like.
I was running into a template error about a missing template when I had everything setup per the documentation. It ended up being a small detail in my routes.rb file.
routes.rb example:
namespace :api do
resources :coupons, only: [:index], defaults: {format: 'json'}]
end
Performing a rake routes
will output a path to allow a get request. The issue with the template error of a template missing had to do with setting the "defaults" to JSON. Once I updated that in the routes file the index.json.jbuilder
file rendered correctly after hitting our endpoint.
You'll want to create and namespace your API controller as well.