Let’s build an API using Ruby on Rails

Iain Robertson
5 min readOct 20, 2020

There are numerous components to a full stack web application, but in the broadest terms, you can think of the stack as being comprised of two main components: the frontend, which is where views are displayed for a client, and the backend, which persists necessary data for the the frontend to render and interact with. Today we are going to build a simple backend using Rails as our API.

  1. create a new rails project.

As rails is basically magic — and I am of the opinion that when magic is available, take full advantage, monkey’s paws included — the foundation of a rails API is achieved with one line in the terminal: ‘rails new your-project --api’. This is the groundwork upon which we will assemble our backend. If you are familiar with the “rails new” command, and the “--api” is unfamiliar to you, all that this is essentially doing is politely asking rails not include functionality that will be superfluous in the context of an API, when generating our new project. Now is an excellent opportunity to ‘cd’ into our new project and begin customizing our infrastructure.

2. create any models, associations, and migrations you may need

Now let’s make our models. First ensure you are inside of your newly created project, either by using ‘cd’ or the terminal in your code editor. We are going to be approaching this API with the concepts of MVC and object orientation in mind, and to accomplish that, we are going to require appropriately associated models. For demonstration purposes let stick with a user model for the time being. We can accomplish this with relative ease with the command line ‘rails g model user name’. This line will generate a model and corresponding migration that contains a column within the migration known as ‘name’, which will have an implicit value of string.

3. migrate

Run ‘rails db:migrate’. This will conduct our migrations and structure our API database to our specifications.

4. create your model controllers

Once again, rails makes this wonderfully convenient with a command line. ‘rails g controller api/v1/users’. This will politely indicate to rails that we need a controller to help coordinate routes and facilitate communication with our new backend, and soon to be constructed frontend. The ‘api/v1/’ segment of that command is merely a naming convention to facilitate easier versioning.

5. seed any test data

This a good time to populate our database with some test data, so that we begin to connect the separate components of our stack, there is something for the backend to communicate to the frontend. We do this by creating new user instances in our seed.rb file ‘User.create(name: “Doug the user”)’. After you have written your seeds, it’s time to run ‘rails db:migrate’ in order to actually seed them.

6. routes

Now we need to define our routes for our controller interactions. Here we are using “resources”, to ensure we have access to Get, Patch, Post, and Delete routes. It is important to use ‘namespace’ here, to ensure that our controller is correctly linked.

This allows us to make ‘GET’ and ‘POST’ requests to our database, using strong params.

7. render json

Here is where our controller comes in handy. We are going to want to define our index method (known as a GET method as it will allow us to retrieve information from our database), Using ‘User.all’ set to a variable, such as ‘users’, in conjunction with ‘render json:’. This will ensure that when we run our server, the data is parsed into language agnostic json, for us to manipulate and display. If our routes are intact, we should be able to start our server using ‘rails s’, and visit our ‘localhost:3000/api/v1/users’ route, which should return something like this in our browser:

Once we loosen our CORS restrictions, we should be able to access this data in our JavaScript frontend by calling fetch on this route.

8. CORS

At this point we have to contend with CORS, or ‘Cross-origin resource sharing’. To enable communication between our frontend and our backend, we will have to navigate around CORS, and once again, Rails has the answer. We will have uncomment out an already provided gem called ‘gem:rack-cors’, you will find it in the gemfile.rb (at the time of this writing it’s hanging out around line 26 of the file). Once it is commented in, you can run ‘bundle install’ to ensure it is put to use. After that you will need to allow access to your API from outside sources, we can accomplish this by going into our config folder, then selecting cors.rb from within the initializers folder (config> initializers> cors.rb). Now comes more uncommenting.

This is the chunk of code we need to comment in. This will allow us to explicitly grant CORS permissions to whoever we choose. In this case, we will keep it simple and make our origins ‘*’

This will ensure access to our API/database data from our frontend, which will be contained in a folder separate from our rails API.

Once your API is set up with above steps, you are ready to construct your front end, and begin fetching data from your Rails backend to be incorporated into your frontend. This is a good time to establish separate folders for your frontend and backend within your project. We will then be able to build out JavaScript, HTML, and CSS in combination with fetches to access and style our JSON data from our API.

The backend folder houses the API, and the frontend folder will contain all Javascript, CSS, and HTML

Hopefully after completing these steps, you should have the beginnings of a backend, which is the first major component in a full stack. Congratulations! By using this API in conjunction with your frontend, you should have the makings of a cheerfully simple full stack app. Good luck!

--

--