REST APIs
An API, or application programming interface, is a set of definitions and protocols for building and integrating application software. It's sometimes referred to as a contract between an information provider and an information user—establishing the content required from the consumer (the call) and the content required by the producer (the response).
A REST API (also known as RESTful API) is an application programming interface that conforms to the constraints of REST architecture. REST stands for representational state transfer.
REST is a set of architectural principles, not a protocol or a standard. API developers can implement REST in a variety of ways.
When a request is made via a RESTful API, it transfers a representation of the state of the resource to the requester. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XML, or plain text. JSON is the most generally popular because, despite its name, it's language-agnostic, as well as readable by both humans and machines.
REST implies stateless client-server communication, meaning no client information is stored between requests and each request is separate and unconnected.
Basic Architecture

REST Architectural Constraints
REST APIs must adhere to six architectural constraints:
Client-Server Architecture: Separation of concerns between client and server, allowing independent evolution of both.
Statelessness: Each request contains all information needed; the server stores no client context between requests.
Cacheability: Responses must define themselves as cacheable or non-cacheable to improve performance.
Uniform Interface: Standardized way of communicating through HTTP methods (GET, POST, PUT, DELETE, PATCH).
Layered System: Architecture can be composed of hierarchical layers, with each layer having specific functionality.
Code on Demand (optional): Servers can extend client functionality by transferring executable code.
Routes and HTTP Methods for a Resource

Standard HTTP Methods
GET: Retrieve resource(s) - should be idempotent and safe (no side effects)
POST: Create a new resource - not idempotent
PUT: Update/replace an entire resource - idempotent
PATCH: Partially update a resource - idempotent
DELETE: Remove a resource - idempotent
Advantages of REST APIs
Separates User Interface from Application Logic - enables independent development of frontend and backend
Using the same Application Logic for various Client Apps - a single API can serve websites, mobile apps, IoT devices, and third-party integrations
Computationally more efficient - reduces server load and network traffic by sending UI templates only once and transferring only data
Better for horizontally-scaling - stateless nature allows easy distribution across multiple servers
Micro-services friendly - different APIs can handle different domains (users, products, payments) independently
Wide adoption and tooling - extensive ecosystem of tools, libraries, and developer familiarity
Cacheable responses - improves performance through standard HTTP caching mechanisms
REST vs GraphQL: A Comparison
While REST remains the dominant API architecture, GraphQL has emerged as an alternative approach for certain use cases. Here's a comprehensive comparison:
Data Fetching
Multiple endpoints, fixed data structure per endpoint
Single endpoint, client specifies exact data needed
Over-fetching/Under-fetching
Common issue - endpoints return fixed data structures, often too much or too little
Eliminated - clients request only required fields
Versioning
Typically requires version numbers in URLs (e.g., /api/v1/, /api/v2/)
Schema evolution without versioning - deprecated fields can coexist
Learning Curve
Simpler, follows HTTP conventions, widely understood
Steeper learning curve, requires understanding of query language and schema
Caching
Standard HTTP caching works out-of-the-box (GET requests cached by default)
More complex - requires custom caching solutions or libraries
Error Handling
Uses HTTP status codes (200, 404, 500, etc.)
Always returns 200 OK, errors in response body
Tooling & Ecosystem
Mature ecosystem, extensive tools (Postman, Swagger, REST clients)
Growing ecosystem, specialized tools (GraphiQL, Apollo, Relay)
Documentation
Manual documentation or tools like Swagger/OpenAPI
Self-documenting through introspection
Network Efficiency
Can require multiple round trips for related data
Single request can fetch all nested/related data
Type System
No built-in type system (can be added with OpenAPI/Swagger)
Strong type system built-in, schema definition language
Real-time Updates
Requires separate implementation (WebSockets, Server-Sent Events)
Built-in subscriptions support for real-time data
File Uploads
Straightforward using multipart/form-data
More complex, requires special handling
Monitoring & Analytics
Easy to monitor per endpoint, standard HTTP metrics
Harder to monitor - all requests go to single endpoint
Typical Use Cases
REST is ideal for:
Public APIs with predictable data access patterns
Simple CRUD operations
Microservices architectures with domain-specific services
Applications where HTTP caching is critical
Projects with teams familiar with REST conventions
Examples: Twitter API, GitHub API, Stripe API, payment gateways, authentication services
GraphQL is ideal for:
Applications with complex, nested data requirements
Mobile applications with bandwidth constraints
Dashboards and analytics platforms with varied data needs
Applications requiring real-time updates
Projects with rapidly evolving frontend requirements
Examples: Facebook, GitHub v4 API, Shopify Admin API, content management systems, social media feeds
Hybrid Approach
Some organizations use both: REST for simple, predictable operations and GraphQL for complex data aggregation. For instance, REST for authentication/payments and GraphQL for content delivery.
HTTP Response Codes
HTTP response codes (or status codes) are three-digit numbers returned by a web server in response to an HTTP request made by a client (such as a web browser or a REST API client). These codes indicate the outcome of the request and provide insight into whether the request was successful, encountered errors, or resulted in redirection.
HTTP response codes are grouped into five classes, with each class representing a different type of response. Here's a breakdown:
1xx – Informational Responses
These status codes indicate that the server has received the request and the client can continue to send more information.
100 Continue: The initial part of the request has been received, and the client should continue with the request.
101 Switching Protocols: The server is switching to the protocol the client requested, such as WebSocket.
102 Processing (WebDAV): The server has received the request, but is still processing it.
2xx – Success
These status codes indicate that the request was successfully received, understood, and accepted.
200 OK: The request was successful, and the server has returned the requested data.
201 Created: The request was successful, and a new resource has been created as a result.
202 Accepted: The request has been accepted for processing, but it hasn't been completed yet.
204 No Content: The server successfully processed the request, but there is no content to return.
206 Partial Content: The server is delivering only part of the resource due to a range header sent by the client.
3xx – Redirection
These status codes indicate that the client must take additional actions to complete the request, often involving redirection to another URL.
301 Moved Permanently: The requested resource has been permanently moved to a new URL.
302 Found: The requested resource is temporarily located at a different URL.
303 See Other: The client should retrieve the resource at another URI using a
GETrequest.304 Not Modified: The resource has not been modified since the last request, so the client can use a cached version.
307 Temporary Redirect: Similar to 302, but the method and body should not be changed when following the redirect.
308 Permanent Redirect: Similar to 301, but it keeps the original HTTP method (like
POSTorPUT).
4xx – Client Errors
These status codes indicate that the client made an error in the request.
400 Bad Request: The server couldn't understand the request due to invalid syntax.
401 Unauthorized: Authentication is required and has failed or hasn't been provided.
403 Forbidden: The server understands the request but refuses to authorize it (usually a permissions issue).
404 Not Found: The requested resource could not be found on the server.
405 Method Not Allowed: The request method (like
GETorPOST) is not allowed for the requested resource.408 Request Timeout: The server timed out waiting for the request from the client.
409 Conflict: The request could not be processed because of a conflict with the current state of the resource.
410 Gone: The requested resource is no longer available and has been permanently removed.
429 Too Many Requests: The client has sent too many requests in a given amount of time (rate limiting).
5xx – Server Errors
These status codes indicate that the server encountered an error and could not complete the request.
500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
501 Not Implemented: The server does not support the functionality required to fulfill the request.
502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from an upstream server.
503 Service Unavailable: The server is not ready to handle the request (due to maintenance or overloading).
504 Gateway Timeout: The server, while acting as a gateway or proxy, did not get a response from the upstream server in time.
505 HTTP Version Not Supported: The server does not support the HTTP protocol version used in the request.
Commonly Used HTTP Response codes in practice
200 OK: Everything went fine (often seen in web pages and API requests).
404 Not Found: The requested URL or resource does not exist (common for broken links).
500 Internal Server Error: Something went wrong on the server's side, and the request couldn't be processed.
403 Forbidden: The user does not have the necessary permissions to access the requested resource.
401 Unauthorized: Authentication failed or wasn't provided, and access to the resource is denied.
These codes provide essential feedback for users and developers to understand the status of their HTTP requests and troubleshoot issues accordingly.
Common HTTP code mistakes
Here are some simple examples of common HTTP response codes that are often mistakenly used or misunderstood:
1. Mistaken use of 404 Not Found instead of 410 Gone
404 Not Found instead of 410 GoneScenario: A blog post was deleted permanently.
Mistaken Response:
404 Not FoundExplanation: Many developers return a
404when a resource (like a blog post) is missing. However,404means the resource may never have existed, or it could just be temporarily unavailable.Correct Response:
410 GoneExplanation:
410 Goneshould be used when a resource has been intentionally removed and will not be available again. This tells the client the resource is permanently gone.
2. Mistaken use of 403 Forbidden instead of 401 Unauthorized
403 Forbidden instead of 401 UnauthorizedScenario: A user tries to access a page that requires login, but they are not logged in.
Mistaken Response:
403 ForbiddenExplanation: Developers sometimes return
403when a user is not authenticated. However,403means the server understood the request but refuses to fulfill it, typically due to permissions (even if the user is authenticated).Correct Response:
401 UnauthorizedExplanation:
401 Unauthorizedshould be returned when authentication is required but has not been provided or has failed (e.g., invalid credentials).
3. Mistaken use of 500 Internal Server Error instead of 400 Bad Request
500 Internal Server Error instead of 400 Bad RequestScenario: A user submits a form with malformed data (e.g., missing required fields or sending invalid JSON).
Mistaken Response:
500 Internal Server ErrorExplanation: Many developers use
500as a catch-all for errors, even when the issue is with the client's request, not the server.500implies a server-side issue.Correct Response:
400 Bad RequestExplanation:
400 Bad Requestshould be returned when the server cannot process the request due to client-side errors (e.g., bad syntax, invalid data).
4. Mistaken use of 302 Found instead of 307 Temporary Redirect
302 Found instead of 307 Temporary RedirectScenario: A web page temporarily redirects users to another URL.
Mistaken Response:
302 FoundExplanation: Developers sometimes use
302 Foundfor temporary redirects. However,302can cause issues with POST/PUT requests because clients might change the HTTP method toGETwhen following the redirect.Correct Response:
307 Temporary RedirectExplanation:
307should be used because it ensures that the original HTTP method (likePOST) is maintained when following the redirect.
5. Mistaken use of 204 No Content instead of 200 OK
204 No Content instead of 200 OKScenario: An API request to update a user's profile is successful, and the server wants to confirm the update.
Mistaken Response:
204 No ContentExplanation: Developers sometimes return
204 No Contentwhen the operation is successful but don't have content to return. However, if the client expects any confirmation, such as a success message,204should not be used.Correct Response:
200 OKExplanation: Use
200 OKwhen the operation is successful and you need to return some data, such as a confirmation message or updated resource data. If no content is returned,204is appropriate, but only when the body is intentionally empty.
6. Mistaken use of 405 Method Not Allowed instead of 400 Bad Request
405 Method Not Allowed instead of 400 Bad RequestScenario: A client sends an invalid request method (like PATCH when only POST or GET are supported).
Mistaken Response:
405 Method Not AllowedExplanation:
405is meant to indicate that the requested method (e.g.,POST,GET) is known by the server but disabled or not allowed for that resource.Correct Response:
400 Bad RequestExplanation: If the method isn't allowed because the client sent a malformed request or incorrect HTTP method, then
400 Bad Requestis more appropriate.
Best practices for REST API design
Use nouns for resource names:
/users,/products, not/getUsersor/createProductUse HTTP methods correctly: GET for retrieval, POST for creation, PUT/PATCH for updates, DELETE for removal
Version your API: Include version in URL (
/api/v1/) or headers for backward compatibilityUse proper status codes: Return appropriate HTTP status codes for different scenarios
Implement pagination: For large datasets, use query parameters like
?page=1&limit=10Provide filtering and sorting: Allow clients to filter (
?status=active) and sort (?sort=createdAt:desc) resultsUse HTTPS: Always use secure connections in production
Document your API: Provide clear documentation using tools like Swagger/OpenAPI
Implement rate limiting: Protect your API from abuse with request limits
Use consistent naming conventions: Stick to either camelCase or snake_case throughout your API
Last updated
Was this helpful?