Namaste coders! Aaj hum seekhenge ki Ruby on Rails (RoR) mein ek simple RESTful API kaise banate hain, toh tension mat lo! π
Requirements:
- Ruby + Rails installed (
gem install rails
) - Terminal/Command Prompt
- Postman (API test karne ke liye)
Step 1: Naya Rails Project Banana (API Mode)
Sabse pehle, ek naya Rails project create karo jo sirf API ke liye optimized ho. Isme views aur frontend-related cheeze nahi hongi.
rails new blog_api --api -T
--api
: API-specific configuration-T
: Skip Test Unit (agar aapko RSpec pasand hai toh skip karo)
Step 2: Database Setup
Maan lo hum Post
model banane wale hain jiska title
aur content
hoga.
Migration File Create Karo:
cd blog_api
rails g model Post title:string content:text
rails db:create db:migrate
Step 3: Controller Banana
Ab ek controller banate hain jiske through API endpoints handle karenge.
rails g controller api/v1/posts
Why
api/v1
? Versioning ke liye! Future mein agar API update karni ho toh aasaan rahega.
Step 4: Controller Code (Edit app/controllers/api/v1/posts_controller.rb
)
class Api::V1::PostsController < ApplicationController
# GET /posts (Saare posts dikhao)
def index
posts = Post.all
render json: posts
end
# GET /posts/:id (Single post dikhao)
def show
post = Post.find(params[:id])
render json: post
end
# POST /posts (Naya post create karo)
def create
post = Post.new(post_params)
if post.save
render json: post, status: :created
else
render json: post.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /posts/:id (Update existing post)
def update
post = Post.find(params[:id])
if post.update(post_params)
render json: post
else
render json: post.errors, status: :unprocessable_entity
end
end
# DELETE /posts/:id (Post delete karo)
def destroy
post = Post.find(params[:id])
post.destroy
head :no_content
end
private
# Strong parameters (security ke liye)
def post_params
params.require(:post).permit(:title, :content)
end
end
Step 5: Routes Setup (config/routes.rb
)
API endpoints define karo:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :posts # auto-creates CRUD routes
end
end
end
Ye automatically generate karega routes:
GET /api/v1/posts
POST /api/v1/posts
GET /api/v1/posts/:id
PUT /api/v1/posts/:id
DELETE /api/v1/posts/:id
Step 6: Server Start Karo!
rails s
Server chalta hoga http://localhost:3000
par.
Step 7: API Test Karein (Postman ke Saath)
- GET Request:
URL:http://localhost:3000/api/v1/posts
Method:GET
- POST Request (New Post):
URL:http://localhost:3000/api/v1/posts
Method:POST
Body (raw JSON):
{
"post": {
"title": "Mera Pehla Post",
"content": "Rails API mast hai!"
}
}
- Update/Delete:
Similar, bas endpoint meinid
daalni hai (e.g.,/api/v1/posts/1
).
Advanced Tips (Agar Time Ho Toh):
- Authentication:
devise
gem ya JWT tokens use karo. - Serializers: Response ko customize karne ke liye
active_model_serializers
gem. - CORS: Agar frontend alag domain se ho, toh
rack-cors
gem setup karo. - Rate Limiting:
rack-attack
gem se API abuse rokho.
Galtiyon Se Bacho! β οΈ
render json
mein status codes sahi bhejo (e.g.,:created
for 201).- Strong parameters (
post_params
) hamesha use karo. - Versioning (
v1
) shuru se hi implement karo.
Final Output:
Aapka pura CRUD API tayyar hai! π Ab aap ise React, Angular, ya mobile app se connect kar sakte ho.
Koi doubt ho toh comment mein pucho! Happy Coding! π
Rails FTW! πβ¨