Claude Code is Anthropic's official AI coding agent, used by developers at companies from startups to Fortune 500. Learn more →
TutorialsHow to Build an API with Claude Code
Create backend services without server-side programming knowledge. Describe your endpoints in plain English, and Claude Code generates a working API you can test and deploy.
You can build a fully functional API with Claude Code by describing your endpoints in plain English — no backend programming experience required. Claude Code generates the server, routes, data validation, and storage, letting you test locally and deploy to the internet in a single session.
This guide walks you through the entire process step by step: from writing your first prompt to deploying a live API. Claude Code, powered by Claude Opus 4.6, understands API design patterns, security best practices, and modern backend architectures out of the box — so you can focus on what your API should do, not how to code it.
What is an API?
An API (Application Programming Interface) is how software talks to other software. When you use an app on your phone, it's probably making API requests to a server somewhere.
Think of an API like a restaurant:
- The menu is the API documentation (what you can order)
- Your order is the request (what you're asking for)
- The kitchen is the server (processes your request)
- Your food is the response (what you get back)
With Claude Code, you describe the menu, and it builds the entire restaurant.
What You Can Build
Here are common types of APIs you can create:
- REST APIs — Standard web APIs that apps and websites use to communicate
- Webhook endpoints — Receive data from other services (Stripe payments, GitHub events)
- Data processing services — Accept data, transform it, return results
- Authentication services — Handle user login and registration
- Third-party integrations — Connect services together
What You'll Need
- Claude Code installed — See installation guide if you haven't set it up (available as a CLI tool or VS Code extension)
- Node.js installed — Claude will use this to run your API locally
- A folder for your project — Just an empty folder on your computer
Don't have Node.js? Ask Claude: "Help me install Node.js on my computer." It will guide you through the installation for your operating system. Claude can also build APIs in Python (Flask, FastAPI), Go, Ruby (Rails), or any other backend language—Node.js is just the example we use in this guide.
Step-by-Step: Building Your First API
Let's build an API for a simple bookmarks service. Users can save, retrieve, and delete bookmarks.
1 Create a Project Folder
Open Terminal and create a folder for your API:
mkdir bookmarks-api
cd bookmarks-api
This folder will contain all your API files.
2 Start Claude Code
Run Claude Code in your project folder:
claude
You'll see Claude's prompt, ready for instructions.
3 Describe Your API
Tell Claude what you want to build:
Create a REST API for a bookmarks service using Express.js:
Endpoints needed:
- GET /bookmarks - list all bookmarks
- GET /bookmarks/:id - get a single bookmark
- POST /bookmarks - create a new bookmark (url, title, tags)
- PUT /bookmarks/:id - update a bookmark
- DELETE /bookmarks/:id - delete a bookmark
Requirements:
- Store data in a JSON file for simplicity
- Validate that URL is required when creating
- Return proper HTTP status codes
- Include error handling
Press Enter and watch Claude create your API.
4 Review What Claude Creates
Claude will generate several files:
package.json— Project configuration and dependenciesserver.jsorindex.js— The main API serverdata/bookmarks.json— Where bookmarks are stored
You don't need to understand the code. Claude handles the structure.
5 Start Your API
Ask Claude to run the server:
Install dependencies and start the server
Claude will run npm install and start the server. You'll see something like:
Server running on http://localhost:3000
6 Test Your API
Ask Claude to test the endpoints:
Test the API by:
1. Creating a new bookmark
2. Listing all bookmarks
3. Getting that bookmark by ID
4. Updating it
5. Deleting it
Claude will make requests and show you the responses.
Want the complete setup from scratch? I walk through every step in my free guide — including API projects like this one.
Understanding API Endpoints
Endpoints are the URLs your API responds to. Each one does something different:
HTTP Methods
- GET — Retrieve data (like viewing bookmarks)
- POST — Create new data (like adding a bookmark)
- PUT — Update existing data (like editing a bookmark)
- DELETE — Remove data (like deleting a bookmark)
Status Codes
- 200 — Success
- 201 — Created (new resource made)
- 400 — Bad request (invalid data)
- 404 — Not found
- 500 — Server error
Request and Response Format
Most APIs use JSON format. A request to create a bookmark might look like:
{
"url": "https://example.com",
"title": "Example Site",
"tags": ["reference", "tech"]
}
And the response:
{
"id": "abc123",
"url": "https://example.com",
"title": "Example Site",
"tags": ["reference", "tech"],
"createdAt": "2026-02-02T10:30:00Z"
}
More API Examples
User Authentication API
Create an authentication API with:
- POST /register - create new user (email, password)
- POST /login - authenticate user, return JWT token
- GET /profile - get current user (requires auth token)
- PUT /profile - update current user
Use bcrypt to hash passwords. Use JWT for tokens.
Store users in a JSON file.
Task Management API
Create a task management API:
- Tasks have: title, description, status, priority, dueDate
- GET /tasks - list tasks (filter by status, priority)
- POST /tasks - create task
- PUT /tasks/:id - update task
- DELETE /tasks/:id - delete task
- PATCH /tasks/:id/complete - mark task complete
Include sorting by dueDate and filtering by status.
Contact Form API
Create a simple contact form API:
- POST /contact - receive form submission
- Validate email format
- Validate required fields (name, email, message)
- Store submissions in a JSON file
- Return success message
This will be used by a website contact form.
Webhook Endpoint
Create a webhook endpoint for Stripe payments:
- POST /webhooks/stripe - receive Stripe events
- Verify webhook signature
- Handle "payment_intent.succeeded" events
- Log successful payments to a file
- Return 200 to acknowledge receipt
Adding a Database
JSON files work for simple cases, but real APIs often need databases. Claude can help:
SQLite (Simple, file-based)
Convert this API to use SQLite instead of JSON files.
Keep the same endpoints but store data in a database.
PostgreSQL (Production-ready)
Update this API to use PostgreSQL.
I'll provide the database connection string.
Add proper connection pooling and error handling.
MongoDB (Document database)
Switch this API to use MongoDB.
Store bookmarks as documents in a bookmarks collection.
Add proper indexing for common queries.
Testing Your API
Using curl
Claude can test with curl commands directly in the terminal. Ask: "Test the create bookmark endpoint with curl."
Using Postman
For visual testing, use Postman (free). Ask Claude: "Generate a Postman collection for this API."
Automated tests
Ask Claude: "Create automated tests for all endpoints using Jest." This creates tests you can run anytime to verify everything works.
Example Test Commands
# Create a bookmark
curl -X POST http://localhost:3000/bookmarks \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com", "title": "Example"}'
# List all bookmarks
curl http://localhost:3000/bookmarks
# Get specific bookmark
curl http://localhost:3000/bookmarks/abc123
# Delete bookmark
curl -X DELETE http://localhost:3000/bookmarks/abc123
Common Mistakes to Avoid
- Forgetting validation: Always validate input data. Ask Claude to add validation if endpoints accept bad data.
- Missing error handling: APIs should handle errors gracefully. Ask: "Add proper error handling for database failures."
- No authentication: If your API handles sensitive data, add authentication. "Add JWT authentication to protect these endpoints."
- Hardcoded values: Use environment variables for secrets. "Move the database password to an environment variable."
- Not testing edge cases: Test what happens with empty data, wrong types, or missing fields.
Deployment Options
Once your API works locally, deploy it so others can use it.
Railway (Easiest)
Deploy this API to Railway
Railway offers a generous free tier and handles everything. You'll get a live URL in minutes.
Render
Deploy this API to Render
Another excellent option with free tier. Good for APIs with databases.
Fly.io
Deploy this API to Fly.io
Great for global distribution. Your API runs close to your users.
Vercel (Serverless)
Convert this API to Vercel serverless functions and deploy
Good for APIs that don't need persistent connections.
Environment variables: After deploying, you'll need to set environment variables (like database URLs) in your hosting platform's dashboard. Ask Claude: "What environment variables do I need to set for deployment?"
Use a CLAUDE.md File for API Standards
If you want Claude to follow specific API conventions across your project, create a CLAUDE.md file in your project root. Claude reads this at the start of every session, so all generated code follows the same patterns.
# API Project Standards
## Tech Stack
- Express.js with TypeScript
- PostgreSQL via Prisma ORM
- JWT authentication with refresh tokens
- Zod for request validation
## API Conventions
- All responses follow: { success: boolean, data?: any, error?: string }
- Use plural nouns for resource names (e.g., /users, /bookmarks)
- Always include pagination for list endpoints
- Rate limit all public endpoints
## Testing
- Jest for unit tests, Supertest for integration tests
- Every endpoint needs at least one happy path and one error test
Piping Test Output to Claude
One powerful debugging workflow is piping your test output directly to Claude Code. Instead of copying and pasting error messages, you can run:
npm run test 2>&1 | claude -p "Fix these failing tests"
Claude receives the full test output, reads the relevant source files, and implements fixes. You can also create a shell alias to make this even easier:
# Add to ~/.zshrc or ~/.bashrc
ask() { "$@" 2>&1 | claude -p "Analyze this output and suggest fixes." }
Then simply run ask npm run test to pipe any command's output to Claude.
Adding Features
Rate Limiting
Add rate limiting: max 100 requests per minute per IP.
Return 429 status when limit exceeded.
API Documentation
Generate OpenAPI/Swagger documentation for this API.
Include all endpoints, request/response schemas, and examples.
Logging
Add request logging: log method, path, status code, and response time.
In production, also log to a file.
CORS for Websites
Enable CORS so my website at example.com can call this API.
Also allow localhost for development.
FAQ
Can I build an API with Claude Code without coding experience?
Yes. Claude Code generates all the server code, endpoints, and data handling for you. You describe what your API should do in plain English, and Claude creates a working API with proper routes, validation, and error handling.
What kind of APIs can I build with Claude Code?
You can build REST APIs, webhook endpoints, data processing services, authentication systems, and integrations with third-party services. Claude handles everything from simple CRUD operations to complex business logic.
How do I connect my API to a frontend?
Your frontend makes HTTP requests to your API endpoints. If they're on different domains, you'll need CORS enabled. Ask Claude: "Add CORS support so my React app can call this API."
Is it secure to deploy an API built with Claude Code?
Claude follows security best practices, but always review before deploying. Ask Claude to add authentication, input validation, and rate limiting. Never expose sensitive data or credentials in your code.
How do I handle file uploads?
Ask Claude: "Add an endpoint for file uploads. Accept images up to 5MB and store them locally." Claude will add the necessary middleware and storage logic.
Can I build APIs in languages other than Node.js?
Absolutely. Claude Code works with Python (Flask, FastAPI, Django), Go (Gin, Echo), Ruby (Rails, Sinatra), Java (Spring Boot), Rust (Actix), and more. Just specify the language: "Create a REST API using FastAPI in Python."
Which AI model does Claude Code use for API development?
Claude Code uses Claude Opus 4.6 by default—the most capable model in the Claude family. For faster iteration on simple endpoints, Claude may delegate read-only exploration tasks to Claude Haiku 4.5 via its built-in subagent system, keeping your main conversation focused on the actual development work.
Related Guides
- How to Install Claude Code — get set up first
- Build a Website with Claude Code — create a frontend
- Create a Chrome Extension — browser extensions
- Claude Code for Non-Coders — more project ideas
Free: The AI Growth Breakdown
See how one business went from 0 to 600 daily visitors in 14 days using AI. The exact tools and results.
Get the Free Breakdown →