DEV Community

Cover image for Is there a FastAPI for TypeScript? A NestJS guide for FastAPI developers
Kamil Mysliwiec for NestJS

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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 {}
Enter fullscreen mode Exit fullscreen mode

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. ParseUUIDPipe or ParseIntPipe converts and checks one.
  • POST answers 201 by default and everything else 200; @HttpCode() is your status_code.
  • raise HTTPException(404) becomes throw 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)
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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,
  ) {}
}
Enter fullscreen mode Exit fullscreen mode

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 });
  }
}
Enter fullscreen mode Exit fullscreen mode

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 });
Enter fullscreen mode Exit fullscreen mode

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 your Depends(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.
  • TokenService issues short-lived access tokens and rotating refresh tokens. PasswordHasher hashes with scrypt, 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');
  }
}
Enter fullscreen mode Exit fullscreen mode

A check that needs only the user goes on the route as @Can(OrderPolicy, 'refund'). A check that needs the record goes in the service once it's loaded, as authorizationService.authorize(OrderPolicy, 'view', user, order), which throws a 403 when the policy says no. And like authentication, the authorization guard denies a route that declares no check at all.

Settings

Here's a pydantic-settings class:

# settings.py
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env")
    database_url: PostgresDsn
    openai_api_key: SecretStr
    debug: bool = False
Enter fullscreen mode Exit fullscreen mode

@nestjs/config does the same with a schema, and a missing or malformed variable stops the app at startup:

// app.module.ts
ConfigModule.forRoot({
  isGlobal: true,
  validationSchema: z.object({
    DATABASE_URL: z.url(),
    OPENAI_API_KEY: z.string().min(1),
    DEBUG: z.stringbool().default(false),
  }),
}),
Enter fullscreen mode Exit fullscreen mode

Where you'd write Depends(get_settings), a provider injects ConfigService and calls get() or getOrThrow().

Databases and migrations

Nest has no ORM of its own. Drizzle, where the schema is TypeScript and queries read like SQL, is the closest thing to SQLAlchemy Core. TypeORM, with decorated entity classes, is closer to SQLModel. Alembic's revision --autogenerate becomes npx drizzle-kit generate, and upgrade head becomes npx drizzle-kit migrate.

The database is registered once and injected where it's used:

// orders/orders.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { orders } from '../database/schema.js';

@Injectable()
export class OrdersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  async findForCustomer(id: string, customerId: string) {
    const [order] = await this.db
      .select()
      .from(orders)
      .where(and(eq(orders.id, id), eq(orders.customerId, customerId)));
    return order;
  }
}
Enter fullscreen mode Exit fullscreen mode

One thing you'll enjoy: every database driver in Node.js is asynchronous. There's no sync engine and async engine to choose between, and no run_in_threadpool for the library that never got an async version. A transaction is a callback, this.db.transaction(async (tx) => ...), that commits when it resolves and rolls back when it throws.

Background tasks, Celery and lifespan

BackgroundTasks runs a function after the response is sent, in the same process. You could do the same in Node by not awaiting a promise, and I'd talk you out of it: the work is lost if the process stops, and an error has nowhere to go. Use a queue. @nestjs/bullmq runs jobs on Redis with retries, so it covers both BackgroundTasks and Celery or ARQ:

// invoices/invoice.processor.ts
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';

@Processor('invoices')
export class InvoiceProcessor extends WorkerHost {
  async process(job: Job<{ orderId: string }>) {
    // ...
  }
}
Enter fullscreen mode Exit fullscreen mode

A service adds a job to the queue it injects, where you'd call background_tasks.add_task():

await this.invoices.add('generate', { orderId: order.id });
Enter fullscreen mode Exit fullscreen mode

Scheduled jobs use @Cron() from @nestjs/schedule. And lifespan becomes lifecycle hooks on any provider: onModuleInit() runs before the app starts listening, and onApplicationShutdown() runs on shutdown once you call app.enableShutdownHooks().

Streaming, SSE and AI backends

A lot of FastAPI apps exist to put a language model behind an API, so this part matters.

StreamingResponse over an async generator becomes a handler that is an async generator. Each value it yields goes out as soon as the client can take it:

@Get('story')
async *story() {
  for await (const token of this.llm.stream('Tell me a story')) {
    yield token;
  }
}
Enter fullscreen mode Exit fullscreen mode

A handler can also return a ReadableStream or a web Response, such as the AI SDK's toTextStreamResponse(), and @Sse() sends each value of an Observable as a server-sent event.

For the model calls themselves, @nestjs/ai registers models by name and injects AiService, with retries, timeouts, fallback models, budgets and answers validated by a schema, on top of the AI SDK, so Claude, GPT, Gemini and the rest all work:

const { text } = await this.ai.generateText({
  model: 'fast',
  instructions: 'Draft a short, friendly reply to the customer.',
  prompt: email,
});
Enter fullscreen mode Exit fullscreen mode

Mark a provider's method @AgentFunction() and the model can call it as a tool, through the same guards and pipes as your routes, as the user it's acting for. @nestjs/mcp serves the same methods as an MCP server, if you were reaching for FastAPI-MCP.

OpenAPI

Here's the first of the two things FastAPI does for free: /docs just exists. In Nest, it's @nestjs/swagger and three lines in main.ts:

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

const config = new DocumentBuilder().setTitle('Orders API').build();
SwaggerModule.setup('docs', app, () =>
  SwaggerModule.createDocument(app, config),
);
Enter fullscreen mode Exit fullscreen mode

Swagger UI is then at /docs. Zod schemas on @Body(), @Query() and @Param() become request bodies and parameters in the document, and the CLI plugin reads DTO classes and handler return types from the TypeScript source, so most routes need no extra decorators. Responses the plugin can't infer get an @ApiResponse(). It's close to what you had, and it's not zero, so I'd rather you know.

Testing

TestClient with dependency_overrides becomes a testing module with overrideProvider(), and Supertest for the requests:

// test/orders.e2e-spec.ts
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { vi } from 'vitest';
import { AppModule } from '../src/app.module.js';
import { OrdersRepository } from '../src/orders/orders.repository.js';

describe('Orders', () => {
  let app: INestApplication;
  const ordersRepository = { findForCustomer: vi.fn() };

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(OrdersRepository)
      .useValue(ordersRepository)
      .compile();
    app = moduleRef.createNestApplication();
    await app.init();
  });

  afterAll(() => app.close());

  it('answers 404 for an unknown order', async () => {
    ordersRepository.findForCustomer.mockResolvedValue(undefined);
    await request(app.getHttpServer())
      .get('/orders/7c9e6679-7425-40de-944b-e07fc1f90ae7')
      .expect(404);
  });
});
Enter fullscreen mode Exit fullscreen mode

overrideProvider() replaces a provider everywhere it's injected, the same thing an entry in dependency_overrides does. Unit tests are even simpler: a provider is a plain class, so new OrdersService(fakeRepository, fakeMailer) works.

Shipping it

A FastAPI app ships as Python code behind uvicorn or Gunicorn with uvicorn workers. A Nest app ships as compiled JavaScript plus its node_modules, almost always in a container:

FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "--enable-source-maps", "dist/main.js"]
Enter fullscreen mode Exit fullscreen mode

Three things to check:

  • Graceful shutdown. Call app.enableShutdownHooks() in main.ts, so your shutdown hooks run on SIGTERM.
  • The process gets the signal. Use the exec form, CMD ["node", ...], not npm start, which doesn't reliably forward signals.
  • One process per core. uvicorn --workers 4 starts four processes, and Node is the same: one process uses one core for your code. Run several containers, or several processes, behind the load balancer.

Moving over without a rewrite

You don't have to port a FastAPI service to start using Nest:

  • Start with a new service. The next one gets written in Nest, behind the same gateway, and a guard can verify the same JWTs your FastAPI services issue, for example with @nestjs/jwt.
  • Share the contract. FastAPI already publishes /openapi.json; generate a TypeScript client from it for the Nest service, and the other way round with @nestjs/swagger.
  • Keep the model work where it is, if it's heavy. If a service does real ML in Python (embeddings computed locally, a model loaded into memory), keep it in Python behind an API and let Nest call it. Nest is a good fit for the API around the model calls, not for running PyTorch.

What's actually different

The syntax takes a week. These take longer.

Types don't validate. I've said it twice and I'll say it once more, because it's the one that bites FastAPI developers: TypeScript types are gone at runtime. Only a schema checks data from outside.

Dependencies are resolved once, not per request. FastAPI calls your dependency functions on every request. Nest creates providers when the app starts and reuses them. That's cheaper, and it means a provider must never keep per-request state in its fields. Per-request values come from handler parameters, @CurrentUser(), or AsyncLocalStorage, which follows a request through every await the way a ContextVar does.

Classes and modules, not functions. A FastAPI app can stay a flat set of functions. Nest wants controllers and providers as classes, in modules that list what they contain and export. It's more structure on day one, and it's what keeps a big codebase navigable on day five hundred.

No thread pool for sync code. FastAPI quietly runs a plain def path operation in a thread pool, so blocking code doesn't freeze the event loop. Node has no such escape hatch: all your code runs on the event loop, and a long CPU-bound loop stalls every request in the process. Move CPU work to a queue or a worker thread. Waiting on I/O is never the problem, since every driver is async.

await everything. You know this one from asyncio, with a twist: a forgotten await in Python hands you a coroutine object and a warning, while in TypeScript the code just carries on before the work has finished. The no-floating-promises lint rule catches it, and nest new turns it on.

Numbers are doubles. There's no Decimal. Keep money in integer cents, or use a decimal library and your database's numeric type, which most drivers return as a string anyway.

ES modules. A new project imports local files with a .js extension, even from .ts files, because that's the name of the compiled file. It looks wrong for about a day.

When I'd stay on FastAPI

To be fair to FastAPI: if the service sits next to data science or machine learning code, if it loads models into memory, or if your team is all Python and happy, stay. Python's ML ecosystem has no equivalent in Node, and a small FastAPI service is hard to beat for how little code it takes.

Nest is a good fit when the backend is a product API that will grow: more modules, more people, auth, a database, background jobs. And when the people building it also write the TypeScript frontend, one language from the browser to the database is worth a lot.

Getting started

npx @nestjs/cli new orders-api
cd orders-api
npm run start:dev
Enter fullscreen mode Exit fullscreen mode

Then nest g resource orders, add @nestjs/swagger and a Zod schema, and you have something to hold up against the FastAPI router in your head. The Coming from FastAPI page in the docs keeps this mapping as a reference, with a link from each row to its full chapter.

If something here doesn't match how you'd do it in FastAPI, tell me. It's written for you, and it's easy to fix.

Coming from Django instead? Here's the same tour for Django developers: Is there a Django for Node.js?.

Top comments (0)