Blog

Building a REST API with Claude Code

How to use Claude Code to scaffold and ship a production-ready REST API: spec endpoints first, generate models and routes, handle auth, validation, and tests.

Phos Team ·
claude code

API scaffolding is one of the clearest wins for Claude Code in a developer’s workflow. If you are not yet familiar with the tool, the what Claude Code is overview covers the basics.

For a structured path through the full development workflow, the Claude Code course covers the practices that keep generated code production-worthy. The mechanical parts of an API build (route definitions, request validation, error handling, test stubs) follow consistent patterns that Claude Code handles fluently.

The result is a working API skeleton in hours rather than days.

The workflow that produces clean, maintainable APIs is not “describe your API and hope.” It is a structured sequence: spec your endpoints before you generate a single line of code, then build in layers.

The quality of a Claude Code-generated API is almost entirely determined by the quality of the endpoint specification you provide before prompting. A well-structured spec produces idiomatic, testable code. A vague description produces code that works in the demo and breaks in production.


Why Claude Code accelerates API development

Pattern recognition at the route level

REST API patterns are well-defined and heavily represented in Claude Code’s training data. CRUD routes, pagination, filtering, sorting, error response shapes, middleware chains: Claude Code has seen thousands of idiomatic implementations in every major framework.

This means the generated code tends to be idiomatic rather than invented. A FastAPI route with Pydantic validation, a proper response model, and a dependency-injected database session is what Claude Code produces by default when you give it a clear endpoint spec.

You are not steering it away from bad patterns. It defaults to good ones.

Framework fluency

Claude Code is particularly strong with Express (Node.js), FastAPI (Python), and Rails (Ruby). It knows the ecosystem tooling for each:

  • Express: zod for validation, Prisma ORM integration.
  • FastAPI: pydantic models, auto-generated OpenAPI docs.
  • Rails: ActiveRecord patterns, strong migration generation.

Generated code uses the framework’s conventions rather than fighting them.


Choosing your framework

FrameworkBest forStrengths with Claude Code
Express (Node.js)JavaScript teams, rapid prototyping, flexible architectureMiddleware patterns, Zod validation, Prisma ORM integration
FastAPI (Python)Data-heavy APIs, ML integration, Python teamsPydantic models generate cleanly, OpenAPI docs auto-generated
Rails (Ruby)Full CRUD applications, convention-heavy teamsActiveRecord, resource routing, strong migration generation

If your team does not have a strong language preference, FastAPI is worth considering for new projects. The automatic OpenAPI documentation generation from Pydantic models means Claude Code produces both working routes and accurate documentation in the same generation step.


The API build workflow

Step 1: Spec your endpoints first

Before opening Claude Code, write an endpoint specification. This does not need to be a formal OpenAPI document.

A Markdown file with the following for each endpoint is sufficient:

  • Method and path. The HTTP method and route (e.g., POST /users).
  • Request shape. Body or query parameters with types.
  • Response shape. The returned object with types.
  • Auth requirement. Public, authenticated, or admin.
  • Business logic. A two-sentence summary of what the endpoint does.

This file is your prompt context. A Claude Code session that starts with a complete endpoint spec generates accurate, coherent route code.

A session that starts with build me a user management API generates something that looks like it works but requires significant rework.

Step 2: Generate your data models

With your spec in hand, prompt Claude Code to generate the data models first. For example: Read ENDPOINTS.md and generate Pydantic models (or Zod schemas, or ActiveRecord models) for all the entities in the spec. Include validation rules as described.

Review the generated models carefully. These are the foundation everything else builds on.

Wrong field types or missing validation rules here become bugs in every route that uses them.

Step 3: Scaffold routes and controllers

Once the models are confirmed, generate the routes. Ask Claude Code to create one route file per resource group.

Breaking the generation into resource groups (users, products, orders) rather than generating the whole API at once makes each output reviewable and testable in isolation.

Step 4: Add middleware

Middleware handles the cross-cutting concerns: authentication, rate limiting, request logging, error formatting. Prompt Claude Code to generate middleware after the routes are in place, not before.

The route structure informs what the middleware needs to handle.

Ask for each middleware piece separately: auth middleware first, then error handling, then logging. Each is testable in isolation.

Step 5: Generate tests

Ask Claude Code to generate test stubs for every route. Specify your test framework (Jest, Pytest, or RSpec) and what each test should cover:

  • Happy path. The expected successful response.
  • Validation failure. Invalid or missing request fields.
  • Auth failure. Missing or invalid credentials.
  • Not-found. Requests for non-existent resources.

Claude Code generates test structure well. You will still need to fill in realistic fixture data and review the assertions, but the scaffolding eliminates the blank-page problem for test writing.

For a deeper look at testing approaches, see the guide on automated testing.


Handling authentication

Auth in a REST API has two parts Claude Code handles well and one part that requires your judgment.

What Claude Code handles well: JWT generation and validation middleware, session token storage patterns, OAuth flow scaffolding, role-based route protection.

What requires your judgment: whether JWT or sessions are right for your use case, your token expiry strategy, your refresh token approach, and how you handle token revocation. These are architecture decisions with security implications that depend on your specific threat model.

A good prompt for auth middleware: Generate JWT authentication middleware for Express. Include: token verification, role extraction, user attachment to request object, and a 401 response for invalid tokens. Use the jose library.


Handling validation

Request validation is mechanical work Claude Code does well. The key is specifying validation rules in your endpoint spec before prompting.

For each endpoint, specify:

  • Field requirements. Required vs. optional fields.
  • Type constraints. string, number, UUID, email.
  • Value constraints. Length limits, min/max values.
  • Nested objects. Validation requirements for nested structures.

Claude Code will generate the validation schema from these specifications. Generated validation catches the obvious cases reliably.

Review for business-logic validation (is this date in the future? does this user own this resource?) which Claude Code may miss without explicit specification.


Production-ready API checklist

AreaWhat to verifyClaude Code generates?
Input validationAll request fields validated before processingYes, with good spec
Error response shapeConsistent error format across all routesYes, with middleware
AuthenticationProtected routes verified, public routes documentedYes
Rate limitingLimits configured for public endpointsPartial, needs configuration
Database connection poolingPool configured for production loadNeeds manual review
Environment variable handlingNo secrets in code, env vars documentedYes
LoggingStructured request/response loggingYes
Health check endpoint/health returns service statusYes
API documentationOpenAPI spec generated or maintainedYes (FastAPI auto, others partial)
Test coverageTests exist for all routesStubs yes, coverage needs review

Frequently asked questions

Should I generate the whole API at once or build it route by route?

Build route group by route group. Generating the entire API in one prompt produces code that is harder to review, harder to test incrementally, and more likely to contain inconsistencies between route groups.

One resource per generation session is a sustainable pace that produces more reliable output.

How does Claude Code handle database migrations?

Claude Code generates migrations well for prisma, alembic (FastAPI), and ActiveRecord (Rails). Always review generated migrations before running them against any database with data.

Generated migrations handle schema creation accurately but may miss index optimization or constraint ordering for complex schemas.

Can Claude Code generate OpenAPI documentation from my routes?

Yes, with varying quality by framework. FastAPI generates accurate OpenAPI docs automatically from Pydantic models, so Claude Code-generated FastAPI routes come with documentation built in.

For Express, you can ask Claude Code to generate a swagger.yaml from your route definitions, but the output requires review for accuracy. The guide on API documentation generation covers this in more depth.

What is the most common error in Claude Code-generated API code?

Missing error handling in async route handlers. Claude Code generates the happy path reliably.

The async error propagation (uncaught promise rejections, unhandled database errors) is where generated code most often needs manual hardening. Review every async route for proper try/catch coverage and error response formatting.


Ready to ship your API?

A well-specced Claude Code API build produces a working, testable API skeleton in a day. The mechanical work (route definitions, validation schemas, middleware wiring, test stubs) is done.

What remains is the judgment work: security review, performance tuning, and the business-logic edge cases only you know. Once the API is containerized for deployment, the Docker and Kubernetes guide covers the production infrastructure side.

The API teams that use Claude Code most effectively treat it as a pair programmer for the mechanical work, not an autonomous engineer. They review every generated file, they test every route, and they own the architecture.

Path one: do it yourself. Write your endpoint spec today. Five endpoints, clearly specified with request/response shapes and auth requirements. Run the models-first workflow in Claude Code and compare the generated code to what you would have written. That comparison shows you where Claude Code saves time and where you need to review closely.

Path two: work with Phos AI Labs. If you want senior engineering oversight on your API build from spec through deployment, including connecting the API to automated pipelines via AI-Native Operations, Phos AI Labs runs structured API build engagements. Start with a conversation.

Related articles

The fastest way to know whether we're the right fit, is a conversation.

STEP 1/2 · ABOUT YOU