Build a RESTful JSON API With Rails

Rails API

Getting Started

Using Rails as your API(Application Programming Interface) is a very popular choice. Rails provides a set of defaults that allows developers to get their app up and running quickly. To get started, run the following command:

This will generate a new project. The API argument tells Rails that we are building an API application. The -T removes the default testing framework if you want to add a different one such as RSpec.

Rack CORS

In order to make cross-origin AJAX calls possible, we need to uncomment the following gem in the GemFile.

We also need to uncomment the following code in the config/initializers/Cors.rb file. Origins can be specified as a string, a regular expression, or as ‘*’ to allow all origins. The same goes for the resource path.

Models

Lets start by making a User Model. We’ve included the model attributes in the model generation command. This way we don’t have to edit the migration file.

After the models have been generated we can go ahead and run:

Which will create the following schema.

Serializer

Rails is a perfect framework for building websites, and it is designed keeping the best programming practices in mind. It is wonderful to use as an API, but it doesn’t render very nicely. To render Rails in a prettier way, it is best to use a serializer such as Active Model Serializer, which is especially useful when you only want to display certain attributes. Add the following gem and run bundle install.

This gem will give to the ability to add a serializer to each model.

Using a serializer gives you the ability to customize which attributes you want displayed. It also gives you the ability to add relationships directly in the serializer class.

Controllers

Now its time to set up the controllers. The problem is that people using your API expect certain results to stay constant and that’s not always possible with updates. So to keep it that way we need to add versioning!

Time to build out the actions.

Namespaced Routes

Now since we versioned our controller, we need to namespace the routes so that we have access to them.

Seed Data

The last thing to do is seed some test data to see if the API displays the data properly.

Which should display the following:

Happy Coding!!!

I am a Full Stack software engineer that enjoys problem solving and can't wait to learn more. Hard work and dedication shape my work ethic.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store