JSON and REST APIs
Learning Focus
JSON is the de facto standard for REST API payloads. Understanding the conventions — headers, status codes, envelopes — prevents integration bugs.
Content Negotiation Headers
| Header | Purpose | Value |
|---|---|---|
Content-Type | Format of the body you are sending | application/json |
Accept | Format you want to receive | application/json |
Standard CRUD Operations
Create (POST → 201)
POST /api/v1/products HTTP/1.1
Content-Type: application/json
{ "name": "Keyboard", "price": 129.99, "stock": 50 }
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/products/42
{ "id": 42, "name": "Keyboard", "createdAt": "2024-01-15T08:30:00Z" }
Read (GET → 200)
GET /api/v1/products/42
HTTP/1.1 200 OK
{ "id": 42, "name": "Keyboard", "price": 129.99 }
Update (PATCH → 200)
PATCH /api/v1/products/42
{ "price": 119.99 }
Delete (DELETE → 204)
DELETE /api/v1/products/42
HTTP/1.1 204 No Content
Envelope / Wrapper Pattern
{
"status": "success",
"data": { "id": 42, "name": "Keyboard" },
"meta": { "requestId": "req_abc123", "processingTime": "12ms" }
}
Pagination
{
"status": "success",
"data": [ "..." ],
"pagination": {
"page": 2, "perPage": 20, "total": 157,
"links": {
"prev": "/api/v1/products?page=1",
"next": "/api/v1/products?page=3"
}
}
}
Error Response (RFC 7807 — Problem Details)
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Error",
"status": 422,
"detail": "The 'price' field must be a positive number.",
"errors": [{ "field": "price", "message": "Must be > 0" }]
}
HTTP Status Code Reference
| Code | Meaning | When |
|---|---|---|
200 | OK | Successful GET, PATCH, PUT |
201 | Created | Successful POST |
204 | No Content | Successful DELETE |
400 | Bad Request | Malformed JSON or invalid input |
401 | Unauthorized | Missing / invalid auth |
403 | Forbidden | Valid auth but insufficient rights |
404 | Not Found | Resource does not exist |
422 | Unprocessable Entity | Validation failure |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Unhandled exception |
Concept Map
Concept Flow
Client → JSON + Headers → REST API
REST API → JSON + Status Code → Client
├── GET → 200 OK
├── POST → 201 Created
├── DELETE → 204 No Content
└── Error → 4xx / 5xx + Problem Details JSON
Common Pitfalls
| Pitfall | Consequence | Prevention |
|---|---|---|
Missing Content-Type header | Server rejects body | Always set Content-Type: application/json |
| Returning 200 for errors | Client can't detect failure | Use 4xx/5xx codes semantically |
| No pagination on list endpoints | Client gets 10,000 records | Always paginate collections |
| Inconsistent envelope structure | Complex client integration | Standardise envelope across all endpoints |
What's Next
- Next: JSON in Databases — Store and query JSON natively in relational databases.
- Section Overview — Return to the Web APIs module index.