Why you should use Rails as an API

As you may have known by now, Rails can act as a frontend and backend, but it is especially great as an API. An API (Application Programming Interface) is how systems communicate with other systems, they are often used as sources of data that we use in our own applications.

By using Rails, it makes it easier to create our own API’s that you can share with others. Rails API’s render JSON strings, which makes it useful when building frontends and requests.You aren’t confined to just using your own API’s though, you can access many different public API’s throughout the web from Twitter to Spotify. To build a new Rails API from scratch, run the following command in your terminal:

$ rails new your_api_name_goes_here --api

By adding the “api” flag at the end, Rails knows that this will be an API application and will remove a lot of the default features related to the browser, like generating views, since we won’t be using them. Once we navigate into our newly created application, we can use generators to build out our resources.

rails g resource ex_one ex_attribute:stringrails g resource ex_two ex_attribute_two:integer rails g resource ex_three ex_one:reference ex_two:reference

Running these commands will create our migrations, models, and controllers. Once we add our seed data, we can run rails “db:migrate”, “db:seed”, and “rails db:create” to populate our API. We then need to add the controller action’s that we want to execute.

def index
ex_three = Ex_three.all
render json: ex_three, include: [:ex_one, :ex_two]

Once you have your resources configured, you can now start up your API by running rails server, and start sending requests to it!