FastAPI vs Ruby on Rails in 2026: Which to Pick for an API
Derar SattoufBackend & databases

FastAPI and Ruby on Rails both build JSON APIs well, but they start from opposite ends. FastAPI is a thin, async layer over Python type hints: you describe the request and response, and it gives you validation, serialization and OpenAPI docs, then leaves the database, jobs and auth to you. Rails is a full application framework: ORM, migrations, background jobs, mail, auth scaffolding and deployment are already in the box, and an API is one of the things it can be.
The short answer: pick FastAPI when the API is the product and its contract matters most (typed requests, generated docs, generated client SDKs), when the service sits next to Python code such as ML models or LLM pipelines, or when each request spends most of its time waiting on other services. Pick Rails when the API is the back end of a whole product, with users, an admin, emails, background jobs and file uploads, and a small team has to ship and run all of it.
The rest of this post shows why, with the same feature built in both. For the wider picture with Laravel, Django and Flask, see Laravel vs Django vs Flask vs FastAPI vs Rails, and for Rails against its closest rival, Laravel vs Ruby on Rails.
Where each one stands in November 2026
| FastAPI | Ruby on Rails | |
|---|---|---|
| Current version | 0.165 (November 2026); still 0.x, with frequent minor releases | Rails 8.1, released October 22, 2025; 8.2 is in development |
| Language | Python, with type hints | Ruby; 4.0 is the newest |
| What it is | An API framework on Starlette (HTTP, ASGI) and Pydantic (validation) | A full-stack framework with an API-only mode |
| Server model | ASGI: async event loop, usually Uvicorn | Rack: Puma with threads and worker processes |
| In the box | Routing, validation, serialization, dependency injection, OpenAPI docs | All of that except generated docs, plus ORM, migrations, jobs, cache, mail, storage, auth generator |
| Hosting from the makers | FastAPI Cloud, deployed with fastapi deploy | Kamal, which deploys to any Linux server you own |
The version number misleads people about FastAPI. It has been production software for years and runs large services; the 0.x numbering means minor releases may include breaking changes, so pin the version and read the release notes before upgrading. Pydantic, which does the validation, is on a stable 2.x line (2.14 in October 2026).
The same feature in both: comments on a post
Signed-in users list and add comments on a post, the post's author is notified in the background, and a test proves it. Same PostgreSQL database, same rules, same responses.
The table
FastAPI does not include an ORM. The usual choice is SQLAlchemy 2.0, with Alembic for migrations. The model is a typed class:
# app/models.py
from datetime import datetime
from sqlalchemy import ForeignKey, Text, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
class Comment(Base):
__tablename__ = "comments"
id: Mapped[int] = mapped_column(primary_key=True)
post_id: Mapped[int] = mapped_column(ForeignKey("posts.id", ondelete="CASCADE"), index=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
body: Mapped[str] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
user: Mapped["User"] = relationship()alembic revision --autogenerate -m "create comments" compares the models with the database and writes the migration, which you review and apply with alembic upgrade head.
Rails generates the model and migration from one command, bin/rails generate model Comment post:references user:references body:text:
class CreateComments < ActiveRecord::Migration[8.1]
def change
create_table :comments do |t|
t.references :post, null: false, foreign_key: true
t.references :user, null: false, foreign_key: true
t.text :body
t.timestamps
end
end
endclass Comment < ApplicationRecord
belongs_to :post
belongs_to :user
validates :body, presence: true, length: { maximum: 2000 }
scope :recent, -> { order(created_at: :desc).limit(20) }
endThe first difference is already visible. In Rails the model, the migration and the validation rules live together and come from the framework. In FastAPI you choose and wire the ORM and migration tool yourself, which is more setup, but SQLAlchemy is the most capable ORM in either language once queries get complex.
Request and response shapes
FastAPI's defining feature is that the API contract is a set of Pydantic classes:
# app/schemas.py
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class CommentIn(BaseModel):
body: str = Field(min_length=1, max_length=2000)
class CommentOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
body: str
user_id: int
created_at: datetimeCommentIn validates the request body. CommentOut decides exactly which fields leave the server, so a column added to the table later never leaks into the response by accident. Both appear in the generated OpenAPI schema.
Rails has no built-in equivalent. render json: comment serializes every column, so production APIs add a serializer: Jbuilder views (included in full apps), Alba, or as_json(only: ...) for small cases.
Routes and handlers
# app/routes/comments.py
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_session
from app.deps import current_user
from app.models import Comment, Post, User
from app.notifications import notify_post_author
from app.schemas import CommentIn, CommentOut
router = APIRouter()
SessionDep = Annotated[AsyncSession, Depends(get_session)]
UserDep = Annotated[User, Depends(current_user)]
async def get_post(post_id: int, session: SessionDep) -> Post:
post = await session.get(Post, post_id)
if post is None:
raise HTTPException(status_code=404, detail="Post not found")
return post
PostDep = Annotated[Post, Depends(get_post)]
@router.get("/posts/{post_id}/comments", response_model=list[CommentOut])
async def list_comments(post: PostDep, session: SessionDep, user: UserDep):
comments = await session.scalars(
select(Comment)
.where(Comment.post_id == post.id)
.order_by(Comment.created_at.desc())
.limit(20)
)
return comments.all()
@router.post("/posts/{post_id}/comments", response_model=CommentOut, status_code=status.HTTP_201_CREATED)
async def create_comment(
data: CommentIn, post: PostDep, session: SessionDep, user: UserDep, tasks: BackgroundTasks
):
comment = Comment(post_id=post.id, user_id=user.id, body=data.body)
session.add(comment)
await session.commit()
await session.refresh(comment)
tasks.add_task(notify_post_author, comment.id)
return comment# app/db.py
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
engine = create_async_engine("postgresql+asyncpg://app:secret@localhost/app")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session():
async with SessionLocal() as session:
yield sessionDependencies (Depends) do the work that before_action does in Rails: load the post or return 404, open a database session, resolve the current user. FastAPI caches a dependency within one request, so get_post and the handler share the same session. current_user is a dependency you write: FastAPI ships helpers such as OAuth2PasswordBearer that read the token, but the user table and token checks are yours.
Rails, generated with rails new blog_api --api:
# config/routes.rb
resources :posts do
resources :comments, only: [ :index, :create ]
endclass ApplicationController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate
private
def authenticate
authenticate_or_request_with_http_token do |token, _options|
Current.user = User.find_by_token_for(:api, token)
end
end
endclass CommentsController < ApplicationController
before_action :set_post
def index
render json: @post.comments.recent.as_json(only: [ :id, :body, :user_id, :created_at ])
end
def create
comment = @post.comments.create!(comment_params.merge(user: Current.user))
NotifyPostAuthorJob.perform_later(comment)
render json: comment.as_json(only: [ :id, :body, :user_id, :created_at ]), status: :created
end
private
def set_post
@post = Post.find(params[:post_id])
end
def comment_params
params.expect(comment: [ :body ])
end
endfind_by_token_for checks a signed token that the User model declares with generates_token_for :api, and Current is a small ActiveSupport::CurrentAttributes class. In an API app, Rails wraps a JSON body such as {"body": "Nice post"} under the comment key automatically, so params.expect works without the client nesting it.
Both return 404 for a missing post and 422 for an empty body. FastAPI's 422 lists every failed field in a fixed shape that matches the OpenAPI schema; Rails' 422 comes from the model validation and its body is up to you.
The background notification
The two lines that look alike, tasks.add_task(...) and perform_later(...), are not the same thing:
- FastAPI's
BackgroundTasksruns the function in the same process right after the response is sent. There is no queue, no retry, and if the process restarts, the task is gone. It suits small best-effort work. For anything that must happen, you add a job queue: Celery with Redis or RabbitMQ, or a lighter one such as ARQ, Dramatiq or Taskiq. - Rails'
perform_laterputs the job in Solid Queue, stored in your database, with retries, scheduling and a dashboard (Mission Control). Since Rails 8.1, long jobs can also resume after a restart with job continuations.
The test
FastAPI's tests use pytest. Dependencies can be swapped per test, which makes faking the signed-in user one line:
# tests/test_comments.py
from fastapi.testclient import TestClient
from app.deps import current_user
from app.main import app
from app.routes import comments
def test_adds_a_comment(post, user, monkeypatch): # post and user are fixtures in conftest.py
sent = []
monkeypatch.setattr(comments, "notify_post_author", sent.append)
app.dependency_overrides[current_user] = lambda: user
response = TestClient(app).post(f"/posts/{post.id}/comments", json={"body": "Nice post"})
assert response.status_code == 201
assert sent == [response.json()["id"]]
app.dependency_overrides.clear()Rails ships Minitest with fixtures and job assertions:
require "test_helper"
class CommentsControllerTest < ActionDispatch::IntegrationTest
include ActiveJob::TestHelper
test "adds a comment to a post" do
user = users(:one)
post_record = posts(:one)
headers = { "Authorization" => "Bearer #{user.generate_token_for(:api)}" }
assert_difference -> { post_record.comments.count }, 1 do
assert_enqueued_with(job: NotifyPostAuthorJob) do
post post_comments_url(post_record), params: { body: "Nice post" }, headers: headers, as: :json
end
end
assert_response :created
end
endWhat the comparison shows
- FastAPI gives you a better API contract for free. Typed inputs, filtered outputs, a uniform 422 and live docs at
/docs, all from the same classes. - Rails gives you more of the application for free. The ORM, migrations, a real job queue, test fixtures and token auth helpers are already there and already wired together.
- The code is about the same length. FastAPI spends its lines on types and wiring; Rails spends them on serializers and auth.
API docs and client generation
This is FastAPI's clearest win. Every route, parameter and model is in an OpenAPI 3.1 schema at /openapi.json, with Swagger UI at /docs and ReDoc at /redoc, and it stays correct because it is generated from the code that runs. Point a generator such as openapi-typescript or Hey API at it and your front end gets typed clients with no hand-written types.
Rails can produce the same schema, but you write it alongside the code. rswag builds OpenAPI from RSpec request specs, so the docs are tested; other gems generate it from annotations. It works, but it is a second description of the API that someone has to keep up to date.
If outside developers will use the API, or a typed front end depends on it, this difference alone can decide the choice.
How each one serves requests
FastAPI runs on an async event loop. One Uvicorn worker process handles many requests at once, switching between them whenever one waits on the database, Redis or another HTTP service. That makes it very efficient for I/O-heavy APIs, such as gateways, aggregators and services that call LLM providers. Run several workers per server (fastapi run --workers 4, or Gunicorn with Uvicorn workers) to use every CPU core.
The catch: one blocking call inside an async def handler stalls every request on that worker. A synchronous database driver, requests.get, or heavy CPU work in an async handler is the most common FastAPI production bug. Use async libraries (asyncpg, httpx) inside async def, or declare the handler with plain def, which FastAPI runs in a thread pool.
Rails runs on Puma threads and processes. Each worker process keeps the app booted and serves requests on a pool of threads. Ruby's global lock (the GVL) lets threads overlap while they wait on I/O, and worker processes give parallel CPU work. YJIT is on by default in recent Rails on Ruby 3.3 and newer. Blocking calls are normal Ruby; they use up one thread, not the whole process, so the async mistake above does not exist in Rails. The trade-off is that each worker holds the full app in memory, so concurrency per server is lower.
What this means in practice:
- In hello-world benchmarks FastAPI serves more requests per second than Rails. That reflects framework overhead on an empty endpoint, which is rarely where a real API spends its time.
- In a real API, the database decides. Queries, indexes and serialization dominate latency in both. Reading EXPLAIN ANALYZE does more for response times than either framework choice.
- FastAPI pulls ahead when requests wait on other services. Thousands of slow upstream calls in flight are cheap on an event loop and expensive in threads.
- Neither is good at heavy CPU work in the request. Move it to a job queue, or to a separate service.
Load-test one realistic endpoint before deciding on speed, and compare p50 and p99 latency and memory per worker. The FastAPI performance guide covers tuning the FastAPI side.
What you have to add yourself
The gap between the two is mostly this table. Everything in the FastAPI column is a library you pick, install and wire up; each is good, but the choices and the glue are yours.
| Need | FastAPI | Rails 8.1 |
|---|---|---|
| ORM | SQLAlchemy 2.0 or SQLModel | Active Record |
| Migrations | Alembic | Built in, with db/schema.rb |
| Background jobs | Celery, ARQ, Dramatiq or Taskiq, plus Redis or RabbitMQ | Solid Queue, in your database |
| Cache | Redis client, or a library such as cashews | Solid Cache, or Redis |
| Auth | Security helpers; users, tokens and passwords are yours, or fastapi-users | has_secure_password, generates_token_for, the authentication generator, Devise |
| Admin panel | SQLAdmin or Starlette-Admin | Avo, ActiveAdmin, Administrate |
| A library such as fastapi-mail | Action Mailer | |
| File uploads | Your own S3 code | Active Storage |
| WebSockets | Built in (Starlette) | Action Cable |
| API docs | Built in | rswag or another gem |
| Settings | pydantic-settings | Encrypted credentials |
For a single-purpose API the FastAPI column stays short. For a product back end it grows quickly, and that is where Rails saves weeks.
Auth and security
FastAPI validates every input against its types, which removes a whole class of bugs, and its security helpers handle reading tokens and API keys. Everything else about users is your code: storing password hashes (pwdlib or argon2), issuing and checking tokens (PyJWT), rate limiting, and CORS, which you turn on with CORSMiddleware. That is fine for a team that wants full control, and a common source of mistakes for one that does not.
Rails covers more by default: has_secure_password with bcrypt, signed and expiring tokens with generates_token_for, encrypted credentials, parameter filtering in logs, rate limiting with rate_limit in controllers since Rails 7.2, and Brakeman scanning new apps for security issues. For a full OAuth2 provider, Doorkeeper on Rails is more established than the Python options.
Testing and CI
| FastAPI | Rails | |
|---|---|---|
| Test framework | pytest | Minitest by default; RSpec is common |
| HTTP tests | TestClient, or httpx's AsyncClient for async tests | Integration tests |
| Faking dependencies | app.dependency_overrides | Fixtures, job and mail assertions, WebMock |
| Test data | Your own fixtures, or factory_boy | Fixtures by default; factory_bot is common |
| Types and linting | mypy or Pyright, Ruff | RuboCop, included |
| CI out of the box | None generated | A GitHub Actions workflow, and bin/ci since 8.1 |
Type checking is a real advantage for FastAPI: Pydantic models and SQLAlchemy's Mapped types let Pyright catch wrong field names and types before tests run. Rails relies on tests for the same safety, and arrives with the test setup, linting and CI already in place.
Deployment
FastAPI deploys as one process type: fastapi run (Uvicorn) in a container, behind a reverse proxy or a platform's load balancer. FastAPI Cloud, from the FastAPI team, deploys an app with fastapi deploy; anywhere else, the same container runs on any host that runs Docker. You also deploy whatever you added: a Celery worker, Redis or RabbitMQ, and running migrations with Alembic.
Rails 8 ships with Kamal, which installs Docker on a plain Linux server and deploys the app with zero downtime, with Thruster in front of Puma. With Solid Queue and Solid Cache, the whole API, jobs included, runs as the app plus PostgreSQL on one small server.
Both containerize well; the Docker course covers a production setup.
AI and ML features
This is FastAPI's strongest reason to exist in 2026. Model libraries, vector databases, evaluation tools and every LLM provider's SDK are Python first. A FastAPI service can load a model in-process, call providers with their official async clients, and stream tokens back:
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
class Prompt(BaseModel):
text: str
@app.post("/chat")
async def chat(prompt: Prompt):
async def events():
async for chunk in llm.stream(prompt.text): # your provider's async streaming client
yield f"data: {chunk}\n\n"
return StreamingResponse(events(), media_type="text/event-stream")Rails can do this too: RubyLLM covers the major providers, ActionController::Live streams responses, and the neighbor gem adds vector search on pgvector. For calling hosted models, that is enough. For anything that runs models, fine-tunes them or uses the Python data stack, the code belongs in Python. See vector search in Postgres for the database side in either.
Using both
Many teams do not choose. Rails runs the product: users, billing, the admin, emails and the main API. A FastAPI service runs the Python work: recommendations, document processing, LLM pipelines. Rails calls it over HTTP, or hands it work through a queue. Each side stays in the language that suits it, and the FastAPI service stays small enough that its missing batteries do not matter.
Hiring and community
Python is one of the most used languages in the world, and FastAPI has become one of its most popular web frameworks, so finding developers who know it is easier than finding Rails developers in most markets. Many of them come from data and ML backgrounds rather than web back ends, so check for experience with databases, migrations and running services in production.
Ruby's pool is smaller but experienced, and Rails conventions mean a new developer finds their way around an unfamiliar Rails codebase quickly. A FastAPI codebase reflects the choices of whoever set it up, so its structure varies more between projects.
Mistakes that hurt in each
In FastAPI:
- Blocking calls in
async defhandlers. A sync database driver orrequestsin an async route freezes the whole worker. Use async libraries, or plaindef. - Using
BackgroundTasksfor work that must happen. It has no retries and dies with the process. Use a real queue for emails, payments and anything else that matters. - Returning ORM objects without a response model. Without
response_modelor a return type, internal fields can end up in the JSON. - Upgrading FastAPI without reading the notes. Minor 0.x releases can change behavior. Pin the version and upgrade on purpose.
- No structure past twenty routes. Split into
APIRoutermodules with shared dependencies early, beforemain.pybecomes the whole app.
In Rails:
render json: recordeverywhere. It serializes every column, including ones you add later. Use a serializer oras_json(only:)from the start.- No API docs. Without rswag or similar, the API's only description is the code. Add it before the first outside consumer.
- N+1 queries in JSON endpoints. Turn on
strict_loadingin development, andincludeswhat the response needs. - Puma sized wrong. Each worker holds the whole app in memory; size workers to RAM and threads to how much requests wait on I/O.
How to choose
| Choose | When |
|---|---|
| FastAPI | The API is the product, and outside developers or typed front ends depend on its contract |
| FastAPI | The service runs ML models, LLM pipelines or other Python code |
| FastAPI | Requests mostly wait on other services, and you need many in flight per server |
| FastAPI | The team writes Python and is comfortable choosing and wiring libraries |
| Rails | The API is the back end of a full product with users, admin, emails, jobs and uploads |
| Rails | A small team must build and run everything, ideally on one server and a database |
| Rails | You want conventions, so any Rails developer can work on the code |
| Rails | Background jobs must be reliable without running Redis or RabbitMQ |
| Both | A Rails product needs Python AI or data work: put that in a FastAPI service |
If neither column clearly wins, choose the language your team writes best.
Questions that come up
Is FastAPI faster than Rails?
On an empty endpoint, yes, clearly. In a real API, the difference shrinks to what your database and upstream services cost, and both are fast enough. FastAPI's real advantage is concurrency for I/O-bound requests, not raw speed.
Is FastAPI production-ready if it is still version 0.x?
Yes. It is widely used in production. The 0.x version means minor releases can include breaking changes, so pin it, read the release notes, and keep tests that cover your endpoints.
Can Rails do async like FastAPI?
Not in the same way. Rails uses threads, which handle typical API load well. For many long-lived connections, such as WebSockets, it has Action Cable, and the Falcon server brings fiber-based concurrency to Ruby, but async request handling is not how most Rails apps run.
Is FastAPI a replacement for Django or Rails?
Only for APIs. FastAPI has no ORM, admin, migrations or job system of its own. If you want Python with those included, look at Django with Django Ninja, which brings FastAPI-style typed APIs to Django.
Which is easier to learn?
FastAPI is quicker to start: a typed endpoint with docs takes minutes, and its tutorial is excellent. Rails takes longer to learn, because there is more of it, but a beginner gets a complete, secure back end without having to pick a dozen libraries.
Can I generate a TypeScript client from either?
From FastAPI directly, because the OpenAPI schema is always there. From Rails, once you have added rswag or another OpenAPI generator.
Sources and docs
- FastAPI documentation and release notes
- FastAPI: dependencies, background tasks and testing
- FastAPI Cloud deployment
- Pydantic documentation
- SQLAlchemy 2.0 asyncio and Alembic autogenerate
- Rails 8.1 release announcement
- Using Rails for API-only applications
- Active Job basics and Rails security guide
- Rails, Ruby and Python release and support dates on endoflife.date