The Chaos of Custom Service APIs
In early web development, teams built custom HTTP interfaces with inconsistent designs:
- ◆*Example:* Returning
200 OKfor an error, with the error message in the JSON payload:{ "error": "User not found" }. - ◆*Example:* Using
POSTrequests for all database reads and updates.
Designing a RESTful API requires standardizing HTTP protocols to make APIs predictable.
API Rule: Use standard HTTP status codes to communicate outcome states. Never return successful status codes for failed server actions.
Standardizing HTTP Status Codes
APIs should use specific status codes:
- ◆200 OK: Successful read or update.
- ◆210 Created: Successful write (returns resource URI in Location header).
- ◆400 Bad Request: Client-side validation errors.
- ◆401 Unauthorized: Missing or invalid auth tokens.
- ◆404 Not Found: Resource does not exist on server.
| Status Code | Type | Meaning |
|---|---|---|
| 201 | Success | Resource created successfully. |
| 403 | Client Error | Authenticated, but lacking permissions. |
| 500 | Server Error | Unhandled server-side code crash. |
Configuring Cross-Origin Resource Sharing (CORS)
When mobile or SPA applications request data from separate domains (e.g. api.shivamitcs.in), browsers block requests due to Same-Origin Policy. Developers must configure CORS headers:
// CORS response headers configuration
Access-Control-Allow-Origin: https://dashboard.shivamitcs.in
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, AuthorizationBy standardizing REST routes and CORS policies, you create clean, secure APIs that simplify client integration.