Design a program API by treating it as a contract that outlives the code behind it. Start by identifying the consumers and the jobs they need done, then model resources and actions, choose a consistent interface style, define request and response shapes, and lock in error, versioning, and security behavior before you write endpoints. In practice, the winning order is: pin down users and use cases, design the surface (names, verbs, resources), specify payloads and status codes, then add reliability rules and document the whole thing. Every choice should optimize for predictable behavior across versions, not for what's easiest to implement today. This guide walks through that sequence for a general-purpose program API you expect other software to call.

Start With Consumers and a Job List, Not an Endpoint List

The most common API design failure isn't a bad framework choice; it's building for an imaginary general caller. Before touching schemas, write down who calls this API and what they're trying to accomplish. For an internal service, that might be three teams: a mobile client that needs fast reads, a batch job that needs bulk writes, and an analytics pipeline that needs consistent exports. Each imposes different constraints—payload size, latency tolerance, pagination needs—and those constraints should shape the surface.

Turn that into a concrete job list. Each entry should read like "a caller can do X so that Y." Examples: "A billing service can fetch a customer's current plan so it can prorate an upgrade." "An admin tool can list all active sessions for a user and revoke one." Notice that each job names a consumer and an outcome; that framing keeps you from exposing internal database tables as a public model.

Two artifacts come out of this step. First, a short scope statement that names what the API is for and, importantly, what it is not for. If your orders API will never handle refunds, say so, because that decision affects resource boundaries later. Second, a list of the top 10–20 jobs ranked by importance. Those are the operations your first design pass must cover; everything else waits.

Success check: Hand your job list to a prospective caller and ask them to trace how they'd accomplish their task. If they can't get from their need to one of your listed jobs without inventing a workaround, the list is incomplete.

Model the Domain as Resources and Actions

Once you know the jobs, model the nouns and verbs. In resource-oriented styles, the nouns become resources—customer, order, invoice, session—and the verbs are the standard operations on them: create, read, update, delete, list. The test for a resource is whether callers need to reference it independently: if a caller must say "this specific thing," it's a resource with its own identifier.

Watch for resources that are really relationships. "A user's membership in a team" is often its own resource when it carries attributes (role, join date) or when membership must be created and revoked separately. Conversely, avoid splitting a single aggregate into too many resources just because the database has separate tables; callers shouldn't have to orchestrate six calls to represent one business operation. A good rule: one caller intent should map to one primary call, plus optional follow-ups.

For actions that don't fit CRUD, name them explicitly rather than overloading update. "Refund an order," "cancel a subscription," "rotate a credential" are distinct operations with their own rules, idempotency needs, and audit trails. A common pattern is a sub-resource action endpoint (for example, a refund resource created under an order) or a dedicated action path. Pick one convention and apply it everywhere, because inconsistency here compounds as the API grows.

A worked boundary example: Suppose a scheduler API manages jobs and runs. Jobs have a definition and a schedule; runs are executions with a start time, status, and logs. Callers list runs for a job, fetch a single run, and cancel an active run. That's three resources—job, schedule, run—and one action (cancel). Trying to express cancel as "update run status to canceled" seems simpler but hides the side effect (stopping running work) behind a state mutation, which makes idempotency and permissions murky.

Choose a Style and Then Be Boringly Consistent

The main families are REST over HTTP with JSON, RPC-style interfaces (including gRPC and JSON-RPC), and GraphQL for client-shaped queries. Each has a good fit:

REST/JSON over HTTP suits general-purpose integration: broad client support, cacheable reads, understandable by anyone who's used an HTTP API. Its weakness is over-fetching for clients that need slices of many resources. gRPC suits high-throughput service-to-service calls with strict schemas and streaming. It's less friendly to ad-hoc browser and scripted callers without tooling. GraphQL suits clients that need flexible shaping across many related resources, at the cost of more complex caching, authorization, and query-cost control. JSON-RPC suits small action-oriented surfaces where a single endpoint with named methods is simpler than resource routing.

The style matters less than applying it without exceptions. If you choose REST, use nouns in paths, plural collection names, and stable HTTP methods; don't invent a verb path on Monday and an update-on-the-resource on Tuesday. If you choose RPC, use one method naming convention and don't leak transport details into method names. Callers learn your API by pattern; every inconsistency forces them to re-read docs.

Here's a compact comparison on equivalent criteria, since this is where teams argue most:

Criterion REST/JSON gRPC GraphQL
Typical caller External, scripts, browsers Internal services Client apps needing flexible queries
Schema contract OpenAPI or similar Protobuf SDL schema
Read caching Strong via HTTP Weak by default Complex
Streaming Limited (SSE/WebSocket) First-class Subscriptions only
Learning curve for callers Low Moderate Moderate-high

The table isn't a verdict; it's a map of trade-offs. Choose based on the consumers from step one, not on what's fashionable. If your callers are mostly unknown external developers, REST/JSON with an OpenAPI document is the lowest-friction default.

Specify Requests, Responses, and Naming Rules

With resources and style fixed, write the actual shapes. Do this before implementation, ideally in a machine-readable schema (OpenAPI for REST, .proto for gRPC, SDL for GraphQL), because the schema becomes the source of truth for docs, client generation, and contract tests.

Define naming rules once and enforce them mechanically. Common conventions: camelCase or snake_case for JSON fields (pick one), plural collection names, and identifier fields ending in _id or Id. Timestamps should be ISO 8601 strings in UTC with an explicit offset or Z, or integer epoch units—document exactly which, because mixing seconds and milliseconds is a classic integration bug. Money should never be a floating-point number; use integer minor units with a currency code, or a decimal string with fixed scale.

Decide what every response carries. A common envelope includes the resource plus metadata; some teams return bare resources and put metadata in headers. Either works if consistent. For lists, define pagination precisely: cursor-based pagination is safer for changing data sets than offset pagination, because inserts and deletes don't shift results. State the page size default and maximum, the cursor field name, and whether the cursor is opaque. If you can't support cursors, say so and explain the consistency caveat.

Partial updates need an explicit rule. With REST, JSON Merge Patch (send only changed fields, null deletes) is simple, while JSON Patch (a list of operations) is more expressive and more complex. Choose one, document what null means, and don't let absence and null mean different things by accident.

Concrete naming example: Instead of POST /getUserData returning { "user_name": ..., "created": 1710000000 }, prefer GET /users/{userId} returning { "id": ..., "displayName": ..., "createdAt": "2025-03-09T14:00:00Z" }. Same data, but a caller can guess the next call without reading docs.

Design Errors, Status Codes, and Idempotency Up Front

Error behavior is part of the contract, not an afterthought. Define a small set of error categories and a consistent body shape. A practical structure includes a stable machine-readable code, a human-readable message, and optional details for field-level problems. The code values should be a closed list you can enumerate, because callers write branching logic against them; the message can change without breaking anyone.

Map categories to transport status codes consistently. In HTTP, 400 for malformed or invalid input, 401 for missing or bad authentication, 403 for authenticated-but-not-allowed, 404 for unknown resource, 409 for state conflicts, 422 for semantically invalid but well-formed input (some teams merge this into 400), 429 for rate limiting, and 5xx for server faults. The exact split between 400 and 422 matters less than applying it the same way every time.

Idempotency deserves its own rule. For any operation that creates or mutates state and could be retried—especially payments, order creation, and message sends—support an idempotency key. The caller sends a unique key with the request; the server stores the first result and replays it for repeats within a defined window. Document the key header name, the retention window, and what happens when a retry reuses the key with different request content (usually a 409 or 422). Without this, network retries create duplicate side effects, and callers can't safely retry.

Failure case to plan for: A caller times out after your server created the resource. If the operation is idempotent, their retry returns the original resource. If it isn't, they've now created two. That single scenario justifies the idempotency rule for every creative operation.

Set Versioning, Deprecation, and Compatibility Rules

APIs age. Decide how change is allowed before the first release, because retrofitting versioning is painful. Three common approaches: path versioning (/v1/...), header or media-type versioning, and additive-only evolution where you never break clients. Many teams combine the last two: keep the surface backward compatible as long as possible and introduce a version boundary only for breaking changes.

Define what counts as breaking. Adding an optional response field is generally non-breaking for tolerant clients but can break strict parsers, so state your tolerance expectation. Removing or renaming fields, changing field types, changing status-code semantics, and tightening validation are breaking. Changing default values can be breaking in effect even if the schema is unchanged.

Write a deprecation policy in advance: how much notice, how deprecation is signaled (a response header and a changelog entry are common), and how long deprecated versions remain available. A practical pattern is to announce, keep both versions running for a stated overlap period, monitor usage, and only then retire. The monitoring piece matters—deprecating a version nobody tracks is how you discover consumers you didn't know existed.

Versioning interacts with documentation: every version needs its own schema snapshot, and your docs should say which version is current. If you offer client SDKs, pin them to versions explicitly rather than using floating latest tags.

Make Security and Access Control Part of the Interface

Authentication and authorization shape the API surface, so design them with the endpoints. Choose an authentication mechanism that fits your consumers: OAuth 2.0 flows for delegated third-party access, scoped API keys or tokens for server-to-server calls, and short-lived credentials where possible. Whatever you pick, define token lifetimes, refresh behavior, and revocation.

Authorization should be modeled per resource and per action, not bolted on per endpoint. A common pattern is scoped access—each token carries scopes that limit which operations are allowed—plus resource-level checks (can this caller see this customer's data?). Design the error response for authorization failures so callers can distinguish "you need a different scope" from "this resource doesn't exist for you." Careful: returning 404 instead of 403 for resources the caller can't see is sometimes deliberate to avoid leaking existence—decide your policy and document it.

Include rate limiting in the interface contract. Specify limits per caller tier, the response when exceeded (429 with a retry hint), and how limits are counted. Also define request size limits, allowed content types, and which fields are considered sensitive in logs. Input validation belongs here too: state maximum string lengths, enum value sets, and numeric ranges in the schema so callers learn constraints from the contract rather than from failures.

For anything touching credentials, personal data, or payments, the general-education nature of this guide ends. Those areas carry regulatory and contractual obligations that vary by jurisdiction and business; get review from your security and legal teams before shipping.

Document, Mock, and Contract-Test the API

Documentation is a deliverable, not a chore. If you wrote a machine-readable schema, generate reference docs from it so they can't drift. Then add the parts a schema can't express: a getting-started path with a working request, authentication setup, pagination and error handling explained with examples, and the versioning and deprecation policy. A good test: can a new caller make a successful authenticated call and handle an error without asking anyone?

Mocks come next. Generating a mock server from the schema lets callers build against the contract before implementation finishes, and it forces you to test whether the schema is complete enough to answer real questions. If the mock can't represent a scenario, the schema is missing something.

Finally, contract tests. These verify that the implementation matches the published schema and that error shapes, status codes, and pagination behavior match the docs. Run them in CI so drift is caught automatically. A practical checklist for the first release:

1: Every listed job has at least one documented call that accomplishes it, with a worked example. 2: Error codes are enumerated and each has a documented status code and example body. 3: Idempotency behavior is specified for every state-changing operation. 4: Pagination, filtering, and sorting are defined with defaults and maximums. 5: Authentication and authorization failure modes are documented, including the 403/404 policy. 6: A mock server generated from the schema answers all top-20 jobs. 7: Contract tests compare live responses to the schema for the happy path and at least one error per category.

Success check: Have someone outside the team follow the getting-started guide start to finish using only the docs and mock. Success is a completed request and a correctly handled error with no clarifying questions. If they get stuck, the gap they hit is your next documentation fix.

Common Design Failures and How to Avoid Them

A few failure patterns show up repeatedly, and each has a cheap prevention:

Leaking the database. Exposing table columns as fields couples callers to your storage. Prevention: define the API model separately and map it in a translation layer, even a thin one.

Inconsistent pagination. One list uses page, another uses offset, a third uses a cursor with no documented format. Prevention: one pagination convention, enforced in review.

Chatty operations. Callers need five calls to complete one task, with no transactional boundary. Prevention: revisit the job list and offer a composite operation when callers routinely chain calls; document ordering and partial-failure behavior.

Silent breaking changes. A field changes type and a client's parser fails. Prevention: the versioning policy from earlier plus contract tests that compare against a frozen schema snapshot.

Unbounded lists. A list endpoint returns everything for large accounts, and callers time out. Prevention: mandatory pagination with a maximum page size from day one, even if early data is small—retrofitting limits is a breaking change.

Ambiguous null. A field is absent in one response and null in another with no rule. Prevention: document the difference or eliminate the ambiguity by always including the field.

Each of these costs more to fix after external adoption than before. The common thread is that callers build assumptions from whatever they observe, so every inconsistency becomes a dependency.

A Worked Sketch: Designing a Small Scheduling API

To make the sequence concrete, here's a compact design for a job-scheduling API, following the steps above.

Consumers and jobs. Two callers: an internal dashboard that lists jobs and their recent runs, and a worker service that claims pending runs and reports completion. Jobs include create a job, list jobs with pagination, fetch a job, update a job's schedule, list runs for a job, fetch a run, claim the next pending run, and report a run result.

Resources. job with id, name, schedule (cron string plus timezone), status, and timestamps. run with id, jobId, status, startedAt, finishedAt, and result. The claim operation doesn't fit CRUD cleanly, so it's an action under a queue resource: create a claim, which atomically selects and locks the next pending run for a lease duration.

Requests and responses. JSON with camelCase, ISO 8601 UTC timestamps, cursor pagination on GET /jobs and GET /jobs/{jobId}/runs. The claim endpoint is a POST that creates a claim resource and returns the claimed run and a lease expiry. Repeating the same idempotency key within the window returns the same claim rather than claiming another run.

Errors. invalid_schedule (400 with details on the cron expression), job_not_found (404), claim_conflict (409 when no run is available or the idempotency key was reused with different input), and rate_limited (429). Each error body has code, message, and optional details.

Versioning and security. Path versioning with /v1, additive fields elsewhere, and a deprecation policy of two releases. Worker credentials use scoped tokens limited to claim and report operations; dashboard tokens are read-only on jobs and runs.

Documentation and tests. The OpenAPI document generates reference docs and a mock. Contract tests cover the happy path for each job, one error per category, pagination boundaries, and the claim idempotency replay case.

That's a design done in sequence: consumers and jobs first, then resources, then shapes, then errors and idempotency, then versioning and security, then docs and tests. Note how many decisions were settled before any handler existed—and how the claim action and its idempotency rule fell out naturally from the worker's need for safe retries.

Where Professional Review Becomes Necessary

Most API design is reversible with versioning and deprecation, but some decisions carry obligations that an individual or small team shouldn't guess at. If the API handles payment credentials, protects personal data, or sits inside a regulated workflow, involve your security, legal, and compliance functions before exposing it. If a breaking change affects active paying consumers or contractual integrations, treat the deprecation plan as a business decision, not just a technical one. And when authentication design touches third-party delegated access, get an explicit review of token lifetimes, scopes, and revocation rather than copying a pattern you saw elsewhere.