JSON and Headers

JSON Bodies

REST APIs send and receive JSON. NestJS automatically converts the object you return into JSON and parses JSON request bodies into objects.

{
  "id": 7,
  "name": "boAt Airdopes 141",
  "price": 1299,
  "stock": 120,
  "category": "audio",
  "tags": ["bluetooth", "earbuds"],
  "discount": null
}

Important Headers

HeaderDirectionExample
Content-TypeBothapplication/json
AuthorizationRequestBearer eyJhbGciOi...
AcceptRequestapplication/json
LocationResponse/products/11 after a create
Cache-ControlResponsepublic, max-age=60

Example

If you forget Content-Type, the body is not parsed as JSON and validation fails:

curl -i -X POST http://localhost:3000/products -d '{"name":"Pen"}'

Example output

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{"message":["name must be a string","price must be a positive number"],"error":"Bad Request","statusCode":400}