What makes a good API?
A good API has 4 traits
- predictable and consistent: code reuse for API endpoints.
- static: an API should not change in a breaking way.
- simple and clear: an API should return what’s expected.
- flexible: easy to scale and maintain
RubyOnRails is mostly known for rapid agile web apps development. Following the current trends, Integrating a front-end framework has become challenging and even time-consuming.
In fact, modern web app architectures nowadays consist of a client app that consumes a JSON API. Indeed, Rails 5 introduced the API mode; A bootstrapped skeleton for API only apps.
The framework may not be as “cool” as it was before. But, it has matured and evolved accordingly with action cable, turbo links 5, etc.
For the sake of this tutorial, we will be building a public API with a single resource: Articles
API versioning is mandatory only if :
- You are introducing breaking changes features.
- Your client apps are installable whether on mobile or desktop.
- Other developers will rely on your API.
- You are shipping features gradually.
Step 1: Create Rails API Skeleton
Open your terminal and type:
rails new [api_name] — api
Step 2: Versioning your API
We wanna access our API via /api/v1 URL . First, let’s create the missing folders.
mkdir app/controllers/apimkdir app/controllers/api/v1
Step 3: Scaffold a resource
Open a terminal and execute Rails commands.
rails g scaffold Article title:string content:text slug:stringrails db:migrate
Step 4: Move the resource controller to its respective folder
mv app/controllers/articles_controller.rb app/controllers/api/v1
Step 5: Update The controller
We will add the namespaces prior to the class name and update the URL helper in the create method.
Step 6: Update the route file
Open config/routes.rb with your text editor. Delete the resource line.
Then add the namespaces. The final route file should look like the following
Rails.application.routes.draw do namespace :api do namespace :v1 do resources :articles end end# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.htmlend
Step 7: More resources
You can repeat steps 3 - 6 for as many resources as you want.
Step 8: Try it!
We will start by seeding the database. Open db/seeds.rb and create a record:
Article.create(title: ‘Hello world’,content: ‘lorem ipso’,slug: ‘hello-world’)
Start the server:
Open the browser and go to:
You can use Postman or curl to interact with the API.
Going further and scale
Congratulations! you have shipped your first API. But this is only the beginning. Here are some things you need to consider:
- Unit Testing: The scaffold by default provides a set of basic test cases. However, when it comes to building real products writing custom test cases is essential.
- Authentication: in case your API is private.
- Hosting: I highly recommend Heroku.
- Serializers: to control the output of the API responses.