/blogs/api-design-that-doesnt-break-at-scale

← Back to blogs
Blog

API Design That Doesn’t Break at Scale

Build clean, predictable REST APIs with proper URL structure, HTTP methods, pagination, filtering, and scalable design patterns.

·57 min read·

API Design: Building RESTful Interfaces That Scale

API design is not an afterthought. It is not something you figure out while writing your first handler function. It is a foundational skill that separates backend engineers who build maintainable systems from those who create technical debt.

When you design APIs well, your interfaces become intuitive, your documentation writes itself, and your consumers integrate faster with fewer support tickets. When you design APIs poorly, you create confusion, inconsistency, and a constant stream of "why doesn't this work?" messages from frontend engineers and third-party developers.

We will cover REST API design from first principles: historical context, core architectural constraints, URL structure, HTTP method semantics, idempotency, pagination, filtering, sorting, custom actions, and practical patterns you can apply immediately. We will walk through a complete project management platform example, designing every endpoint for organizations, projects, and tasks.

If you are new to API design, this will give you a solid foundation. If you are experienced, this will help you refine your approach and catch edge cases you might have missed.

#Tables of Contents

#The Problem with API Design

REST has been the dominant API architectural style for over two decades. Thousands of engineers have built APIs using its principles. Countless articles, books, and talks have explained its concepts. Yet new developers still ask the same questions, and experienced engineers still debate the same decisions:

  • Should resource paths be plural or singular? /users or /user?
  • When updating a resource, should I use PUT or PATCH? What is the actual difference?
  • What HTTP method do I use for a custom action that isn't create, read, update, or delete?
  • Which status code fits this scenario? 200, 201, 204, 400, 404, 422?
  • Should I return the updated resource after a PATCH, or just a success message?
  • How do I handle pagination? Query parameters or request body?
  • What about filtering and sorting? How do I design those query parameters?
  • Should I version my APIs? If so, how? In the URL, headers, or content negotiation?

These questions persist not because REST is unclear, but because the web has evolved dramatically since REST was formalized. When Roy Fielding described REST in his 2000 dissertation, most web applications were Multi-Page Applications (MPAs). Pages were rendered on the server, links navigated to new pages, and forms submitted to server endpoints. The client was relatively thin.

Today, Single Page Applications (SPAs) dominate. The browser downloads a JavaScript bundle on first load, and all subsequent navigation and data fetching happens client-side via API calls. The client is thick, stateful, and often maintains its own cache. Mobile apps, server-to-server integrations, and IoT devices add even more variety to API consumers.

The context changed, but the core principles of REST remain valid. The goal of this guide is not to invent new standards. It is to extract clear, actionable, practical guidelines from existing REST specifications and real-world experience so you can:

  • Design predictable, intuitive routes that consumers can guess correctly
  • Structure consistent request and response payloads that are easy to parse
  • Return appropriate HTTP status codes that convey meaning without ambiguity
  • Document behavior clearly so consumers do not need to read your source code
  • Build APIs that scale in complexity without becoming unmaintainable

When you follow established patterns, you stop debating style and start shipping features. You reduce onboarding time for new team members. You minimize support burden from API consumers. You create a foundation that can evolve without breaking existing integrations.

#Historical Context: Where REST Came From

Understanding where REST came from helps you apply it correctly. It is not arbitrary. Each constraint solves a specific problem.

The Birth of the Web

In 1990, Tim Berners-Lee, a British computer scientist working at CERN, started a project called the World Wide Web. His motivation was simple: enable researchers around the world to share knowledge and documents easily.

Within about a year, Berners-Lee invented the foundational technologies that still power the web today:

  1. URI (Uniform Resource Identifier) - A string that identifies a resource. Examples: https://example.com/users/123, mailto:alice@example.com. URIs provide a universal addressing scheme.

  2. HTTP (Hypertext Transfer Protocol) - The application-layer protocol for client-server communication. HTTP defines methods (GET, POST, etc.), status codes (200, 404, etc.), headers, and message formats.

  3. HTML (Hypertext Markup Language) - The markup language for structuring web pages. HTML introduced hyperlinks, enabling navigation between resources.

  4. The first web server - Software that listens for HTTP requests and returns responses. Berners-Lee's server ran on a NeXT computer.

  5. The first web browser - Software that renders HTML and allows users to navigate the web. The first browser was also an editor.

  6. The first WYSIWYG HTML editor - Built into the browser, allowing users to create and edit web content visually.

We still use advanced versions of all these technologies. HTTP has evolved through versions 1.1, 2, and 3. HTML has added semantic elements, APIs, and multimedia support. Web servers and browsers are vastly more sophisticated. But the core concepts remain.

The Scalability Crisis

The web grew faster than anyone anticipated. Within a few years, thousands of users were connecting daily. Berners-Lee had not designed the original architecture for exponential growth. The system began to show strain.

To address scalability, new techniques, standards, and components had to be introduced. Around 1993, Roy Fielding, a graduate student and co-founder of the Apache HTTP Server project, became concerned about the web's scalability problem. He proposed a set of architectural constraints that could help the web scale to accommodate millions of users.

The Six REST Constraints

Fielding's constraints form the foundation of REST. Each constraint addresses a specific architectural concern.

1. Client-Server

Rendering diagram...

What it means: Separation of concerns between client and server. The client handles user interface, user experience, and client-side state. The server handles data storage, business logic, and authentication.

Why it matters:

  • Clients and servers can evolve independently. The server can change its database schema without affecting clients, as long as the API contract remains stable.
  • Different clients (web, mobile, CLI) can consume the same server API.
  • Servers can scale horizontally without requiring changes to clients.

Practical implication: Do not embed business logic in your frontend. Do not expose your database schema directly to clients. Use an API layer as a contract.

2. Uniform Interface

What it means: A standardized way for components to communicate. The uniform interface has four sub-constraints:

Sub-constraintDescriptionExample
Resource identificationResources are identified by URIs/api/v1/users/123 identifies a specific user
Resource manipulation through representationsClients modify resources by sending representations (JSON, XML)PATCH /users/123 with {"name": "Alice"} updates the user's name
Self-descriptive messagesEach message contains enough information to process itHTTP method, headers, and body together describe the request
HATEOAS (Hypermedia as the Engine of Application State)Responses include links to related actionsA user response includes "links": {"projects": "/users/123/projects"}

Why it matters:

  • Consistency across services. Engineers can work on different parts of the system without learning new interaction patterns.
  • Discoverability. Clients can navigate the API by following links.
  • Interoperability. Different implementations can communicate because they follow the same interface.

Practical implication: Use standard HTTP methods consistently. Return hypermedia links when it adds value. Document your API contract clearly.

3. Layered System

Rendering diagram...

What it means: The architecture is composed of hierarchical layers. Each layer can only interact with the immediate layer below it. Layers can include load balancers, proxies, caches, and application servers.

Why it matters:

  • Scalability. You can add layers (like a cache or CDN) without changing core logic.
  • Security. Proxies can handle authentication, rate limiting, and request validation before traffic reaches your application.
  • Maintainability. Layers can be replaced or upgraded independently.

Practical implication: Design your API so it can sit behind a proxy or load balancer. Do not assume direct client-to-server communication.

4. Cache

What it means: Responses must be explicitly labeled as cacheable or non-cacheable. The server controls caching behavior via HTTP headers like Cache-Control, ETag, and Last-Modified.

Why it matters:

  • Performance. Cached responses reduce server load and improve response times.
  • Efficiency. Clients can avoid re-fetching unchanged resources.
  • Scalability. Caching layers can serve repeated requests without hitting your application.

Practical implication: Set appropriate cache headers for each endpoint. GET requests for static data can be cached aggressively. POST, PUT, PATCH, and DELETE responses should generally not be cached.

5. Stateless

What it means: Each request from client to server must contain all information necessary to understand and process the request. The server does not store client context between requests.

Rendering diagram...

Why it matters:

  • Reliability. Any server instance can handle any request. No session affinity required.
  • Scalability. You can add or remove server instances without disrupting clients.
  • Visibility. Each request is self-contained, making logging and debugging easier.

Practical implication: Do not store session state on the server. Use tokens (JWT, opaque tokens) that contain all necessary context. Include authentication credentials with each request.

6. Code on Demand (Optional)

What it means: Servers can temporarily extend client functionality by transferring executable code, such as JavaScript.

Why it matters:

  • Flexibility. Clients can receive new behavior without updates.
  • Efficiency. Common logic can be shared via code downloads.

Practical implication: This constraint is rarely used in API design. Most REST APIs do not transfer executable code. It remains optional for specialized use cases.

The REST Dissertation

In 2000, after the web's scalability crisis was addressed, Roy Fielding named and described the web's architectural style in his PhD dissertation: "Architectural Styles and the Design of Network-based Software Architectures." He called it REST: Representational State Transfer.

Fielding's dissertation is a dense, academic document. Reading it provides deep context for why REST constraints exist. If you are a backend engineer, it is worth reading at least the sections on REST. Search for "Roy Fielding REST dissertation" to find the original document.

You do not need to memorize every detail. But understanding the motivation behind REST helps you apply its principles correctly, especially when facing edge cases or trade-offs.

#Why Is It Called REST

The name "Representational State Transfer" is descriptive. Breaking it down clarifies what REST actually means.

Representational

Resources on the web are abstract concepts: a user, a book, a shopping cart. They do not have a physical form. To interact with them, we use representations: specific formats that encode the resource's state.

Common representation formats:

FormatUse CaseExample
JSONAPI client communication{"id": 123, "name": "Alice"}
HTMLBrowser rendering<div class="user">Alice</div>
XMLLegacy integrations, SOAP<user><id>123</id><name>Alice</name></user>
Protocol BuffersHigh-performance internal APIsBinary format, schema-defined

The same resource can have multiple representations. A user resource might be:

>_ text
// JSON representation for API client
{
  "id": "usr_123",
  "name": "Alice",
  "email": "alice@example.com",
  "createdAt": "2025-01-15T10:30:00Z",
  "roles": ["admin", "editor"]
}
>_ text
<!-- HTML representation for browser -->
<!DOCTYPE html>
<html>
<body>
  <div class="user-profile">
    <h1>Alice</h1>
    <p>alice@example.com</p>
    <span class="badge admin">Admin</span>
    <span class="badge editor">Editor</span>
    <small>Member since January 2025</small>
  </div>
</body>
</html>

Key insight: The representation is not the resource. The resource is the abstract concept; the representation is how we encode it for transmission.

State

State refers to the current attributes of a resource at a specific point in time.

Example: An e-commerce shopping cart resource.

>_ text
{
  "cartId": "cart_789",
  "userId": "usr_123",
  "items": [
    {
      "productId": "prod_101",
      "name": "Wireless Headphones",
      "quantity": 2,
      "price": 79.99,
      "currency": "USD"
    },
    {
      "productId": "prod_202",
      "name": "Phone Case",
      "quantity": 1,
      "price": 19.99,
      "currency": "USD"
    }
  ],
  "subtotal": 179.97,
  "tax": 14.40,
  "total": 194.37,
  "currency": "USD",
  "updatedAt": "2025-06-01T14:22:00Z"
}

This JSON document represents the state of the shopping cart at the moment it was fetched. If the user adds another item, the state changes. The next GET request will return a different representation.

Key insight: State is transferable. The client and server exchange representations that encode the resource's current state.

Transfer

Transfer describes the movement of resource representations between client and server via HTTP.

HTTP methods define the semantics of transfer:

MethodSemanticsIdempotentSafe
GETRetrieve a representationYesYes
HEADRetrieve headers onlyYesYes
POSTCreate a new resource or execute an actionNoNo
PUTReplace a resource entirelyYesNo
PATCHPartially update a resourceDependsNo
DELETERemove a resourceYesNo
OPTIONSDescribe communication optionsYesYes

Key insight: Transfer is standardized. HTTP provides a common vocabulary for client-server communication.

Putting It All Together

REST describes an architectural style where:

  1. Resources are identified by URIs - Every resource has a unique address.
  2. Resources have multiple representation formats - JSON for APIs, HTML for browsers, etc.
  3. Resource state transfers between client and server - Via HTTP methods and messages.
  4. Communication follows a uniform interface - Standard methods, status codes, headers.
  5. The system is stateless - Each request is self-contained.
  6. The system is layered - Proxies, caches, and gateways can be added transparently.
  7. Responses are cacheable when appropriate - Improving performance and scalability.

When you design a REST API, you are applying these principles to create an interface that is predictable, scalable, and maintainable.

#URL Structure for APIs

URLs are the primary way clients identify and interact with your resources. Getting URL structure right is critical for API usability.

Anatomy of a URL

https://sriniously.xyz/blog/zist?q=something#header │ │ │ │ │ │ │ │ │ └─ Fragment: Client-side navigation anchor │ │ │ └─ Query string: Key-value parameters for filtering, pagination, etc. │ │ └─ Path: Hierarchical resource identifier │ └─ Authority: Domain and optional port └─ Scheme: Protocol (http or https)
ComponentDescriptionExample
SchemeProtocol used for communicationhttps
AuthorityDomain name and optional portsriniously.xyz, api.example.com:8080
PathHierarchical resource identifier/blog/zist, /api/v1/users/123
Query stringKey-value parameters for filtering, sorting, pagination?q=something&limit=20
FragmentClient-side anchor for in-page navigation#header

API URL Structure

Production APIs typically follow a consistent structure:

https://api.example.com/v1/organizations │ │ │ │ └─ Resource: Plural, lowercase, hyphenated │ │ │ └─ Version: v1, v2, etc. │ │ └─ Subdomain: Dedicated API domain │ └─ Domain: Your organization's domain └─ Scheme: Always https in production

Why a Dedicated API Subdomain?

Using api.example.com instead of example.com/api provides several benefits:

  • Clear separation: API traffic is distinct from web traffic.
  • Independent scaling: You can scale API servers separately from web servers.
  • Simplified CORS: Browsers enforce same-origin policy; a dedicated subdomain makes CORS configuration explicit.
  • Monitoring and logging: API requests can be tracked separately.

Why Version in the URL?

Including the version in the path (/v1/) is the most practical approach for most APIs:

  • Explicit: Clients know exactly which version they are using.
  • Cacheable: Different versions have different URLs, so caches do not mix them.
  • Simple: No need for complex content negotiation or header parsing.

Alternative versioning strategies exist (headers, query parameters, content negotiation), but URL versioning is the most straightforward and widely adopted.

Resource Naming Rules

Rule 1: Always Use Plural Nouns

Use plural nouns for resource names, even when referring to a single resource:

GET /api/v1/books # List all books GET /api/v1/books/123 # Get book with ID 123 POST /api/v1/books # Create a new book PATCH /api/v1/books/123 # Update book with ID 123 DELETE /api/v1/books/123 # Delete book with ID 123 GET /api/v1/book # Inconsistent: singular GET /api/v1/book/123 # Inconsistent: singular

Why plural?

  • Consistency: The path represents a collection. /books is the collection; /books/123 is a member of that collection.
  • Predictability: Consumers can guess that /books lists resources and /books/{id} fetches one.
  • Extensibility: Nested resources follow naturally: /books/123/reviews.

Rule 2: Use Lowercase with Hyphens

Use lowercase letters and hyphens for multi-word resource names:

/api/v1/user-profiles /api/v1/order-items /api/v1/payment-methods /api/v1/UserProfiles # PascalCase: case sensitivity issues across systems /api/v1/user_profiles # Underscores: less URL-friendly, harder to type /api/v1/userprofiles # No separator: harder to read

Why lowercase and hyphens?

  • Case sensitivity: Some systems treat User and user as different. Lowercase avoids ambiguity.
  • Readability: Hyphens are more visible than underscores in URLs, especially when underlined as links.
  • Typing: Hyphens are easier to type on mobile keyboards.

Rule 3: Use IDs or Slugs for Resource Identifiers

When referencing a specific resource in the path, use either:

  • Numeric or UUID IDs for internal references: /api/v1/users/usr_123abc
  • Slugs for human-readable, SEO-friendly URLs: /api/v1/articles/how-to-design-apis

Slug conversion rules:

Original: "Harry Potter and the Chamber of Secrets" Step 1: Convert to lowercase: "harry potter and the chamber of secrets" Step 2: Replace spaces with hyphens: "harry-potter-and-the-chamber-of-secrets" Step 3: Remove special characters: "harry-potter-and-the-chamber-of-secrets" Result: /api/v1/books/harry-potter-and-the-chamber-of-secrets

When to use slugs vs IDs:

  • Use slugs for public-facing resources where readability matters (blog posts, products).
  • Use IDs for internal APIs or when the identifier is not human-meaningful (user IDs, order IDs).
  • Consider supporting both: /api/v1/articles/{slugOrId} with logic to resolve either.

Hierarchical Paths

Forward slashes in the path denote hierarchical relationships between resources:

/api/v1/organizations/123/projects/456/tasks/789 │ │ │ └─ Task resource (child of project) │ │ └─ Project resource (child of organization) │ └─ Organization resource (top-level)

Design guidelines for hierarchical paths:

  1. Start with top-level resources: /organizations, /users, /products.
  2. Nest only when there is a strong ownership relationship: A task belongs to a project; a project belongs to an organization.
  3. Avoid deep nesting: More than three levels (/a/b/c/d) becomes hard to work with.
  4. Consider flat alternatives: Instead of /organizations/123/projects, you could use /projects?organizationId=123.

When to nest vs. when to flatten:

Rendering diagram...

Examples:

Nested (strong ownership, frequent parent access): /api/v1/organizations/123/projects /api/v1/projects/456/tasks Flat (weak relationship, independent access): /api/v1/tasks?projectId=456 /api/v1/members?organizationId=123 Over-nested (hard to work with): /api/v1/organizations/123/projects/456/tasks/789/comments/101/replies

#Idempotency and HTTP Methods

Idempotency is a critical concept for API design, especially for retry logic, distributed systems, and client resilience.

What Is Idempotency

An operation is idempotent if performing it multiple times has the same effect as performing it once.

In API terms: If a client sends the same request multiple times (due to network retries, user double-clicks, or bugs), the server's state after the first successful request should be the same as after the tenth.

Why idempotency matters:

  • Network reliability: HTTP requests can fail or time out. Clients may retry. Idempotent operations ensure retries do not cause unintended side effects.
  • User experience: Users may double-click a submit button. Idempotency prevents duplicate creations.
  • Distributed systems: In microservices, the same event might be processed multiple times. Idempotency ensures consistency.

Idempotency by HTTP Method

MethodIdempotentWhyExample
GETYesFetching data does not change server state. Multiple GET requests return the same representation (assuming no concurrent updates).GET /users/123 returns the same user data whether called once or 100 times.
HEADYesLike GET, but returns headers only. No state change.HEAD /users/123 checks if a resource exists without fetching it.
PUTYesReplacing a resource with the same payload yields the same result.PUT /users/123 with {"name": "Alice"} sets the name to "Alice" regardless of how many times it is called.
DELETEYesDeleting a resource once or multiple times results in the resource being absent.DELETE /users/123 removes the user. Subsequent calls return 404, but the state (user absent) is unchanged.
POSTNoEach POST typically creates a new resource with a new ID. Multiple calls create multiple resources.POST /users with {"name": "Alice"} creates a new user each time.
PATCHDependsIdempotency depends on the patch operation. See detailed section below.PATCH /users/123 with {"name": "Alice"} is idempotent; with {"viewCount": "+1"} is not.

PATCH Idempotency: It Depends

Per HTTP specifications (RFC 5789, RFC 7231), the PATCH method is not guaranteed to be idempotent. Whether a PATCH request is idempotent depends entirely on the payload format and server logic.

Idempotent PATCH Examples

These operations produce the same result regardless of how many times they are applied:

>_ text
// Replace a field - always results in name = "Alice"
{
  "op": "replace",
  "path": "/name",
  "value": "Alice"
}

// Set a value unconditionally
{
  "op": "set",
  "path": "/status",
  "value": "archived"
}

// JSON Patch format (RFC 6902)
[
  { "op": "replace", "path": "/email", "value": "alice@example.com" }
]

Why these are idempotent: The operation sets a specific value. Applying it multiple times does not change the outcome after the first application.

Non-Idempotent PATCH Examples

These operations produce different results with each application:

>_ text
// Increment a counter - each call changes the value
{
  "op": "add",
  "path": "/viewCount",
  "value": 1
}

// Append to a list - each call adds a new item
{
  "op": "add",
  "path": "/tags/-",
  "value": "new-tag"
}

// Conditional update - outcome depends on current state
{
  "op": "test-and-set",
  "path": "/status",
  "if": "pending",
  "value": "approved"
}

Why these are not idempotent: The operation's effect depends on the current state or accumulates with each application.

Practical Guidance for PATCH

  1. Document idempotency: If your PATCH endpoint is idempotent, state that clearly in your documentation. If not, warn consumers about retry behavior.

  2. Prefer idempotent operations: When possible, design PATCH payloads to be idempotent. Use "set" semantics instead of "increment" or "append."

  3. Support idempotency keys: For non-idempotent operations that must be retry-safe, allow clients to send an Idempotency-Key header. Your server can cache the response for a given key and return the cached result on retry.

>_ text
PATCH /api/v1/orders/123
Idempotency-Key: abc123xyz
Content-Type: application/json

{ "status": "shipped" }
>_ text
// Server-side pseudocode
if (cache.has(req.headers['idempotency-key'])) {
  return cache.get(req.headers['idempotency-key']);
}
const result = await processPatch(req.body);
cache.set(req.headers['idempotency-key'], result, { ttl: 3600 });
return result;

POST for Custom Actions

The POST method serves two distinct purposes in REST API design:

  1. Create a new resource (standard CRUD operation)
  2. Execute a custom action that does not fit CRUD semantics

When to Use POST for Custom Actions

Use POST for custom actions when:

  • The operation does not map cleanly to create, read, update, or delete.
  • The operation triggers complex server-side logic beyond simple state changes.
  • The operation may have side effects that are not obvious from the resource representation.

Examples of custom actions:

# Send a welcome email to a user POST /api/v1/users/123/send-welcome-email # Archive an organization (triggers cascading deletes, notifications) POST /api/v1/organizations/123/archive # Clone a project (copies tasks, preserves assignments, sends notifications) POST /api/v1/projects/456/clone # Approve a pending request (changes state and triggers workflow) POST /api/v1/requests/789/approve # Generate a report (long-running operation, may return a job ID) POST /api/v1/reports/generate

Designing Custom Action Endpoints

Follow these patterns for custom action endpoints:

  1. Use a descriptive path segment: Place the action name after the resource identifier.
POST /api/v1/users/123/send-welcome-email POST /api/v1/send-welcome-email?userId=123 # Action should be in path, not query
  1. Use POST, not GET: Custom actions typically change state or trigger side effects. GET should be safe and idempotent.

  2. Document the action's effects: Clearly describe what the action does, what preconditions are required, and what the response means.

  3. Return appropriate status codes:

    • 200 OK if the action updates an existing resource and returns it.
    • 201 Created if the action creates a new resource.
    • 202 Accepted if the action is asynchronous and returns a job ID.
    • 204 No Content if the action succeeds but has no response body.
  4. Consider idempotency: If the action should be retry-safe, document whether it is idempotent or support idempotency keys.

Example: Archive Organization

>_ http
POST /api/v1/organizations/123/archive
Authorization: Bearer abc123
Content-Type: application/json

{}
>_ text
// Response: 200 OK
{
  "id": "org_123",
  "name": "Acme Corp",
  "status": "archived",
  "archivedAt": "2025-06-01T15:30:00Z",
  "archivedBy": "usr_456"
}

Server-side behavior:

  • Validates that the caller has permission to archive the organization.
  • Updates the organization's status to "archived".
  • Sets archivedAt and archivedBy metadata.
  • Cascades to associated projects: marks them as archived or deletes them based on business rules.
  • Sends notifications to organization members.
  • Logs the action for audit purposes.

This is far more complex than a simple PATCH to update the status field. That complexity justifies a dedicated custom action endpoint.

#API Design Workflow: From Wireframes to Endpoints

Do not start coding immediately. Design your API interface first. This upfront investment saves time later by preventing costly refactors and ensuring your API meets consumer needs.

Step 1: Start with UI/Wireframes

Look at Figma designs, user stories, or product requirements. Understand how end users interact with your platform. This reveals:

  • What data users see on each screen
  • What actions users can perform (create, edit, delete, filter, sort)
  • How resources relate to each other (organizations contain projects, projects contain tasks)

Example: Project Management Platform

Imagine you are building a platform like Linear or Jira. The wireframes show:

  1. Organization Dashboard: Lists organizations the user belongs to. Each organization card shows name, status, and member count.
  2. Project List: Within an organization, shows projects with name, status, progress, and due date.
  3. Task Board: Within a project, shows tasks in columns (To Do, In Progress, Done). Each task shows title, assignee, priority, and due date.
  4. Task Detail: Clicking a task opens a modal with full details, comments, and attachments.

From these wireframes, you can infer the API requirements:

  • List organizations → GET /organizations
  • Create organization → POST /organizations
  • List projects for an organization → GET /organizations/123/projects
  • Create task → POST /projects/456/tasks
  • Update task status → PATCH /tasks/789
  • Archive organization → Custom action: POST /organizations/123/archive

Step 2: Identify Resources (Nouns)

Extract nouns from requirements. These become your top-level API resources.

Brainstorming session:

Product manager: "Users can create organizations, invite members, and manage projects." → Resources: users, organizations, projects Product manager: "Each project has tasks with titles, descriptions, assignees, and due dates." → Resources: tasks Product manager: "Tasks can have comments, attachments, and tags." → Resources: comments, attachments, tags Product manager: "Users can filter tasks by assignee, priority, or due date." → Query parameters: assigneeId, priority, dueDateRange

Prioritize resources:

  1. Core resources: organizations, projects, tasks (required for MVP)
  2. Secondary resources: comments, attachments, tags (can be added later)
  3. Utility resources: users, roles, permissions (may be handled by a separate auth service)

Document resources:

>_ markdown
API Resources

Organization
- Represents a company or team
- Fields: id, name, status, description, createdAt, updatedAt
- Relationships: has many projects, has many members

Project
- Represents a body of work within an organization
- Fields: id, name, organizationId, status, description, createdAt, updatedAt
- Relationships: belongs to organization, has many tasks

Task
- Represents a unit of work within a project
- Fields: id, title, projectId, status, priority, assignedTo, dueDate, description, createdAt, updatedAt
- Relationships: belongs to project, assigned to user, has many comments

Step 3: Design Database Schema

Map resources to database tables. This step ensures your API design aligns with your data model.

Example schema for project management platform:

Rendering diagram...

Key schema design decisions:

  1. Use UUIDs for IDs: string type with UUID format. Avoid auto-increment integers for distributed systems.
  2. Include timestamps: createdAt and updatedAt for auditing and sorting.
  3. Use enums for status fields: Constrain values at the database level.
  4. Make optional fields nullable: description?, assignedTo? indicate fields that may be absent.
  5. Define foreign keys explicitly: Clarify relationships for documentation and tooling.

Step 4: Identify Actions (CRUD + Custom)

For each resource, list the required operations. Start with CRUD, then add custom actions.

Organization actions:

ActionHTTP MethodEndpointDescription
List organizationsGET/organizationsReturn paginated list of organizations the user can access
Create organizationPOST/organizationsCreate a new organization
Get organizationGET/organizations/{id}Return details of a specific organization
Update organizationPATCH/organizations/{id}Partially update organization fields
Delete organizationDELETE/organizations/{id}Soft-delete or hard-delete an organization
Archive organizationPOST/organizations/{id}/archiveCustom action: archive organization and cascade to projects

Project actions:

ActionHTTP MethodEndpointDescription
List projectsGET/projects or /organizations/{orgId}/projectsReturn paginated list of projects
Create projectPOST/projects or /organizations/{orgId}/projectsCreate a new project
Get projectGET/projects/{id}Return details of a specific project
Update projectPATCH/projects/{id}Partially update project fields
Delete projectDELETE/projects/{id}Delete a project
Clone projectPOST/projects/{id}/cloneCustom action: duplicate a project with its tasks

Task actions:

ActionHTTP MethodEndpointDescription
List tasksGET/tasks or /projects/{projectId}/tasksReturn paginated, filterable list of tasks
Create taskPOST/tasks or /projects/{projectId}/tasksCreate a new task
Get taskGET/tasks/{id}Return details of a specific task
Update taskPATCH/tasks/{id}Partially update task fields
Delete taskDELETE/tasks/{id}Delete a task
Move taskPOST/tasks/{id}/moveCustom action: change task's project or position

Step 5: Design the Interface

Use a tool like Insomnia, Postman, or Stoplight to design endpoints before writing code. Focus on:

  • Route structure and HTTP methods
  • Request headers, query parameters, and body schema
  • Response status codes, headers, and body schema
  • Error response format
  • Pagination, filtering, and sorting parameters

Example: Designing the Create Organization endpoint in Insomnia

  1. Create a new request:

    • Method: POST
    • URL: http://localhost:3000/api/v1/organizations
  2. Define request headers:

    Content-Type: application/json Authorization: Bearer <token>
  3. Define request body (JSON):

    >_ text
    {
      "name": "Acme Corp",
      "status": "active",
      "description": "Leading provider of widgets"
    }
  4. Define expected response:

    • Status: 201 Created
    • Body:
    >_ text
    {
      "id": "org_123abc",
      "name": "Acme Corp",
      "status": "active",
      "description": "Leading provider of widgets",
      "createdAt": "2025-06-01T10:30:00Z",
      "updatedAt": "2025-06-01T10:30:00Z"
    }
  5. Define error responses:

    • 400 Bad Request: Validation errors
    • 401 Unauthorized: Missing or invalid token
    • 403 Forbidden: User lacks permission to create organizations
    • 409 Conflict: Organization name already exists
  6. Document the endpoint: Create Organization

POST /api/v1/organizations

Creates a new organization. The caller must have the org:create permission.

Request

Headers

  • Authorization: Bearer <token> (required)
  • Content-Type: application/json (required)

Body

>_ text
{
  "name": "string (required, 3-100 chars, unique)",
  "status": "active | archived (optional, default: active)",
  "description": "string (optional, max 500 chars)"
}

Response

201 Created

>_ text
{
  "id": "string",
  "name": "string",
  "status": "string",
  "description": "string | null",
  "createdAt": "ISO8601 timestamp",
  "updatedAt": "ISO8601 timestamp"
}

400 Bad Request

>_ text
{
  "error": "Validation failed",
  "details": [
    {
      "field": "name",
      "message": "Name is required"
    }
  ]
}

This design-first approach ensures you think through the consumer experience before writing implementation code. It also creates living documentation that stays in sync with your API.

#Designing Organization APIs

Let's design every endpoint for the organizations resource. We will use Insomnia-style examples, but the patterns apply to any API client or documentation tool.

List Organizations (GET)

Endpoint: GET /api/v1/organizations

Purpose: Return a paginated list of organizations the authenticated user can access.

Query parameters:

ParameterTypeRequiredDefaultDescription
pageintegerNo1Page number (1-indexed)
limitintegerNo20Items per page (max: 100)
sortBystringNo"createdAt"Field to sort by (name, createdAt, updatedAt)
sortOrderstringNo"descending"Sort direction (ascending, descending)
statusstringNo-Filter by status (active, archived)
searchstringNo-Filter by name or description (case-insensitive partial match)

Request example:

>_ http
GET /api/v1/organizations?page=1&limit=10&sortBy=createdAt&sortOrder=descending&status=active
Authorization: Bearer abc123

Success response (200 OK):

>_ text
{
  "data": [
    {
      "id": "org_123abc",
      "name": "Acme Corp",
      "status": "active",
      "description": "Leading provider of widgets",
      "createdAt": "2025-01-15T10:30:00Z",
      "updatedAt": "2025-01-15T10:30:00Z"
    },
    {
      "id": "org_456def",
      "name": "Beta Industries",
      "status": "active",
      "description": "Innovative solutions for modern businesses",
      "createdAt": "2025-01-10T14:22:00Z",
      "updatedAt": "2025-01-20T09:15:00Z"
    }
  ],
  "pagination": {
    "total": 47,
    "page": 1,
    "limit": 10,
    "totalPages": 5,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Response fields explained:

FieldTypeDescription
dataarrayThe requested portion of organization records
pagination.totalintegerTotal count of organizations matching the filter (ignoring pagination)
pagination.pageintegerCurrent page number (1-indexed)
pagination.limitintegerItems per page
pagination.totalPagesintegerTotal pages available for the current filter
pagination.hasNextPagebooleanWhether there is a next page
pagination.hasPrevPagebooleanWhether there is a previous page

Error responses:

>_ text
// 401 Unauthorized - Missing or invalid token
{
  "error": "Authentication required",
  "code": "AUTH_REQUIRED"
}

// 403 Forbidden - User lacks permission to list organizations
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

// 400 Bad Request - Invalid query parameters
{
  "error": "Invalid request parameters",
  "details": [
    { "field": "limit", "message": "Limit must be between 1 and 100" }
  ]
}

Create Organization (POST)

Endpoint: POST /api/v1/organizations

Purpose: Create a new organization. The authenticated user becomes the owner.

Request headers:

Authorization: Bearer abc123 Content-Type: application/json

Request body:

>_ text
{
  "name": "Acme Corp",
  "status": "active",
  "description": "Leading provider of widgets"
}

Request body schema:

FieldTypeRequiredConstraintsDescription
namestringYes3-100 chars, uniqueOrganization name
statusstringNoenum: active, archivedInitial status (default: active)
descriptionstringNomax 500 charsOptional description

Success response (201 Created):

>_ text
{
  "id": "org_123abc",
  "name": "Acme Corp",
  "status": "active",
  "description": "Leading provider of widgets",
  "createdAt": "2025-06-01T10:30:00Z",
  "updatedAt": "2025-06-01T10:30:00Z"
}

Why 201 Created? The request created a new resource. The response includes the full representation of the created resource.

Error responses:

>_ text
// 400 Bad Request - Validation errors
{
  "error": "Validation failed",
  "details": [
    { "field": "name", "message": "Name is required" },
    { "field": "name", "message": "Name must be at least 3 characters" }
  ]
}

// 409 Conflict - Name already exists
{
  "error": "Organization name already exists",
  "code": "RESOURCE_CONFLICT",
  "field": "name"
}

// 403 Forbidden - User lacks permission to create organizations
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

Get Single Organization (GET)

Endpoint: GET /api/v1/organizations/{id}

Purpose: Return details of a specific organization.

Path parameters:

ParameterTypeRequiredDescription
idstringYesOrganization ID (UUID format)

Request example:

>_ http
GET /api/v1/organizations/org_123abc
Authorization: Bearer abc123

Success response (200 OK):

>_ text
{
  "id": "org_123abc",
  "name": "Acme Corp",
  "status": "active",
  "description": "Leading provider of widgets",
  "createdAt": "2025-01-15T10:30:00Z",
  "updatedAt": "2025-01-15T10:30:00Z",
  "memberCount": 12,
  "projectCount": 5
}

Note: The response includes computed fields (memberCount, projectCount) that are derived from related resources. These are safe to include in a GET response because they do not require client-side joins.

Error responses:

>_ text
// 404 Not Found - Organization does not exist or user lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

// 401 Unauthorized - Missing or invalid token
{
  "error": "Authentication required",
  "code": "AUTH_REQUIRED"
}

Important: Return 404 for both "resource does not exist" and "user lacks permission to access this resource." This prevents information leakage about the existence of resources the user cannot access.

Update Organization (PATCH)

Endpoint: PATCH /api/v1/organizations/{id}

Purpose: Partially update an organization's fields.

Path parameters:

ParameterTypeRequiredDescription
idstringYesOrganization ID

Request body:

>_ text
{
  "status": "archived"
}

Request body rules:

  • Only include fields you want to update.
  • Omitted fields remain unchanged.
  • All fields follow the same validation rules as POST.

Success response (200 OK):

>_ text
{
  "id": "org_123abc",
  "name": "Acme Corp",
  "status": "archived",
  "description": "Leading provider of widgets",
  "createdAt": "2025-01-15T10:30:00Z",
  "updatedAt": "2025-06-01T15:30:00Z"
}

Note: The updatedAt timestamp changes to reflect the modification. The response includes the full updated resource.

Error responses:

>_ text
// 400 Bad Request - Validation errors
{
  "error": "Validation failed",
  "details": [
    { "field": "status", "message": "Status must be one of: active, archived" }
  ]
}

// 404 Not Found - Organization does not exist or user lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

// 403 Forbidden - User lacks permission to update this organization
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

// 409 Conflict - Update would violate a constraint (e.g., duplicate name)
{
  "error": "Organization name already exists",
  "code": "RESOURCE_CONFLICT",
  "field": "name"
}

Delete Organization (DELETE)

Endpoint: DELETE /api/v1/organizations/{id}

Purpose: Delete an organization. This may be a soft delete (mark as deleted) or hard delete (remove from database), depending on your business requirements.

Path parameters:

ParameterTypeRequiredDescription
idstringYesOrganization ID

Request example:

>_ http
DELETE /api/v1/organizations/org_123abc
Authorization: Bearer abc123

Success response (204 No Content):

(empty body)

Why 204 No Content? The resource has been deleted. There is no representation to return. Returning the deleted resource would be misleading because it no longer exists in the active dataset.

Error responses:

>_ text
// 404 Not Found - Organization does not exist or user lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

// 403 Forbidden - User lacks permission to delete this organization
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

// 409 Conflict - Organization has active projects that must be handled first
{
  "error": "Cannot delete organization with active projects",
  "code": "RESOURCE_CONFLICT",
  "details": {
    "activeProjects": 3,
    "suggestion": "Archive or delete projects before deleting the organization"
  }
}

Custom Action: Archive Organization

Endpoint: POST /api/v1/organizations/{id}/archive

Purpose: Archive an organization. This is a custom action because it triggers complex server-side logic beyond a simple status update.

Why a custom action instead of PATCH? Archiving an organization may:

  1. Update the organization's status to "archived".
  2. Cascade to associated projects: mark them as archived or delete them based on business rules.
  3. Revoke or downgrade member permissions.
  4. Send notifications to organization members.
  5. Log the action for audit purposes.
  6. Update search indexes to exclude archived organizations.

This complexity justifies a dedicated endpoint with clear semantics.

Path parameters:

ParameterTypeRequiredDescription
idstringYesOrganization ID

Request body:

>_ text
{
  "reason": "Company restructuring",
  "archiveProjects": true
}

Request body schema:

FieldTypeRequiredDescription
reasonstringNoOptional reason for archival (for audit logs)
archiveProjectsbooleanNoWhether to archive associated projects (default: true)

Success response (200 OK):

>_ text
{
  "id": "org_123abc",
  "name": "Acme Corp",
  "status": "archived",
  "description": "Leading provider of widgets",
  "createdAt": "2025-01-15T10:30:00Z",
  "updatedAt": "2025-06-01T15:30:00Z",
  "archivedAt": "2025-06-01T15:30:00Z",
  "archivedBy": "usr_456def",
  "archivedReason": "Company restructuring",
  "affectedResources": {
    "projectsArchived": 5,
    "tasksArchived": 42,
    "membersNotified": 12
  }
}

Why 200 OK instead of 201 Created? The action updated an existing resource (the organization) rather than creating a new one. The response includes the updated resource plus metadata about the action's effects.

Error responses:

>_ text
// 400 Bad Request - Invalid request body
{
  "error": "Validation failed",
  "details": [
    { "field": "archiveProjects", "message": "archiveProjects must be a boolean" }
  ]
}

// 404 Not Found - Organization does not exist or user lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

// 403 Forbidden - User lacks permission to archive this organization
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

// 409 Conflict - Organization is already archived
{
  "error": "Organization is already archived",
  "code": "RESOURCE_CONFLICT"
}

#Pagination, Sorting, and Filtering

List endpoints (GET /resources) need three features to be usable at scale: pagination, sorting, and filtering.

Why Pagination Exists

Returning all records in a single response does not scale. Consider an endpoint that lists tasks:

GET /api/v1/tasks

If your database contains 100,000 tasks, returning all of them in one response would:

  1. Consume excessive server resources: Serializing 100,000 JSON objects is CPU-intensive.
  2. Consume excessive network bandwidth: A 50MB JSON response takes time to transmit.
  3. Overwhelm the client: Parsing and rendering 100,000 items in a browser or mobile app is slow and memory-intensive.
  4. Provide poor user experience: Users rarely need to see all 100,000 tasks at once.

Pagination solves these problems by returning data in chunks.

Pagination Response Structure

Use a consistent structure for paginated responses:

>_ text
{
  "data": [/* array of resource objects */],
  "pagination": {
    "total": 100000,
    "page": 1,
    "limit": 20,
    "totalPages": 5000,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}
FieldTypeDescription
dataarrayThe requested portion of records
pagination.totalintegerTotal count of records matching the filter (ignoring pagination)
pagination.pageintegerCurrent page number (1-indexed)
pagination.limitintegerItems per page
pagination.totalPagesintegerTotal pages available for the current filter
pagination.hasNextPagebooleanWhether there is a next page
pagination.hasPrevPagebooleanWhether there is a previous page

Why include total and totalPages? These fields enable UI features like:

  • "Showing 1-20 of 100,000 tasks"
  • Page number navigation: "1 2 3 ... 5000"
  • Progress indicators: "Page 1 of 5000"

Why include hasNextPage and hasPrevPage? These boolean fields simplify client logic for infinite scroll or "Load more" buttons. The client does not need to calculate whether a next page exists.

Pagination in Practice

Query parameters:

ParameterTypeRequiredDefaultConstraintsDescription
pageintegerNo1min: 1Page number (1-indexed)
limitintegerNo20min: 1, max: 100Items per page

Examples:

>_ http
# Get first page with default limit (20 items)
GET /api/v1/organizations

# Get second page with custom limit (10 items)
GET /api/v1/organizations?page=2&limit=10

# Get last page (calculate page number from total/limit)
GET /api/v1/organizations?page=5000&limit=20

Server-side implementation considerations:

  1. Validate parameters: Ensure page and limit are within acceptable ranges. Return 400 Bad Request for invalid values.

  2. Apply defaults: If the client omits page or limit, use sensible defaults (page=1, limit=20).

  3. Enforce maximum limit: Prevent clients from requesting excessive data in a single response (e.g., limit=10000). Return an error or cap the limit.

  4. Count efficiently: Calculating total requires a COUNT(*) query, which can be expensive on large tables. Consider:

    • Caching the count for frequently accessed filters
    • Using approximate counts for very large datasets
    • Omitting total for endpoints where it is not critical
  5. Sort before paginating: Apply sorting before slicing the result set. Otherwise, page boundaries may shift between requests.

Sorting in List APIs

Clients should control the order of results. Provide sortBy and sortOrder parameters.

Query parameters:

ParameterTypeRequiredDefaultAllowed ValuesDescription
sortBystringNo"createdAt"name, createdAt, updatedAt, statusField to sort by
sortOrderstringNo"descending"ascending, descendingSort direction

Examples:

>_ http
# Default sort: newest first
GET /api/v1/organizations

# Sort by name alphabetically
GET /api/v1/organizations?sortBy=name&sortOrder=ascending

# Sort by last updated, oldest first
GET /api/v1/organizations?sortBy=updatedAt&sortOrder=ascending

Server-side implementation:

  1. Whitelist sortable fields: Only allow sorting on fields that are indexed and make sense for ordering. Reject unknown sortBy values with 400 Bad Request.

  2. Map client field names to database columns: The API may use createdAt, but the database column might be created_at. Handle this mapping internally.

  3. Apply defaults: If the client omits sortBy or sortOrder, use sensible defaults (sortBy=createdAt, sortOrder=descending).

  4. Combine with pagination: Apply sorting before slicing the result set for pagination.

Filtering in List APIs

Clients should filter results by field values. Support filtering on commonly queried fields.

Query parameters:

Use field names directly as query parameters. Support exact match, partial match, and range filters.

Filter TypeExampleDescription
Exact match?status=activeReturn resources where status equals "active"
Partial match?search=acmeReturn resources where name or description contains "acme" (case-insensitive)
Range (gte/lte)?createdAt[gte]=2025-01-01&createdAt[lte]=2025-12-31Return resources created in 2025
Multiple values?status=active,archivedReturn resources where status is either "active" or "archived"

Examples:

>_ http
# Filter by status
GET /api/v1/organizations?status=active

# Search by name or description
GET /api/v1/organizations?search=acme

# Filter by date range
GET /api/v1/organizations?createdAt[gte]=2025-01-01

# Combine filters
GET /api/v1/organizations?status=active&search=acme&sortBy=createdAt&sortOrder=descending

Server-side implementation:

  1. Whitelist filterable fields: Only allow filtering on fields that are indexed and safe to query. Reject unknown filter fields with 400 Bad Request.

  2. Sanitize input: Prevent injection attacks by parameterizing queries. Never interpolate user input directly into SQL.

  3. Support multiple filter types: Implement exact match, partial match, and range filters for flexible querying.

  4. Combine filters with AND logic: By default, combine multiple filters with AND. Support OR logic via a separate parameter if needed (e.g., ?status=active,archived).

Combining Parameters

All three features work together:

>_ http
GET /api/v1/tasks?projectId=proj_456&status=pending&priority=high&sortBy=dueDate&sortOrder=ascending&page=1&limit=20

This request:

  • Filters tasks to a specific project (projectId=proj_456)
  • Filters to pending tasks with high priority (status=pending&priority=high)
  • Sorts by due date, earliest first (sortBy=dueDate&sortOrder=ascending)
  • Returns the first page of 20 results (page=1&limit=20)

Design guidelines:

  1. Document supported parameters: Clearly list which query parameters are supported for each endpoint.

  2. Provide examples: Include example requests in your documentation to help consumers understand how to combine parameters.

  3. Validate combinations: Some parameter combinations may not make sense (e.g., search with id). Return helpful errors for invalid combinations.

  4. Consider performance: Complex filter combinations can be expensive. Use database indexes and query planning to optimize performance.

#Designing Project APIs

Apply the same patterns to the projects resource. Consistency across resources reduces cognitive load for API consumers.

Create Project (POST)

Endpoint: POST /api/v1/projects

Purpose: Create a new project within an organization.

Request headers:

Authorization: Bearer abc123 Content-Type: application/json

Request body:

>_ text
{
  "name": "Website Redesign",
  "organizationId": "org_123abc",
  "status": "planned",
  "description": "Refresh the company website with modern design and improved UX"
}

Request body schema:

FieldTypeRequiredConstraintsDescription
namestringYes3-100 charsProject name
organizationIdstringYesvalid UUIDID of the parent organization
statusstringNoenum: planned, in-progress, completedInitial status (default: planned)
descriptionstringNomax 500 charsOptional description

Success response (201 Created):

>_ text
{
  "id": "proj_456def",
  "name": "Website Redesign",
  "organizationId": "org_123abc",
  "status": "planned",
  "description": "Refresh the company website with modern design and improved UX",
  "createdAt": "2025-06-01T16:00:00Z",
  "updatedAt": "2025-06-01T16:00:00Z"
}

Error responses:

>_ text
// 400 Bad Request - Validation errors
{
  "error": "Validation failed",
  "details": [
    { "field": "name", "message": "Name is required" },
    { "field": "organizationId", "message": "Invalid organization ID" }
  ]
}

// 403 Forbidden - User lacks permission to create projects in this organization
{
  "error": "Insufficient permissions",
  "code": "PERMISSION_DENIED"
}

// 404 Not Found - Organization does not exist or user lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

List Projects (GET)

Endpoint: GET /api/v1/projects

Purpose: Return a paginated, filterable list of projects.

Query parameters:

ParameterTypeRequiredDefaultDescription
pageintegerNo1Page number
limitintegerNo20Items per page
sortBystringNo"createdAt"Field to sort by
sortOrderstringNo"descending"Sort direction
organizationIdstringNo-Filter by organization
statusstringNo-Filter by status
searchstringNo-Search by name or description

Request example:

>_ http
GET /api/v1/projects?organizationId=org_123abc&status=in-progress&limit=10
Authorization: Bearer abc123

Success response (200 OK):

>_ text
{
  "data": [
    {
      "id": "proj_456def",
      "name": "Website Redesign",
      "organizationId": "org_123abc",
      "status": "in-progress",
      "description": "Refresh the company website",
      "createdAt": "2025-06-01T16:00:00Z",
      "updatedAt": "2025-06-01T16:00:00Z"
    }
  ],
  "pagination": {
    "total": 12,
    "page": 1,
    "limit": 10,
    "totalPages": 2,
    "hasNextPage": true,
    "hasPrevPage": false
  }
}

Get Single Project (GET)

Endpoint: GET /api/v1/projects/{id}

Purpose: Return details of a specific project.

Path parameters:

ParameterTypeRequiredDescription
idstringYesProject ID

Success response (200 OK):

>_ text
{
  "id": "proj_456def",
  "name": "Website Redesign",
  "organizationId": "org_123abc",
  "status": "in-progress",
  "description": "Refresh the company website",
  "createdAt": "2025-06-01T16:00:00Z",
  "updatedAt": "2025-06-01T16:00:00Z",
  "taskCount": 24,
  "completedTaskCount": 8,
  "progress": 33
}

Note: Computed fields (taskCount, completedTaskCount, progress) provide useful summary information without requiring client-side joins.

Update Project (PATCH)

Endpoint: PATCH /api/v1/projects/{id}

Purpose: Partially update a project's fields.

Request body:

>_ text
{
  "status": "completed",
  "description": "Website redesign launched successfully"
}

Success response (200 OK):

>_ text
{
  "id": "proj_456def",
  "name": "Website Redesign",
  "organizationId": "org_123abc",
  "status": "completed",
  "description": "Website redesign launched successfully",
  "createdAt": "2025-06-01T16:00:00Z",
  "updatedAt": "2025-06-01T18:30:00Z"
}

Delete Project (DELETE)

Endpoint: DELETE /api/v1/projects/{id}

Purpose: Delete a project.

Success response (204 No Content):

(empty body)

Error response (409 Conflict):

>_ text
{
  "error": "Cannot delete project with active tasks",
  "code": "RESOURCE_CONFLICT",
  "details": {
    "activeTasks": 5,
    "suggestion": "Complete or delete tasks before deleting the project"
  }
}

Custom Action: Clone Project

Endpoint: POST /api/v1/projects/{id}/clone

Purpose: Clone a project, including its tasks and metadata.

Why a custom action? Cloning a project is more complex than creating a new project with the same fields:

  1. Copy the project's metadata (name, description, status) with modifications (e.g., append " - Copy" to the name).
  2. Duplicate all tasks associated with the project, preserving their structure but assigning new IDs.
  3. Preserve task assignments, comments, and attachments if applicable.
  4. Send notifications to project members about the clone.
  5. Log the action for audit purposes.

This complexity justifies a dedicated endpoint.

Request body:

>_ text
{
  "name": "Website Redesign - Copy",
  "status": "planned",
  "includeTasks": true,
  "includeComments": false
}

Request body schema:

FieldTypeRequiredDefaultDescription
namestringNo"{originalName} - Copy"Name for the cloned project
statusstringNo"planned"Initial status for the clone
includeTasksbooleanNotrueWhether to clone associated tasks
includeCommentsbooleanNofalseWhether to clone task comments

Success response (201 Created):

>_ text
{
  "id": "proj_789ghi",
  "name": "Website Redesign - Copy",
  "organizationId": "org_123abc",
  "status": "planned",
  "description": "Refresh the company website",
  "createdAt": "2025-06-01T19:00:00Z",
  "updatedAt": "2025-06-01T19:00:00Z",
  "clonedFrom": "proj_456def",
  "clonedAt": "2025-06-01T19:00:00Z",
  "clonedBy": "usr_456def",
  "affectedResources": {
    "tasksCloned": 24,
    "commentsCloned": 0
  }
}

Why 201 Created? The action created a new resource (the cloned project). The response includes the new resource plus metadata about the clone operation.

#Consistency Across Resources

Consistency is one of the most important characteristics of a well-designed API. When your API behaves predictably across resources, consumers can integrate faster with fewer mistakes.

JSON Field Naming

Always use camelCase for JSON field names:

>_ text
 { "createdAt": "2025-06-01T10:30:00Z", "organizationId": "org_123" }
 { "created_at": "2025-06-01T10:30:00Z", "organization_id": "org_123" }  // snake_case
 { "CreatedAt": "2025-06-01T10:30:00Z", "OrganizationId": "org_123" }  // PascalCase

Why camelCase?

  • JavaScript convention: Most API consumers use JavaScript/TypeScript, where camelCase is standard.
  • Consistency: Stick to one convention across your entire API.
  • Tooling: Many JSON libraries and code generators expect camelCase.

Exception: If your API primarily serves a language that uses a different convention (e.g., Python with snake_case), you may choose that convention. But be consistent within your API.

Payload Structure

Use consistent field names for the same concept across resources:

>_ text
// Organization payload
{ "name": "Acme Corp", "description": "Widget maker", "status": "active" }

// Project payload - same field names
{ "name": "Website Redesign", "description": "Refresh the website", "status": "planned" }

// Task payload - same field names
{ "title": "Implement login", "description": "Add user authentication", "status": "pending" }

Note: Tasks use title instead of name because "task title" is more semantically accurate than "task name." This is an acceptable deviation when the semantics differ.

Avoid inconsistent abbreviations:

>_ text
 { "description": "Details about the project" }
 { "desc": "Details about the project" }  // Unclear abbreviation
 { "dsc": "Details about the project" }   // Even less clear

Route Patterns

Apply the same structure across resources:

/api/v1/organizations /api/v1/projects /api/v1/tasks /api/v1/organization // singular: inconsistent /api/v1/Project // PascalCase: inconsistent /api/v1/tasks_list // suffix: inconsistent

Nested resource patterns:

/api/v1/organizations/123/projects /api/v1/projects/456/tasks /api/v1/orgs/123/projs // inconsistent abbreviations /api/v1/organization/123/project // singular: inconsistent

Query Parameter Names

Use consistent parameter names for common operations:

# Pagination (all list endpoints) ?page=1&limit=20 # Sorting (all list endpoints) ?sortBy=createdAt&sortOrder=descending # Filtering (all list endpoints) ?status=active&search=acme # Date ranges (all list endpoints) ?createdAt[gte]=2025-01-01&createdAt[lte]=2025-12-31

Do not rename parameters for different resources:

/api/v1/organizations?status=active /api/v1/projects?status=active /api/v1/tasks?status=active /api/v1/organizations?status=active /api/v1/projects?state=active // inconsistent parameter name /api/v1/tasks?taskStatus=active // overly verbose

#Status Code Reference

Use HTTP status codes to convey the outcome of a request. Consumers rely on these codes to handle responses appropriately.

Success Codes (2xx)

CodeNameWhen to UseExample
200OKStandard success for GET, PATCH, or custom actions that update existing resourcesGET /users/123 returns user data
201CreatedA new resource was createdPOST /users returns the new user
204No ContentThe request succeeded but there is no response bodyDELETE /users/123 returns empty
202AcceptedThe request was accepted for processing but is not completePOST /reports/generate returns a job ID

Client Error Codes (4xx)

CodeNameWhen to UseExample
400Bad RequestThe request is malformed or contains invalid parametersMissing required field, invalid enum value
401UnauthorizedAuthentication is required or the token is invalidMissing Authorization header
403ForbiddenThe user is authenticated but lacks permissionUser tries to delete an organization they do not own
404Not FoundThe requested resource does not exist or the user lacks accessGET /users/999 where user 999 does not exist
409ConflictThe request conflicts with the current state of the resourceCreating a user with an email that already exists
422Unprocessable EntityThe request is well-formed but contains semantic errorsValidation failed: name too short
429Too Many RequestsThe client has exceeded rate limitsClient sends 100 requests per second when limit is 10

Server Error Codes (5xx)

CodeNameWhen to UseExample
500Internal Server ErrorAn unexpected error occurred on the serverDatabase connection failed, unhandled exception
502Bad GatewayThe server received an invalid response from an upstream serviceAPI gateway cannot reach the application server
503Service UnavailableThe server is temporarily unable to handle requestsMaintenance mode, database overload
504Gateway TimeoutThe server did not receive a timely response from an upstream serviceUpstream service took too long to respond

Important Guidelines

  1. List endpoints never return 404 for empty results: If a list query matches zero resources, return 200 OK with an empty data array. 404 is only for when a specific resource ID does not exist.
>_ text
GET /api/v1/organizations?status=archived  // No archived orgs
{
  "data": [],
  "pagination": { "total": 0, "page": 1, "limit": 20, "totalPages": 0 }
}

GET /api/v1/organizations?status=archived  // Incorrect: 404 for empty list
{
  "error": "No organizations found"
}
  1. Use 404 for missing resources, not permission errors: Return 404 when a resource does not exist OR when the user lacks permission to access it. This prevents information leakage.
>_ text
GET /api/v1/organizations/999  // User lacks access
{
  "error": "Organization not found",
  "code": "RESOURCE_NOT_FOUND"
}

GET /api/v1/organizations/999  // Incorrect: reveals resource exists
{
  "error": "You do not have permission to access this organization",
  "code": "PERMISSION_DENIED"
}
  1. Include error details for 400 and 422: Help consumers fix validation errors by including field-specific messages.
>_ text
{
  "error": "Validation failed",
  "details": [
    { "field": "email", "message": "Invalid email format" },
    { "field": "password", "message": "Password must be at least 8 characters" }
  ]
}
  1. Do not expose internal errors to clients: For 500 errors, return a generic message. Log the full error server-side for debugging.
>_ text
{ "error": "Internal server error", "code": "INTERNAL_ERROR" }
{ "error": "Database connection failed: ECONNREFUSED 127.0.0.1:5432" }

#Best Practices for API Design

Provide Interactive Documentation

Documentation is not optional. Consumers cannot integrate your API if they do not know how it works.

Use OpenAPI/Swagger:

  • Define your API contract in YAML or JSON using the OpenAPI Specification.
  • Generate interactive documentation with Swagger UI or Redoc.
  • Allow consumers to test endpoints directly from the documentation.
  • Auto-generate client SDKs in multiple languages.

Example OpenAPI snippet:

>_ text
paths:
  /organizations:
    post:
      summary: Create a new organization
      operationId: createOrganization
      tags:
        - Organizations
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateOrganizationRequest'
      responses:
        '201':
          description: Organization created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Organization'
        '400':
          description: Validation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ValidationError'

Keep documentation in sync:

  • Store your OpenAPI spec in version control alongside your code.
  • Use code generation or validation tools to ensure your implementation matches the spec.
  • Update the spec before deploying changes to production.

Make APIs Intuitive and Consistent

Consumers form expectations based on your first endpoint. Meet those expectations everywhere.

Guidelines:

  1. Follow REST conventions: Use standard HTTP methods, status codes, and URL patterns unless you have a compelling reason to deviate.

  2. Be predictable: If GET /organizations returns a paginated list, then GET /projects should also return a paginated list with the same structure.

  3. Use consistent naming: If you use camelCase for JSON fields in one endpoint, use it everywhere. If you use sortBy for sorting in one list endpoint, use it in all list endpoints.

  4. Document deviations: If you must deviate from conventions (e.g., using PUT for partial updates), document the reason clearly.

Provide Sane Defaults

Do not force consumers to send obvious parameters. Provide sensible defaults that cover the common case.

Examples:

>_ text
// Pagination defaults
if (!req.query.page) req.query.page = 1;
if (!req.query.limit) req.query.limit = 20;

// Sorting defaults
if (!req.query.sortBy) req.query.sortBy = 'createdAt';
if (!req.query.sortOrder) req.query.sortOrder = 'descending';

// Status default for create
if (!req.body.status) req.body.status = 'active';

Benefits:

  • Simpler client code: Consumers do not need to send parameters for the common case.
  • Better user experience: APIs work out of the box without configuration.
  • Reduced errors: Fewer required parameters means fewer validation errors.

Caveat: Do not hide important behavior behind defaults. If a parameter significantly changes the response (e.g., include=comments), document it clearly even if it has a default.

Avoid Abbreviations

Clarity beats brevity. Consumers should not need to guess what your fields mean.

>_ text
 { "description": "Details about the project", "createdAt": "2025-06-01T10:30:00Z" }
 { "desc": "Details about the project", "created": "2025-06-01T10:30:00Z" }
 { "dsc": "Details about the project", "created_at": "2025-06-01T10:30:00Z" }

Why avoid abbreviations?

  • Ambiguity: desc could mean "description" or "descending".
  • Onboarding: New consumers spend time deciphering your field names.
  • Maintenance: Abbreviations are harder to search and refactor.

Exception: Well-known abbreviations that are part of the domain (e.g., id for identifier, url for uniform resource locator) are acceptable.

Design Before You Code

Spend time designing your API interface before writing implementation code.

Benefits:

  • Catch design flaws early: It is cheaper to change a JSON schema in a document than in production code.
  • Align stakeholders: Product, frontend, and backend teams can review and agree on the API contract before implementation.
  • Generate documentation: Your design document becomes the foundation for your API docs.

Process:

  1. Sketch endpoints in Insomnia, Postman, or Stoplight.
  2. Define request/response schemas for each endpoint.
  3. Review with frontend engineers and product managers.
  4. Iterate on the design based on feedback.
  5. Implement the API to match the design.
  6. Generate documentation from the design.

Tooling:

  • Insomnia/Postman: Design and test endpoints interactively.
  • Stoplight Studio: Visual OpenAPI editor with collaboration features.
  • openapi-generator: Generate server stubs and client SDKs from your OpenAPI spec.

#Common Pitfalls and How to Avoid Them

Pitfall 1: Inconsistent Error Formats

Problem: Different endpoints return errors in different formats, forcing consumers to write custom parsing logic for each endpoint.

>_ text
// Endpoint A
{ "error": "Invalid email" }

// Endpoint B
{ "message": "Email format is invalid", "field": "email" }

// Endpoint C
{ "errors": [{ "code": "INVALID_EMAIL", "path": "email" }] }

Solution: Define a standard error format and use it everywhere.

>_ text
{
  "error": "Validation failed",
  "code": "VALIDATION_ERROR",
  "details": [
    { "field": "email", "message": "Invalid email format" }
  ]
}

Pitfall 2: Leaking Internal Details

Problem: Error messages or response fields expose implementation details that should remain internal.

>_ text
// Bad: Exposes database schema
{
  "error": "Duplicate entry 'alice@example.com' for key 'users.email_unique'",
  "sql": "INSERT INTO users (email) VALUES ('alice@example.com')"
}

// Bad: Exposes file paths
{
  "error": "File not found: /var/www/uploads/avatar.jpg"
}

Solution: Return user-friendly messages. Log internal details server-side.

>_ text
{
  "error": "Email already exists",
  "code": "RESOURCE_CONFLICT",
  "field": "email"
}

Pitfall 3: Over-Nesting Resources

Problem: Deeply nested paths become hard to work with and maintain.

/api/v1/organizations/123/projects/456/tasks/789/comments/101/replies/202

Solution: Flatten the path and use query parameters for filtering.

/api/v1/tasks/789/comments/101/replies /api/v1/replies?commentId=101&taskId=789

Pitfall 4: Ignoring Versioning

Problem: Making breaking changes to your API without versioning breaks existing consumers.

Solution: Include the version in the URL and follow semantic versioning principles.

/api/v1/organizations /api/v2/organizations // New version with breaking changes

Pitfall 5: Not Testing Edge Cases

Problem: APIs work for the happy path but fail for edge cases (empty results, invalid input, concurrent requests).

Solution: Write comprehensive tests for:

  • Validation errors
  • Authentication and authorization failures
  • Empty result sets
  • Pagination boundaries
  • Rate limiting
  • Concurrent modifications

API design is a skill that improves with practice. The patterns in this guide are not rules to follow blindly. They are tools to help you build APIs that are intuitive, consistent, and maintainable.

Key takeaways:

  1. Start with the consumer experience: Design your API interface before writing code. Use tools like Insomnia or OpenAPI to prototype and document.

  2. Follow REST conventions: Use standard HTTP methods, status codes, and URL patterns. Deviate only when necessary, and document your reasons.

  3. Be consistent: Apply the same naming conventions, response structures, and error formats across all endpoints. Consistency reduces cognitive load for consumers.

  4. Provide sane defaults: Make your APIs work out of the box. Do not force consumers to send obvious parameters.

  5. Document thoroughly: Interactive documentation is not optional. Use OpenAPI/Swagger to generate docs that stay in sync with your code.

  6. Design for evolution: Version your APIs. Plan for breaking changes. Make it easy for consumers to migrate.

When your APIs are well-designed, everyone wins:

  • Frontend engineers integrate faster with fewer support tickets.
  • Third-party developers adopt your platform more readily.
  • Your backend team spends less time fixing misunderstandings and more time building features.
  • Your system scales gracefully as requirements evolve.

Invest in API design. Your future self and your consumers will thank you.

8,567 words left