Saturday, August 6, 2016

How to create a REST API for an existing Ruby on Rails 5 application?

Leave a Comment

I have a Rails 5 app with ActionCable and Devise gem hosted on Heroku with 15K users. Many users have suggested to release a mobile app for the website. I want to start by creating a basic mobile app for the website.

When I google, all I get is API only guide. Are there any tutorials or books or any resource that show how to create a REST API for an existing Rails app?

Can someone kindly guide on how to do this? How do I authenticate users? How do I use real-time chat? Should I use any gem? Kindly share how to start and the best practices. Thanks

7 Answers

Answers 1

You could use grape gem. Check out its Rails integration section.

Since you already have some routes in place, just pick up an unused root path for your API and mount it there:

mount Twitter::API => '/api' 

Answers 2

This Railscast is very helpful. He goes through how to set up the basic parts of a restful API for an already functioning (albeit very simple) Rails app.

It's a few years old, but should still work for Rails 5.

Answers 3

I would recommend you to start looking for the JSON responses, in Rails you have everything you need to create an web application and an API with the same controllers. You need to start with 'respond_to' for JSON. To start playing around, use scaffold for controller generation and it will provide you a responder for JSON and HTML.

Answers 4

May be you can use activemodel serializers gem, it is part of rails 5. if you are currently not using Rails 5 api mode, you can add activemodel serializers gem to your Gemfile.

may be this tutorial will help

Answers 5

For Ruby on Rails 5 you can generate an API app using:

$ rails new my_api --api

You can also change an existing application and make it an API one, with a few minor changes in some files.

And for your current normal Rails app, you just need to add respond_to for JSON in your current controller. Ex:

def index   @tasks = Task.all   respond_to :html, :json end 

For user authentication you can check Devise gem

Answers 6

I think you first start with API authentication. This gem may suit your need: https://github.com/lynndylanhurley/devise_token_auth

Answers 7

Since you want to integrate a RESTful API with an existing Rails app, you should refer to this guide.

It is a more user-friendly guide on how to integrate Grape (as Nic Nilov mentioned) with your Rails 5 application. This guide assumes you already have an existing Rails application.

Hopefully this helps!

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment