Rails API creating a simple REST service



The first thing you need to do is

1. gem install rails-api

2. create your new rails api application by issuing the following command

 rails-api new RailApi

Here, we have just created a new application called RailApi. This has more or less the same structure with traditional rails based application

3. cd RailApi

4. Lets create our REST service'. We begin by creating a user controller and its model.

rails g scaffold User name email

If you goto db/migrate, you will see a file called user followed by some date. It should has the following contents :-




4. Add active_model_serializer to our gem file, as shown here.

gem 'active_model_serializer'

5. And run "bundle install"

6. Create its serializer

rails g serializer user name email

This will generate the files as follows :-



7. Lets update our database by issuing rake command

rake db:migrate

If will go ahead and creates all the required table for our application

8. Lets start our server by issuing :- rails server

9. We need to setup some test data by going into rails console.

Execute rails console, and create some fake data

10. Lets try to retrieve our data by typing the following in our brower

http://localhost:3000/users

and

http://localhost:3000/users/1

Noticed that Rails automatically gives a plural version of the model that we wanted to create.

It should have your data returned as json format.

Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm