Start learning free

LESSON 8 OF 173 · BACKEND: HOW THE WEB WORKS

Send Data with POST

Practice

Every request has a method, the verb that says what it does. GET asks for something and changes nothing. POST sends data to the server so it can create something new.

In Java you build a POST yourself, in three moves: turn a map into JSON text with new ObjectMapper().writeValueAsString, add the header Content-Type: application/json so the server knows how to read it, and hand the text to .POST(HttpRequest.BodyPublishers.ofString(…)) on the builder. Without .POST, the builder makes a GET. For example, to send a note to a notes service:

Map<String, Object> note = Map.of("text", "Call the supplier", "pinned", true);
String text = new ObjectMapper().writeValueAsString(note);
HttpRequest send = HttpRequest.newBuilder(URI.create("https://notes.example/notes"))
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(text))
        .build();

Then client.send sends it like any other request. When a POST creates something, the server answers 201 Created, not 200, and the body usually describes what it made, with the id it gave it. Each POST changes the server: send two, and you create two things. Your program orders 3 mugs (product 1), then 10 pens (product 4):

POST /orders  {"product_id": 1, "quantity": 3}   →  201  {"order_id": 1001, "product_id": 1, "quantity": 3}
POST /orders  {"product_id": 4, "quantity": 10}  →  order_id 1002
Status: 201
Order placed: 1001
Order placed: 1002

Your task: POST an order for 3 of product 1 as JSON to /orders, and print the status and the new order's id. Then POST a second order, 10 of product 4, and print its id.


Assignment
Follow the Coding Tutorial to place two orders with the supplier and read what it created.


Hint
Build the request like a GET, then add the Content-Type header and .POST(…) with the JSON text before .build(). The answer's body is JSON: read it with readValue(response.body(), Map.class) and take its "order_id" with get.


STEP 1 OF 11
    Ctrl + Enter to check