Headers and JSON

Common Headers

HeaderSent byExamplePurpose
Content-Typebothapplication/jsonformat of the body being sent
Acceptclientapplication/jsonformat the client wants back
AuthorizationclientBearer eyJhbGciOi...login token (see the Spring Security material)
Locationserver/api/orders/101URL of a newly created resource (with 201)
Cache-Controlservermax-age=60how long the response may be cached

JSON in Two Minutes

JSON (JavaScript Object Notation) is the language of REST APIs. Objects use { }, arrays use [ ], keys are always in double quotes, and values are strings, numbers, booleans, null, objects or arrays.

{
  "id": 1,
  "name": "Boat Rockerz 450",
  "price": 1499.00,
  "inStock": true,
  "category": { "id": 3, "name": "Electronics" },
  "tags": ["wireless", "bluetooth"],
  "discount": null
}

Spring Boot uses the Jackson library to convert Java objects to JSON (serialization) and JSON back to Java objects (deserialization) automatically.

What Jackson Does For You

Example

A hand-written converter from a Java record to JSON. Jackson does the same thing for any class, with escaping, nesting and dates handled correctly:

import java.util.List;
import java.util.StringJoiner;

public class Main {
    static String quote(String s) { return '"' + s + '"'; }

    static String toJson(Product p) {
        StringJoiner json = new StringJoiner(",", "{", "}");
        json.add(quote("id") + ":" + p.id());
        json.add(quote("name") + ":" + quote(p.name()));
        json.add(quote("price") + ":" + p.price());
        json.add(quote("inStock") + ":" + (p.stock() > 0));
        return json.toString();
    }

    public static void main(String[] args) {
        List<Product> products = List.of(
            new Product(1, "Boat Rockerz 450", 1499.0, 25),
            new Product(2, "Clean Code", 599.0, 0));
        StringJoiner array = new StringJoiner(",", "[", "]");
        products.forEach(p -> array.add(toJson(p)));
        System.out.println(array);
    }
}

record Product(long id, String name, double price, int stock) {}

Output

[{"id":1,"name":"Boat Rockerz 450","price":1499.0,"inStock":true},{"id":2,"name":"Clean Code","price":599.0,"inStock":false}]