Programming fundamentals
REST API Design Principles: Practical Rules With Examples
A well-designed REST API models your data as nouns, uses HTTP methods and status codes the way clients expect, and behaves consistently for errors, pagination and versioning. The goal is that a developer who has never met your team can guess how the next endpoint works.
By CodingMarble · Published · 5 min read

Model resources, not actions
In REST, the URL names a thing and the HTTP method says what to do with it. Use plural nouns for collections: /orders is the collection, and /orders/42 is one order. Nest only when the relationship is real and shallow, such as /orders/42/items, and avoid deep chains like /customers/7/orders/42/items/3/notes because they are hard to read and fragile. Keep names lowercase, use hyphens for multi-word names, and avoid verbs in paths. An endpoint called /getAllOrders repeats what the GET method already says.
Some actions do not fit a noun cleanly, such as cancelling an order or sending a password reset. Two approaches work. You can model the result as a resource, for example POST /orders/42/cancellation, or you can update a state field with PATCH. Pick one convention and apply it across the API. Consistency matters more than which style you choose.
Methods and status codes that mean what they say
- GET reads and must not change data. It is safe to retry and safe for caches.
- POST creates a resource or triggers a process. Return 201 Created with the new resource and a Location header.
- PUT replaces a resource entirely. PATCH changes only the fields you send.
- DELETE removes a resource. Return 204 No Content when there is no body to send back.
Status codes tell clients how to react without parsing the body. 200 means success with a body, 201 means created, 204 means success without a body. 400 means the request itself is malformed or invalid, 401 means the caller is not authenticated, 403 means authenticated but not allowed, 404 means the resource does not exist, 409 means a conflict with the current state such as a duplicate, and 422 is commonly used for well-formed requests that fail validation. 429 means too many requests. 5xx means the server failed and the client may retry. Returning 200 with an error message inside the body defeats monitoring tools, caches and client libraries, so avoid it. The http-status-codes cheat sheet lists the full set.
Idempotency: making retries safe
An operation is idempotent if doing it several times has the same effect as doing it once. GET, PUT and DELETE are meant to behave that way: deleting an order twice leaves it deleted. POST is not idempotent by default, and that is a real problem on unreliable networks. If a client sends a payment request, the connection drops and the client retries, the customer could be charged twice.
The usual fix is an idempotency key. The client generates a unique value per intended action and sends it in a header. The server stores the result against that key, and if the same key arrives again, it returns the stored result instead of repeating the work. Keep keys for a limited time and reject a reused key that comes with a different request body. For any endpoint that creates money-related records or sends messages, this protection is worth adding from the start.
Lists: pagination, filtering and sorting
Never return an unbounded list. A collection that has ten rows today may have a million later, and one request would then exhaust memory and bandwidth. Pagination comes in two common styles. Offset pagination uses page and limit or offset and limit parameters. It is simple and lets users jump to a page, but deep offsets get slower in many databases, and results can shift if rows are added between requests. Cursor pagination returns an opaque cursor for the next page, based on the last item seen. It is stable under inserts and scales better, but you cannot jump to page 50.
Put filters and sorting in query parameters, keep names predictable, and validate them against an allowed list so callers cannot sort by an unindexed column or inject unexpected fields. Always set a maximum limit on the page size and return metadata, such as the next cursor, so clients do not guess.
Versioning and a consistent error shape
Clients you do not control will depend on your response shapes, so changes that remove or rename fields break them. Adding optional fields is usually safe. For breaking changes, version the API, most commonly with a prefix like /v1/orders, though a header-based scheme is also used. Choose one approach, document how long old versions will be supported, and avoid version numbers in individual resources. Do not create a new version for every small change, since each version you keep is something you must maintain.
Errors deserve the same care as successes. Use one error shape for the whole API so clients write a single handler. A machine-readable code lets clients branch on it, a human message helps developers, and a field pointer helps forms highlight the problem. Do not leak stack traces or internal details to callers.
{
"error": {
"code": "validation_failed",
"message": "The request body has invalid fields.",
"details": [
{ "field": "email", "issue": "must be a valid email address" },
{ "field": "quantity", "issue": "must be 1 or more" }
],
"requestId": "req_8f2c1a"
}
}Including a request id lets support and developers find the exact log line for a failed call, which saves a lot of back and forth.
Authentication, rate limits and documentation
Send credentials in the Authorization header, not in the URL, because URLs end up in logs, browser history and referrer headers. Always use HTTPS. Check permissions on the server for every request, including that the caller is allowed to touch this specific resource, since hiding a button in the interface protects nothing. Return 401 when credentials are missing or invalid and 403 when they are valid but insufficient.
Rate limiting protects your service from accidents and abuse. Return 429 with a Retry-After header, and tell well-behaved clients their remaining allowance through headers, using whatever naming convention your gateway or documentation defines. Apply stricter limits to expensive or sensitive endpoints, such as login and password reset.
Documentation is part of the product. An OpenAPI description gives you generated reference pages, client code and a contract you can test against. Add examples of real requests and responses, list error codes, and explain authentication on the first page. Keep the specification in the same repository as the code so changes are reviewed together.
A small before and after
Here is a typical poorly designed set of endpoints for an order system, followed by a cleaned-up equivalent.
POST /getOrders (body: { "customerId": 7 }) -> 200 always
POST /createOrder -> 200 { "status": "error", "msg": "bad qty" }
GET /deleteOrder?id=42 -> deletes data with a GET
POST /updateOrderStatus -> 200
GET /orders -> returns every order ever createdGET /v1/orders?customerId=7&status=paid&limit=20&cursor=abc
-> 200 { "data": [...], "nextCursor": "def" }
POST /v1/orders (Idempotency-Key header)
-> 201 + Location: /v1/orders/42
or 422 with the standard error shape
GET /v1/orders/42 -> 200, or 404 if missing
PATCH /v1/orders/42 (body: { "status": "shipped" })
DELETE /v1/orders/42 -> 204Practical tip: before you publish an endpoint, call it with a client such as curl and look at the raw response. Check the status code, the headers and the body for a success, a validation failure, a missing resource and a request without credentials. If you cannot predict all four responses from the documentation alone, the design or the docs need another pass.
Keep reading
- Web developmentREST vs GraphQL: How to Choose an API StyleREST exposes many URLs that each return a fixed resource, while GraphQL exposes one endpoint where the client describes the exact shape of data it wants. For a small team with a handful of clients, REST is usually the simpler default; GraphQL pays off when many different screens or apps need different slices of the same data.
- Interview questions and cheat sheetsHTTP Status Codes Cheat SheetThis cheat sheet explains the HTTP status codes you meet in real websites and APIs, grouped by class, with guidance on which one to return and why. It also covers redirects and soft 404s for SEO, caching with 304, and how to inspect responses with curl.
- Technology explainedWhat Is an API? A Plain-English Explanation With ExamplesAn API is an agreed way for one piece of software to ask another for data or an action, and to get a structured answer back. Apps use APIs to show weather, maps and payments without building those systems themselves.
- Programming fundamentalsAuthentication: Sessions vs JWT Explained ClearlyA session keeps the login state on the server and gives the browser an opaque ID in a cookie, while a JSON Web Token carries signed claims inside the token itself. Sessions are easier to revoke and are the safer default for a single web app; JWTs suit cases where several services must verify a user without sharing a session store.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.