Skip to content
DevPlainly
Comparisons

FastAPI vs Express: We Built the Same API in Both

FastAPI vs Express with real numbers: the same REST API in both, the code side by side, validation, automatic docs, and a benchmark with one surprising result.

Published
Reading time
9 min read
Contents
  1. The short answer
  2. We built the same API in both
  3. The code, side by side
  4. FastAPI
  5. Express
  6. Validation and errors
  7. Automatic documentation
  8. Performance: the async def surprise
  9. Language and ecosystem
  10. When to choose each
  11. Tips for choosing
  12. How to run each one
  13. FAQ
  14. Is FastAPI faster than Express?
  15. Should I always use async def in FastAPI?
  16. Is FastAPI good for beginners?
  17. Can I use TypeScript with Express?
  18. Is Express still maintained?
  19. Further reading

FastAPI and Express are two of the most popular ways to build a backend API: FastAPI in Python, Express in Node.js. Comparisons usually turn into "Python vs JavaScript" arguments. This one starts with a test instead: we built the same REST API in both, sent them the same requests, and measured what happened.

The result has one surprise that changes how you should write FastAPI code, and it's worth knowing even if you never pick Express.

Nil's note

I've used both in class, but FastAPI is the one I remember, and the one I liked: the code feels logical, the validation is just a Python class, and the documentation page appears on its own. Express I barely remember, which says something too. So for this comparison I didn't trust my preference: we built the same API in both and measured them.

The short answer

  • Choose FastAPI if you work in Python, want validation and API documentation without extra work, or your API sits next to data science or AI code.
  • Choose Express if you work in JavaScript or TypeScript, want the same language on the frontend and backend, or need the huge npm ecosystem.
  • Performance is not the deciding factor. Written the right way, both handled the same load in our test.

We built the same API in both

The API manages a task list: create, list, read, update and delete tasks, with a title between 1 and 100 characters. Both versions keep the tasks in memory, so the test measures the frameworks, not a database. We used FastAPI 0.162 on Python 3.13 and Express 5.3 with Zod 4 for validation on Node.js 22, in November 2026.

MeasureFastAPIExpress + Zod
Lines of code5248
Dependencies installed15 packages, 18 MB66 packages, 13 MB
Request validationBuilt in (Pydantic)Add a library (Zod)
Interactive API docsAutomatic, at /docsNot included
GET /tasks/abc (invalid id)422, with an explanation404, unless you check it yourself
Requests per second, GET /tasks/52,732 with def, 7,555 with async def8,371
Requests per second, POST /tasks2,439 with def, 5,991 with async def7,205

The benchmark used autocannon with 50 connections for 10 seconds, one process for each server, on the same 4-core machine. The numbers are for comparing the two, not a promise of what your server will do.

The code, side by side

FastAPI

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI(title="Tasks API")


class TaskIn(BaseModel):
    title: str = Field(min_length=1, max_length=100)
    done: bool = False


class Task(TaskIn):
    id: int


tasks: dict[int, Task] = {}
next_id = 1


@app.get("/tasks")
def list_tasks() -> list[Task]:
    return list(tasks.values())


@app.post("/tasks", status_code=201)
def create_task(data: TaskIn) -> Task:
    global next_id
    task = Task(id=next_id, **data.model_dump())
    tasks[task.id] = task
    next_id += 1
    return task


@app.get("/tasks/{task_id}")
def get_task(task_id: int) -> Task:
    if task_id not in tasks:
        raise HTTPException(404, "Task not found")
    return tasks[task_id]


@app.put("/tasks/{task_id}")
def update_task(task_id: int, data: TaskIn) -> Task:
    if task_id not in tasks:
        raise HTTPException(404, "Task not found")
    tasks[task_id] = Task(id=task_id, **data.model_dump())
    return tasks[task_id]


@app.delete("/tasks/{task_id}", status_code=204)
def delete_task(task_id: int) -> None:
    if tasks.pop(task_id, None) is None:
        raise HTTPException(404, "Task not found")

Express

import express from "express";
import { z } from "zod";

const app = express();
app.use(express.json());

const TaskIn = z.object({
  title: z.string().min(1).max(100),
  done: z.boolean().default(false),
});

const tasks = new Map();
let nextId = 1;

app.get("/tasks", (req, res) => {
  res.json([...tasks.values()]);
});

app.post("/tasks", (req, res) => {
  const result = TaskIn.safeParse(req.body);
  if (!result.success) return res.status(422).json(z.flattenError(result.error));
  const task = { id: nextId++, ...result.data };
  tasks.set(task.id, task);
  res.status(201).json(task);
});

app.get("/tasks/:id", (req, res) => {
  const task = tasks.get(Number(req.params.id));
  if (!task) return res.status(404).json({ detail: "Task not found" });
  res.json(task);
});

app.put("/tasks/:id", (req, res) => {
  const id = Number(req.params.id);
  if (!tasks.has(id)) return res.status(404).json({ detail: "Task not found" });
  const result = TaskIn.safeParse(req.body);
  if (!result.success) return res.status(422).json(z.flattenError(result.error));
  const task = { id, ...result.data };
  tasks.set(id, task);
  res.json(task);
});

app.delete("/tasks/:id", (req, res) => {
  if (!tasks.delete(Number(req.params.id))) return res.status(404).json({ detail: "Task not found" });
  res.status(204).end();
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));

The length is almost the same, but the work is split differently:

  • In FastAPI, the types do the work. data: TaskIn reads the JSON body, validates it and gives you an object. task_id: int converts the URL parameter and rejects anything that isn't a number. The return type -> Task shapes the response. You declare what you want and FastAPI checks it.
  • In Express, you do it step by step. You parse the body with express.json(), validate it with Zod, convert the id with Number() and decide every status code yourself. More code to write, but nothing happens that you can't see.

Validation and errors

Send both APIs a task with an empty title and both answer 422, but with different shapes:

// FastAPI
{"detail": [{"type": "string_too_short", "loc": ["body", "title"],
  "msg": "String should have at least 1 character", "input": "", "ctx": {"min_length": 1}}]}

// Express + Zod
{"formErrors": [], "fieldErrors": {"title": ["Too small: expected string to have >=1 characters"]}}

Two differences we only found by testing:

  • Invalid ids. GET /tasks/abc returns 422 in FastAPI, because task_id: int is validated automatically. In Express, Number("abc") is NaN, so the lookup fails and the API answers 404. It isn't wrong, but if you want a proper error, you have to validate the parameter yourself.
  • Pydantic converts values when it can. We sent {"done": "yes"}. Zod rejected it: "expected boolean, received string". Pydantic accepted "yes" as true, because its default "lax" mode converts common values like "yes", "1" and "true". Usually that's convenient; if you need exact types, turn on strict mode with model_config = ConfigDict(strict=True) in the model.

Automatic documentation

This is FastAPI's best feature. Start the server and open http://localhost:8000/docs: there's an interactive page listing every endpoint, with the fields each one expects and a button to try it. It's generated from your code, so it's never out of date. The same information is available as an OpenAPI file at /openapi.json, which other tools can use to generate clients.

Express has nothing similar out of the box. You can add it with packages like swagger-ui-express, but you write or generate the API description yourself.

Performance: the async def surprise

Our first FastAPI run was about three times slower than Express. The reason wasn't Python: it was one word.

FastAPI runs functions declared with plain def in a thread pool, so they can safely call slow, blocking code. That costs time on every request. Functions declared with async def run directly on the event loop, which is how Node.js works too. Changing def to async def in our five functions took FastAPI from 2,732 to 7,555 requests per second on the same endpoint, close to Express's 8,371.

The rule, from FastAPI's own docs:

  • Use async def when everything inside is fast or awaited: async database drivers, httpx, in-memory work.
  • Use def when you call blocking code: requests, time.sleep, or a synchronous database driver. Inside async def, that code would freeze the whole server while it waits.

One more trap we hit: running FastAPI with several workers (--workers 4) starts separate processes, and each one has its own memory. Our in-memory tasks existed in one worker and not the others, so most requests returned 404. Real apps keep their data in a database, which all workers share; the same applies to Node.js clusters.

Language and ecosystem

  • FastAPI brings Python's ecosystem: pandas, NumPy, machine learning libraries, and the official SDKs of most AI providers. If your API serves a model or processes data, it can live in the same codebase.
  • Express brings npm, the largest package registry there is, and the same language as your frontend. A team that writes React or Angular can share types and code with the backend, especially with TypeScript.
  • Real-time features like WebSockets work in both.

When to choose each

SituationBetter fit
You know Python, or the API uses data or AI librariesFastAPI
You want validation and docs with no extra setupFastAPI
Your team writes JavaScript or TypeScript everywhereExpress
You want full control and a minimal coreExpress
A large app that needs more structureNestJS (Node.js) or FastAPI with a clear project layout

Tips for choosing

  1. Pick the language you're stronger in. A well-written API in the language you know beats a messy one in a "faster" framework.
  2. If you choose FastAPI, decide def or async def on purpose. Use async def with async libraries, def with blocking ones, and don't mix them up.
  3. If you choose Express, add validation from day one. Zod or a similar library keeps bad data out; without it, Express trusts whatever arrives.
  4. Try the docs page. Build a small API in FastAPI and open /docs. For many people, that page alone settles the decision.
  5. Plan the database early. In-memory data is fine for learning, but it disappears on restart and isn't shared between workers. See SQLite vs PostgreSQL and PostgreSQL vs MySQL.

How to run each one

# FastAPI
python -m venv .venv && source .venv/bin/activate
pip install "fastapi[standard]"
fastapi dev main.py          # http://localhost:8000/docs
# Express
npm init -y && npm pkg set type=module
npm install express zod
node --watch index.js        # http://localhost:3000/tasks

To ship either one in a container, the Dockerfile generator has presets for FastAPI and Express.

FAQ

Is FastAPI faster than Express?

In our test, Express was slightly faster, but only when FastAPI used async def. With plain def functions, FastAPI handled about a third of the requests. In real apps, the database is usually the bottleneck, not the framework.

Should I always use async def in FastAPI?

Only when everything inside the function is non-blocking. If you call a library that blocks, like requests or a synchronous database driver, use def so FastAPI runs it in a thread and the server stays responsive.

Is FastAPI good for beginners?

Yes. Type hints make the code read like a description of the API, validation is automatic, and the /docs page lets you test every endpoint from the browser without Postman or curl.

Can I use TypeScript with Express?

Yes, and many teams do. With TypeScript and Zod together, you can get validated, typed request bodies close to what FastAPI gives you with Pydantic.

Is Express still maintained?

Yes. Express 5, the first new major version in about ten years, was released in 2024, and Express is still one of the most downloaded packages on npm.

Further reading

Written by Nil Martinez

Developer · DAM & DAW student

Developer studying multiplatform (DAM) and web (DAW) application development. I work every day with TypeScript, Angular, React, Java, Python, FastAPI, MySQL and Docker on Kubuntu, and I write about the tools I actually use.

How I test and write each guideGitHub

Keep reading