This repository provides a step-by-step guide on how to create a Ruby on Rails API, seed it with fake data using the Faker gem, and test the API endpoints using Postman.
- Creating a Rails API
- Setting Up the Database
- Generating Models and Controllers
- Implementing API Endpoints
- Seeding Data with Faker
- Testing API Endpoints with Postman
-
Install Ruby and Rails if you haven't already.
-
Open your terminal and run the following command to create a new Rails API-only application:
rails new my_api --api --database=postgresql
- Change into the project directory:
cd my_api
- Open the 'config/database.yml` file and configure your PostgreSQL connection details
- Create the database:
rails db:create
- Generate a model (e.g, Article)
rails g model Article title:string content:text
- Run the migration:
rails db:migrate
- Generate a namespaced controller:
rails g controller Api::V1::Articles
- Define your routes in
config/routes.rb
:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :articles, only: [:index, :show, :create, :update, :destroy]
end
end
end
- Implement controller actions in app/controllers/api/v1/articles_controller.rb:
class Api::V1::ArticlesController < ApplicationController
def index
articles = Article.all
render json: articles
end
def show
article = Article.find(params[:id])
render json: article
end
def create
article = Article.new(article_params)
if article.save
render json: article, status: :created
else
render json: article.errors, status: :unprocessable_entity
end
end
def update
article = Article.find(params[:id])
if article.update(article_params)
render json: article
else
render json: article.errors, status: :unprocessable_entity
end
end
def destroy
article = Article.find(params[:id])
article.destroy
head :no_content
end
private
def article_params
params.require(:article).permit(:title, :content)
end
end
- Add the faker gem to your Gemfile
gem 'faker'
- Run
bundle/install
- Edit
db/seeds.rb
require 'faker'
50.times do
Article.create!(
title: Faker::Lorem.sentence(word_count: 3, supplemental: true, random_words_to_add: 4),
content: Faker::Lorem.paragraphs(number: 3).join("\n\n")
)
end
- Run the seed file:
rails db:seed
-
Install Postman client on desktop, and open Postman
-
Start your Rails server:
rails s
- Send the requests and observe the responses. In this example, you can try
http://localhost:3000/api/v1/articles/1
. You can replace1
with the actual iD of the article you want to interact with.
This README provides a comprehensive guide that covers creating a Rails API, setting up the database, implementing API endpoints, seeding data with Faker, and testing the API using Postman. It's structured in a way that's easy to follow and includes all the necessary steps and code snippets.