Skip to main content

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

HeaderPurposeValue
Content-TypeFormat of the body you are sendingapplication/json
AcceptFormat you want to receiveapplication/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

CodeMeaningWhen
200OKSuccessful GET, PATCH, PUT
201CreatedSuccessful POST
204No ContentSuccessful DELETE
400Bad RequestMalformed JSON or invalid input
401UnauthorizedMissing / invalid auth
403ForbiddenValid auth but insufficient rights
404Not FoundResource does not exist
422Unprocessable EntityValidation failure
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnhandled 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

PitfallConsequencePrevention
Missing Content-Type headerServer rejects bodyAlways set Content-Type: application/json
Returning 200 for errorsClient can't detect failureUse 4xx/5xx codes semantically
No pagination on list endpointsClient gets 10,000 recordsAlways paginate collections
Inconsistent envelope structureComplex client integrationStandardise envelope across all endpoints

What's Next