Creating a Ruby on Rails API (Speed Guide)

Whether you are creating an endpoint to serve data to the public or supplying data to your web app, using Ruby on Rails allows you to quickly accomplish your task while supporting SQL databases and Ruby models. To get started, make sure that you have Ruby installed on your computer, along with the rails gem.

Generating the Project

A large part of why Ruby on Rails allows for projects to be quickly prototyped and implemented is the existence of easy-to-use generators. You can read more about Ruby on Rails generators here. For now, we will generate a Rails API using Postgresql as the database with the following command:

The command is pretty straightforward. We are asking the rails gem to create a new project, and by specifying --api we are asking the API-specific files to be generated. By specifying --database=postgresql, we are asking that we use Postgresql instead of SQLite. We need to do this because Postgresql is typically used for production level projects compared to SQLite since SQLite is not as easily scalable.

Depending on your computer’s processor speed, the command will vary in how long it takes. Once the command finishes, the directory with the name specified in api_name from the command above will be created, along with many subdirectories and files within. After running this command, we are almost done already! Next, let’s set up our git repository. If you do not care about setting up Github in your project, skip the next section and go directly to Creating Models.

Connecting to Github

If you do not wish to connect your project with Github, skip this section and proceed to Creating Models directly. When we use the rails generator, a git repository is automatically created for us, as we can see from the .git directory in our main project directory. So, we can easily link our local copy to Github. To do so, navigate to https://github.com/new and make sure that you have an account set up. Then, create a repository with the name of your choosing, add a description, and choose the privacy of your repository. Since we already have a repository, leave the checkboxes for the README and other additional files unchecked.

After creating the Github repository, we can now push our local code online. After creating the repository, the repository will have a link in the following form: github.com/<your-username>/<project-name>.git

Connecting the new rails project to the repository is simple and can be done with the following commands executed in the main project directory:

Where the < > are filled with information from the repository link. After executing these commands, you may need to verify your GitHub credentials in the command line.

And just like that, you are done, and can refresh your Github page to check that all the files have been uploaded.

Creating Models

Creating models is exactly the same as if you were doing so with a regular rails project. Create the migrations for the database and also the Ruby class files, along with any associations between the models. Since that isn’t the main point of this post, I would just suggest reading the documentation for the rails generator, which comes in with commands to automatically create useful files.

Enabling CORS

CORS, or Cross Origin Resource Sharing, allows our API to accept requests from other domain names. This is important because if our frontend is independent from the backend, we won’t be able to retrieve the data unless we enable CORS. To enable CORS, we need to use the rack-cors gem with some extra code specifying what we want to grant permissions to. If you used the rails generator with the API option for the project, then just navigate to the Gemfile and uncomment the rack-cors gem. Then, run bundle install to ensure that it works.

Next, we need to specify the configuration options for CORS. Once we enable the gem, we can now navigate to the config/initializers/cors.rb file, which contains settings for CORS. Uncomment the Ruby code, and for now, just replace where it asks for the url to ‘*’. This will permit any other outside resource to access the API. If you are giving data to your webapp, then you will want to change this to be your front-end web address, but if you are providing data for all to use, then this should suffice.

Sending out JSON Data

We are almost done setting up our Rails API. Next, configure your routes in the config/routes.rb file the same way you would as in a full stack Rails application. If you are only providing data for others to use, then your routes would primarily be GET routes. If you are serving data for a front end, then you will have a greater variety of HTTP request types. For my personal project, I had the following routes:

Of course, along with your routes, you will need the corresponding controllers in the app/controllers/ directory. This is nothing new, if you’ve made a Ruby on Rails application this is the same process.

Now, in the controller is where things start to become different. When making a full stack Rails app, we rendered full html, and had a views folder where we could specify which one to render in our controller method. We also could use redirect_to to move between pages. However, since we’re just creating an API, we won’t have any views, and instead will pass on data as JSON. Doing so is simple, all we need to do is specify render json: {data}. For {data}, we can just put in any Ruby hash, and rails will automatically convert it to JSON and send it in the body of the response. Here is a following example of a controller method:

Rails will automatically convert the hash into JSON and send it as a response. Rails also integrates the option to pass models in as JSON data, and will automatically retrieve the attributes of the instance of the class. You also can look into the gem active_model_serializers to help with JSON data creation.

Conclusion

With that, you are done! Run rails server and you should be able to test out your GET endpoints through the browser!