API Design Prompt Templates
AI prompt templates for designing APIs. Create well-structured, intuitive API endpoints and documentation.
Overview
Well-designed APIs are intuitive, consistent, and evolvable. These prompts help you design APIs that developers enjoy using, whether you're building REST endpoints, GraphQL schemas, or internal service interfaces. Good API design considers not just the happy path, but versioning, error handling, and how the API will grow over time.
Best Practices
Describe the domain and use cases before asking for endpoint design, context shapes good API structure
Specify your constraints upfront: REST vs GraphQL, authentication method, versioning strategy
Include existing API patterns from your system so new endpoints stay consistent
Think about who consumes the API, mobile apps have different needs than server-to-server calls
Consider pagination, filtering, and sorting from the start, retrofitting these is painful
Prompt Templates
1. REST API Endpoint Design
Design REST API endpoints for this feature: **Feature:** [WHAT THE FEATURE DOES] **Domain entities:** [KEY OBJECTS/RESOURCES INVOLVED] **Operations needed:** - [OPERATION 1 - e.g. create, list, update] - [OPERATION 2] - [OPERATION 3] **Constraints:** - Auth method: [API KEY / JWT / OAUTH] - Versioning: [URL PATH / HEADER / NONE] - Existing patterns: [ANY CONVENTIONS TO FOLLOW] **Consumers:** [WEB APP / MOBILE / THIRD-PARTY / INTERNAL] For each endpoint provide: - HTTP method and path - Request parameters/body - Response structure - Status codes - Pagination approach (if listing)
Feature: User subscription management Domain entities: User, Subscription, Plan Operations: Create subscription, cancel, upgrade/downgrade, list user's subscription history Auth: JWT Versioning: URL path (/api/v1/) Consumers: Web app and mobile app
## Subscription API Endpoints
### Create Subscription
`POST /api/v1/subscriptions`
**Request:**
```json
{
"plan_id": "plan_pro_monthly",
"payment_method_id": "pm_xxx"
}
```
**Response (201 Created):**
```json
{
"id": "sub_abc123",
"plan": { "id": "plan_pro_monthly", "name": "Pro Monthly" },
"status": "active",
"current_period_end": "2024-02-15T00:00:00Z",
"cancel_at_period_end": false
}
```
### List Subscription History
`GET /api/v1/subscriptions`
**Query params:**
- `status` - Filter by: active, canceled, past_due
- `limit` - Max 100, default 20
- `starting_after` - Cursor for pagination
**Response (200):**
```json
{
"data": [...],
"has_more": true,
"next_cursor": "sub_xyz789"
}
```
### Change Plan
`PATCH /api/v1/subscriptions/{id}`
**Request:**
```json
{
"plan_id": "plan_enterprise_monthly",
"proration_behavior": "create_prorations"
}
```
### Cancel Subscription
`DELETE /api/v1/subscriptions/{id}?cancel_at_period_end=true`
**Response (200):** Returns subscription with `cancel_at_period_end: true`Designing new API features, planning API refactors, or standardizing existing ad-hoc endpoints
- •Use nouns for resources, not verbs (/subscriptions not /createSubscription)
- •Design for the 80% use case first, don't over-engineer for edge cases upfront
2. API Error Response Design
Design an error response structure for my API: **API type:** [REST / GRAPHQL / RPC] **Current consumers:** [WHO USES THE API] **Error scenarios I need to handle:** - [ERROR TYPE 1 - e.g. validation errors] - [ERROR TYPE 2 - e.g. authorization failures] - [ERROR TYPE 3 - e.g. rate limiting] **Requirements:** - [ANY SPECIFIC REQUIREMENTS - e.g. machine-readable codes, localization] Design a consistent error response structure that: - Is consistent across all error types - Is useful for debugging (dev) and displaying (user) - Supports multiple errors when applicable - Includes enough detail without leaking sensitive info
API type: REST Consumers: React web app, React Native mobile app Error scenarios: Validation errors, auth failures, rate limits, not found, server errors Requirements: Machine-readable error codes, support for field-level validation errors
## Error Response Structure
**Standard format:**
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request could not be processed due to validation errors.",
"details": [...],
"request_id": "req_abc123"
}
}
```
### Error Codes
| Code | HTTP Status | Description |
|------|-------------|-------------|
| VALIDATION_ERROR | 400 | Request body/params invalid |
| UNAUTHORIZED | 401 | Missing or invalid auth |
| FORBIDDEN | 403 | Valid auth, insufficient permissions |
| NOT_FOUND | 404 | Resource doesn't exist |
| RATE_LIMITED | 429 | Too many requests |
| INTERNAL_ERROR | 500 | Server error (don't expose details) |
### Validation Errors (with field details)
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Please fix the following errors.",
"details": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Please enter a valid email address."
},
{
"field": "password",
"code": "TOO_SHORT",
"message": "Password must be at least 8 characters."
}
]
}
}
```
### Rate Limit Response
```json
{
"error": {
"code": "RATE_LIMITED",
"message": "Too many requests. Please try again in 60 seconds.",
"retry_after": 60
}
}
```
**Headers for rate limits:**
- `X-RateLimit-Limit: 100`
- `X-RateLimit-Remaining: 0`
- `X-RateLimit-Reset: 1705312800`Designing new APIs, standardizing error handling across microservices, or improving API developer experience
- •Include request_id in all errors, it's very useful for debugging support tickets
- •Never expose stack traces or internal details in production error responses
3. API Versioning Strategy
Help me design an API versioning strategy: **API context:** - Current state: [NEW API / EXISTING WITH X CONSUMERS] - Expected change frequency: [RARELY / QUARTERLY / FREQUENTLY] - Consumer types: [INTERNAL ONLY / EXTERNAL PARTNERS / PUBLIC] - Breaking change tolerance: [LOW - must support old versions long / HIGH - can deprecate quickly] **Current endpoints (if existing):** [LIST KEY ENDPOINTS] **Upcoming changes:** [DESCRIBE WHAT CHANGES ARE PLANNED] Recommend: 1. Versioning approach (URL path, header, query param) 2. Deprecation policy 3. Migration strategy for breaking changes 4. How to communicate changes to consumers
Context: Existing API with 50+ external partner integrations Change frequency: Major changes quarterly Consumer types: External partners, some with slow update cycles Breaking change tolerance: Low - partners need 6+ months to migrate Upcoming: Complete restructure of the order resource
## Recommended Strategy: URL Path Versioning
Given your external partners with slow update cycles, URL path versioning (`/api/v1/`, `/api/v2/`) provides:
- Clear visual distinction between versions
- Easy for partners to test against both versions
- Simple routing in your infrastructure
### Deprecation Policy
1. **Announce** new version 3 months before release
2. **Sunset warning** on old version: 6 months after new version launches
3. **Deprecation headers** immediately on old version:
```
Deprecation: true
Sunset: Sat, 15 Jun 2025 00:00:00 GMT
Link: <https://api.example.com/v2/orders>; rel="successor-version"
```
4. **Hard deprecation** 9 months after new version (12 months total support)
### Migration Strategy for Order Resource
**Phase 1:** Release v2 with new order structure
- v1 and v2 run in parallel
- v1 responses include deprecation headers
**Phase 2:** Provide migration helper
- `GET /api/v1/orders/{id}?include=v2_preview` returns both formats
- Detailed migration guide with field mappings
**Phase 3:** Usage monitoring
- Track v1 usage by partner
- Reach out to high-volume v1 users at 3-month mark
### Communication Plan
1. Email announcement to all API key holders
2. In-dashboard banner for developer portal
3. Changelog with detailed field-by-field migration guide
4. Office hours / Q&A sessions for partnersPlanning long-term API strategy, preparing for major API changes, or establishing API governance
- •For external APIs, URL versioning is clearest despite being less 'pure'
- •Track API version usage, you need data to know when it's safe to deprecate
4. GraphQL Schema Design
Design a GraphQL schema for this feature: **Feature:** [WHAT IT DOES] **Key entities:** - [ENTITY 1 AND ITS KEY FIELDS] - [ENTITY 2] **Queries needed:** - [QUERY 1 - e.g. get single item, list with filters] **Mutations needed:** - [MUTATION 1 - e.g. create, update, delete] **Relationships:** - [ENTITY 1] has many [ENTITY 2] - [OTHER RELATIONSHIPS] **Performance considerations:** - [EXPECTED DATA SIZES, N+1 CONCERNS] Provide the schema with types, queries, mutations, and resolver notes for complex fields.
Feature: Blog with posts and comments Entities: User (id, name, email), Post (id, title, content, author), Comment (id, content, author, post) Queries: Get post by ID/slug, list posts with pagination and filters Mutations: Create/update/delete post, add comment Relationships: User has many Posts, Post has many Comments Performance: Posts can have thousands of comments
```graphql
type User {
id: ID!
name: String!
email: String!
posts(first: Int, after: String): PostConnection!
}
type Post {
id: ID!
slug: String!
title: String!
content: String!
author: User!
comments(first: Int = 20, after: String): CommentConnection!
commentCount: Int! # Denormalized for performance
createdAt: DateTime!
updatedAt: DateTime!
}
type Comment {
id: ID!
content: String!
author: User!
createdAt: DateTime!
}
# Relay-style pagination
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type PostEdge {
node: Post!
cursor: String!
}
type Query {
post(id: ID, slug: String): Post
posts(
first: Int = 20
after: String
filter: PostFilter
orderBy: PostOrder = CREATED_AT_DESC
): PostConnection!
}
input PostFilter {
authorId: ID
publishedAfter: DateTime
search: String
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
updatePost(id: ID!, input: UpdatePostInput!): UpdatePostPayload!
deletePost(id: ID!): DeletePostPayload!
addComment(postId: ID!, input: AddCommentInput!): AddCommentPayload!
}
input CreatePostInput {
title: String!
content: String!
slug: String # Auto-generated if not provided
}
type CreatePostPayload {
post: Post
errors: [UserError!]!
}
```
**Resolver Notes:**
- `Post.comments`: Use DataLoader to batch comment fetches across posts
- `Post.commentCount`: Store denormalized, update via database trigger
- `posts` query: Implement cursor-based pagination with Relay specDesigning new GraphQL APIs, adding features to existing schemas, or migrating from REST to GraphQL
- •Use connections (Relay pagination) from the start, retrofitting pagination is a breaking change
- •Include commentCount-style fields to avoid fetching all items just to count them
Common Mistakes to Avoid
Designing APIs around your database schema instead of how consumers will use the data
Ignoring pagination, filtering, and sorting until you have performance problems
Inconsistent naming conventions and response structures across endpoints
Frequently Asked Questions
Well-designed APIs are intuitive, consistent, and evolvable. These prompts help you design APIs that developers enjoy using, whether you're building REST endpoints, GraphQL schemas, or internal service interfaces. Good API design considers not just the happy path, but versioning, error handling, and how the API will grow over time.
Related Templates
Code Review Prompt Templates
AI prompt templates for thorough code reviews. Get comprehensive feedback on code quality, security, and best practices.
Debugging Prompt Templates
AI prompt templates for debugging code. Identify issues, understand errors, and find solutions faster.
Code Documentation Prompt Templates
AI prompt templates for writing code documentation. Create clear comments, READMEs, and API docs.
Have your own prompt to optimize?