Skip to content
All projects

TypeScript AI API

Production-ready Fastify REST API in TypeScript, integrated with the OpenAI API to deliver intelligent-assistant capabilities behind clean, typed endpoints.

Production · TypeScript · Backend · AI API · 2024

Fastify, TypeScript, OpenAI API, Node.js, Zod, Vitest

  • TypeScript AI API screenshot 1

The problem

Teams integrating an LLM into a product need a small, fast, well-tested API layer in front of OpenAI — with auth, rate limiting, and validation already handled — rather than wiring raw SDK calls into every service.

My role

Responsibilities

Built the API solo: route design, the AiService wrapper around OpenAI, the auth middleware, and the full Vitest test suite.

Main workflows

  1. 1.Client authenticates every AI request with an X-API-Key header
  2. 2.POST /ai/chat proxies a multi-turn conversation to an OpenAI GPT model and returns the assistant's reply plus token usage
  3. 3.POST /ai/summarize condenses long text into a paragraph or bullet-point summary
  4. 4.GET /health reports API and AI service status for uptime checks

Architecture

  1. Client app
  2. Fastify REST API (TypeScript)
  3. OpenAI API

Backend API service with no UI to screenshot. See the source for endpoint documentation.

  • Fastify chosen over Express for 2–3x throughput, native TypeScript support, and schema-based validation
  • Zod schemas validate every request body at runtime, mirroring the TypeScript types with clearer error messages than raw JSON Schema
  • Service layer pattern: AiService is injected into routes, so it's mockable in tests without real HTTP calls to OpenAI
  • App factory pattern (buildApp()) returns a fresh Fastify instance per test, avoiding port conflicts in the suite

Security and deployment

  • X-API-Key header required on every AI route
  • 60 requests/min per IP via @fastify/rate-limit
  • Security headers via @fastify/helmet
  • Multi-stage Dockerfile + docker-compose for containerized deployment; auto-generated Swagger docs at /docs

Results

Full unit + integration test suite via Vitest, covering routes, the service layer, and error handling for 400/401/403/404/500.