Is there a FastAPI for TypeScript? A NestJS guide for FastAPI developers
route with a decorator, describe the body with a type, get validation and an OpenAPI document for free, and let Depends() hand each function what it needs.
Once you've worked that way, going back to a framework where you wire validation and docs by hand feels like a step backwards. So when a FastAPI team has to write TypeScript (the frontend is already TypeScript, the company standardized on Node, or you just want one language end to end), the first question is "is there a FastAPI for TypeScript?".
Nest is the closest match I know, and I'm biased, so here's the honest version. The ideas carry over almost one to one: decorator routes, schema validation, dependency injection, async everywhere, a generated OpenAPI document. The shape of the code doesn't. FastAPI is functions that declare their dependencies as parameters; Nest is classes, grouped into modules, that receive their dependencies in the constructor.
And two things FastAPI does for free take a line of setup in Nest. I'll point them out as we go. This is the tour I'd give a FastAPI team on day one: the tools, the structure, each FastAPI feature and its Nest counterpart with code on both sides, how it ships, and the differences that will actually bite.
The short version
| FastAPI | Nest |
|---|---|
uvicorn main:app --reload |
npm run start:dev |
APIRouter, include_router() |
controllers, grouped into modules |
@router.get(), @router.post() |
@Get(), @Post() |
| Pydantic request models | a Zod schema on @Body() |
response_model |
StandardSchemaSerializerInterceptor |
Depends() |
providers, injected into constructors |
Depends(get_current_user) |
@CurrentUser() from @nestjs/authentication |
app.dependency_overrides |
overrideProvider() |
HTTPException, exception handlers |
HttpException, exception filters |
CORSMiddleware |
app.enableCors() |
OAuth2PasswordBearer, scopes |
@nestjs/authentication, @nestjs/authorization |
pydantic-settings |
@nestjs/config |
| SQLAlchemy or SQLModel, Alembic | Drizzle or TypeORM, and their migrations |
BackgroundTasks, Celery, ARQ |
@nestjs/bullmq |
lifespan |
onModuleInit(), onApplicationShutdown() |
StreamingResponse, SSE |
async generators, @Sse() |
/docs |
@nestjs/swagger |
TestClient |
@nestjs/testing with Supertest |
Every row has its own section below. The docs keep the same mapping as a reference page, with a link from each row to its full chapter: Coming from FastAPI.
Your tools, translated
| FastAPI world | Nest world |
|---|---|
| Python | Node.js (a current LTS release) and TypeScript |
pip or uv, pyproject.toml |
npm, package.json |
| A virtualenv | node_modules, per project, with nothing to activate |
uvicorn |
Node.js itself: node dist/main.js |
uvicorn --reload |
npm run start:dev |
pytest |
Vitest |
mypy or pyright |
the TypeScript compiler, on every build |
| Ruff | oxlint and Prettier, set up by nest new |
| Pydantic | Zod (or Valibot, or ArkType) |
The last row is the one to remember. Pydantic is both a type and a validator. In TypeScript, those are two things, and Zod is how you get them back together.
Project layout
A FastAPI project often starts as one main.py. nest new orders-api starts you with a small src/ folder, and as the app grows, the convention is one folder per feature, each with its module, and tests next to the code:
src/
main.ts # creates the app: FastAPI() plus uvicorn
app.module.ts # the root module: your include_router() calls
orders/
orders.module.ts
orders.controller.ts # the APIRouter
orders.controller.spec.ts
orders.service.ts # what your Depends() factories built
orders.repository.ts # the queries
create-order.schema.ts # the Pydantic models
test/
orders.e2e-spec.ts
Routers become controllers
Here's a FastAPI router with two path operations, each asking for the current user and a service:
# orders/router.py
router = APIRouter(prefix="/orders", tags=["orders"])
@router.get("/{order_id}", response_model=OrderOut)
async def get_order(
order_id: UUID,
user: User = Depends(get_current_user),
orders: OrdersService = Depends(get_orders_service),
):
order = await orders.find_one(user, order_id)
if order is None:
raise HTTPException(status_code=404, detail="Order not found")
return order
@router.post("", status_code=201, response_model=OrderOut)
async def create_order(
body: CreateOrder,
user: User = Depends(get_current_user),
orders: OrdersService = Depends(get_orders_service),
):
return await orders.place(user, body)
In Nest, the router is a controller class. The prefix goes on @Controller(), each method is a path operation, and the service is injected once, into the constructor, instead of into every function:
// orders/orders.controller.ts
import { Body, Controller, Get, Param, ParseUUIDPipe, Post, } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { createOrderSchema, type CreateOrder } from './create-order.schema.js';
import { OrdersService } from './orders.service.js';
@Controller('orders')
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}
@Get(':id')
findOne(
@CurrentUser() user: User,
@Param('id', ParseUUIDPipe) id: string
) {
return this.ordersService.findOne(user, id);
}
@Post()
create(
@CurrentUser() user: User,
@Body({ schema: createOrderSchema }) body: CreateOrder,
) {
return this.ordersService.place(user, body);
}
}
The controller lives in a module, with the providers it uses, and the root module imports the feature modules the way include_router() adds routers:
// orders/orders.module.ts
import { Module } from '@nestjs/common';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';
@Module({
controllers: [OrdersController],
providers: [OrdersService],
})
export class OrdersModule {}
What to notice, coming from FastAPI:
- Route parameters are
:id, not a name in braces, and the type annotation doesn't convert them: they arrive as strings.ParseUUIDPipeorParseIntPipeconverts and checks one. - POST answers 201 by default and everything else 200;
@HttpCode()is yourstatus_code. raise HTTPException(404)becomesthrow new NotFoundException(), and you can throw it from the service, which is where I'd put it.- There's no
Depends(get_current_user)guarding the route, and it isn't missing. With@nestjs/authentication, every route is closed to anonymous requests unless it's marked@Public(). FastAPI is the other way round, and "I forgot the dependency on that one route" is a bug class you no longer have.
Pydantic becomes Zod
Here's a Pydantic model:
# orders/schemas.py
class OrderItem(BaseModel):
product_id: UUID
quantity: int = Field(ge=1, le=20)
class CreateOrder(BaseModel):
items: list[OrderItem] = Field(min_length=1)
note: str | None = Field(default=None, max_length=500)
The same model in Zod. The schema validates at runtime, and the type is inferred from it, so like a Pydantic model it's both at once:
// orders/create-order.schema.ts
import { z } from 'zod';
export const createOrderSchema = z.object({
items: z.array(
z.object({
productId: z.uuid(),
quantity: z.int().min(1).max(20),
}),
).min(1),
note: z.string().max(500).optional(),
});
export type CreateOrder = z.infer<typeof createOrderSchema>;
The controller passes it with @Body({ schema: createOrderSchema }), and one line in main.ts turns validation on for every parameter that has a schema:
app.useGlobalPipes(new StandardSchemaValidationPipe());
An invalid body gets a 400 listing every failed rule, where FastAPI answers 422. Valibot and ArkType plug in the same way, since Nest accepts any Standard Schema library.
Now the gotcha, and it's the big one for anyone coming from FastAPI. In FastAPI, the type annotation is the validation. In TypeScript, types are erased when the code compiles. @Body() body: CreateOrder with no schema compiles fine and accepts whatever JSON the client sent. The annotation checks your code, never the data. Pass a schema on every parameter that comes from outside, and the problem goes away.
response_model
response_model is what stops a password hash from leaking into a response. Nest's counterpart is StandardSchemaSerializerInterceptor, which runs the handler's return value through a schema. Since z.object() drops properties it doesn't declare, the schema works as an allowlist:
@Controller('orders')
@UseInterceptors(StandardSchemaSerializerInterceptor)
export class OrdersController {
// constructor as above
@Get(':id')
@SerializeOptions({ schema: orderResponseSchema })
findOne(
@CurrentUser() user: User,
@Param('id', ParseUUIDPipe) id: string
) {
return this.ordersService.findOne(user, id);
}
}
An array response gets the schema applied to each element. Without the interceptor, whatever the handler returns is sent as JSON as it is, so for anything with secrets in it, either select only the columns you mean to send or put a response schema on it.
Depends becomes dependency injection
This is the biggest change in how the code is shaped, so it gets the longest section. FastAPI calls your dependency functions on every request, and you compose them with Depends():
# orders/service.py
class OrdersService:
def __init__(self, db: AsyncSession, mailer: Mailer):
self.db = db
self.mailer = mailer
def get_orders_service(
db: AsyncSession = Depends(get_db),
mailer: Mailer = Depends(get_mailer),
) -> OrdersService:
return OrdersService(db, mailer)
In Nest, the class declares its dependencies in its constructor, and that's all. No factory function, and no Depends() on every route:
// orders/orders.service.ts
import { Injectable } from '@nestjs/common';
import { Mailer } from '@nestjs/mail';
import { OrdersRepository } from './orders.repository.js';
@Injectable()
export class OrdersService {
constructor(
private readonly ordersRepository: OrdersRepository,
private readonly mailer: Mailer,
) {}
}
Nest reads the constructor's parameter types when the app starts, creates one instance of each provider, and passes the same instances to everything that asks. So providers are where the things you'd keep in module-level globals or app.state go: database pools, HTTP clients, model clients.
The catch is that not every Depends() builds a service. Some read the request, some reject it, some open something and close it. Here's where each kind goes:
| A FastAPI dependency that... | In Nest |
|---|---|
| builds a service or a client | a provider, injected into constructors |
| reads the current user | @CurrentUser() from @nestjs/authentication |
| rejects the request, such as a permission check | a guard, or a policy with @Can() |
| parses or checks one parameter | a pipe |
| pulls a value out of the request | a custom parameter decorator |
opens and closes something per request (yield) |
an interceptor, or a request-scoped provider |
| opens and closes something for the app's lifetime | a provider with onModuleInit() and onApplicationShutdown() |
And the most common yield dependency of all, get_db(), usually has no counterpart. The database module holds a connection pool for the app's lifetime, and each query borrows a connection and gives it back. Request-scoped providers exist, but Nest rebuilds them, and everything that injects them, on every request, so I keep them for the rare case that needs them.
Exceptions, middleware and CORS
HTTPException becomes HttpException and its subclasses (NotFoundException, ConflictException, ForbiddenException and the rest). Throw one anywhere and Nest turns it into a JSON response with its status. Anything else becomes a 500.
@app.exception_handler() becomes an exception filter, a class whose @Catch() names the exceptions it handles:
@Catch(OrderNotFoundError)
export class OrderNotFoundFilter implements ExceptionFilter {
catch(exception: OrderNotFoundError, host: ArgumentsHost) {
const response = host.switchToHttp().getResponse();
response.status(404).json({ detail: exception.message });
}
}
Register it with app.useGlobalFilters().
Middleware works as you'd expect, and around the handler Nest has more specific places: guards decide whether the handler runs, interceptors wrap it and see its result, pipes check each argument.
CORSMiddleware is one call:
app.enableCors({ origin: ['https://shop.example.com'], credentials: true });
Security
FastAPI gives you building blocks: OAuth2PasswordBearer reads a bearer token, and a get_current_user you write decodes it and loads the user. Hashing passwords, issuing tokens and storing sessions are libraries you pick.
@nestjs/authentication ships those parts:
- Closed by default. Every route requires a signed-in user once the module is registered.
@Public()opens one. @CurrentUser()is yourDepends(get_current_user).- Credential providers read a bearer token, a session cookie or an API key, and load the user through your code.
- Users stay your own table.
TokenServiceissues short-lived access tokens and rotating refresh tokens.PasswordHasherhashes withscrypt, and an unknown email takes as long to check as a wrong password.- The flows you'd otherwise build: server-side sessions, email verification, password reset links, TOTP two-factor authentication, magic links, sign-in with Google and other OpenID Connect providers, and API keys that users create and revoke.
OAuth2 scopes check what a token allows. @nestjs/authorization checks what a user may do, with policies:
// orders/order.policy.ts
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';
import type { Order } from './order.js';
@Policy()
export class OrderPolicy {
view(user: User | null, order: Order) {
if (!user) {
return false;
}
return user.roles.includes('staff') || order.customerId === user.id;
}
refund(user: User | null) {
return !!user?.roles.includes('staff');
}
}
A ch
Comments
No comments yet. Start the discussion.