Code for fun! Create a Rails API

Share this post!
Rails API – original pic from jetruby.com –

Rails API – original pic from jetruby.com –

Introduction

The use of the term Application Programming Interface, or API, is very common in the computer community. My interest in this post is focused on the Web APIs or, in other words, the tools used by web communities to facilitate sharing content and data between communities and applications  So let’s share some data in a few steps using Rails. As a de facto standard, I use JSON to serve data and a TDD methodology to test first what I code later.

I have based this work on this post (in Spanish) from Giancarlos Isasi. I’ve completed the steps with some notes, just to do not forget what I have done.

Let’s code

I use RVM to keep control of the different versions of Ruby running in my server. If you do so, let’s choose the right version – feel free to use another version if needed.

Let’s add some gems. I would add RSpec to test the application, Shoulda Matchers to help with the tests conditions and Factory Girl to do the same with the test data. To do so, edit the Gemfile and modify the group :development, :test group to be as follows:

Now I should install the gems and bootstrap RSpec. Once this is done, I should add the User model, create the database and prepare the test structure. There are no tests yet, but the infrastructure for RSpec is ready to be used.

Add some tests and run RSpec again. You will see the tests that do not pass.

In order to make the tests to pass,  add some validations to the User model.

But we wanted to create an API to access the resource Users. So I have to modify the route.

This will set up a route in the form http://localhost:3000/api/v1/… The ‘api’ part indicates that the URL is part of an API and not give access to a normal web app, and the ‘v1’ indicates to developers the version number. Using this info on the URL will allow future updates of the API without breaking applications accessing previous versions still in operation.

Create the test for the user controller.

In order to access the data, I will add the users’ controller and the users’ view. Is a view needed when the data will be rendered to the client in JSON format? Probably not. This point needs a more in-depth reading!!

If we want to ask the API for data we need to enter the data first. Modify the file seeds.rb to add some data, populate the database and start the application

Access the URL of the web service on http://localhost:3000/api/v1/users and you will receive the data in JSON format.

Congrats! You have your API up and running!

, ,