Build Your First Rails API
Engr. Promise
Posted on January 5, 2023
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
We will need to create the database by running
rails db:create
Next, you will need to create a model for your greetings table by running the following command:
rails g model Greeting content:string
Run the following command to create the table in your database:
rails db:migrate
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")
Run the following command to seed your database:
rails db:seed
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'
Create a GreetingsController by running the following command:
rails g controller Greetings
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
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.
Posted on January 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024