DEV Community

Cover image for Build Your First Rails API
Engr. Promise
Engr. Promise

Posted on

Build Your First Rails API

In this article i am going to quickly show you how you can build a simple rails api. This will give you an idea of what building API entails.
I am going to make this as simple as possible so that you understand the basics.
The api end point that we will be building will get us a random greetings.
Lets dive in and get our hands dirty.
First, you will need to create a Rails API app by running the following command:

rails new my_api --api --database=postgresql

Enter fullscreen mode Exit fullscreen mode

We will need to create the database by running

rails db:create
Enter fullscreen mode Exit fullscreen mode

Next, you will need to create a model for your greetings table by running the following command:

rails g model Greeting content:string

Enter fullscreen mode Exit fullscreen mode

Run the following command to create the table in your database:

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Next, you will need to seed your database with some greeting data. You can do this by adding the following lines of code to the db/seeds.rb file:

Greeting.create(content: "Hello")
Greeting.create(content: "Hi")
Greeting.create(content: "Good morning")
Greeting.create(content: "Good afternoon")
Greeting.create(content: "Good evening")

Enter fullscreen mode Exit fullscreen mode

Run the following command to seed your database:

rails db:seed

Enter fullscreen mode Exit fullscreen mode

Now you can create your API endpoint. In your config/routes.rb file, add the following line of code:

get '/random_greeting', to: 'greetings#random'
Enter fullscreen mode Exit fullscreen mode

Create a GreetingsController by running the following command:

rails g controller Greetings
Enter fullscreen mode Exit fullscreen mode

In your app/controllers/greetings_controller.rb file, add the following action:

def random
  greeting = Greeting.order("RANDOM()").first
  render json: { greeting: greeting.content }
end

Enter fullscreen mode Exit fullscreen mode

Now when you make a GET request to the '/random_greeting' endpoint, it will return a JSON response with a random greeting from your table.
I hope this helps! Let me know if you have any questions.

Top comments (0)