Start learning free

LESSON 8 OF 173 · BACKEND: HOW THE WEB WORKS

Send Data with POST in TypeScript

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.

fetch sends a GET unless you say otherwise. For a POST, pass an object with three options after the address: method: "POST"; headers with Content-Type: application/json, so the server knows how to read the body; and body, the text to send. JSON.stringify turns an object into JSON text. An interface describes the object you send. For example, to send a note to a notes service:

interface Note {
  text: string;
  pinned: boolean;
}

const note: Note = { text: "Call the supplier", pinned: true };
const reply = await fetch("https://notes.example/notes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(note),
});

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. The interface Order in the starting code describes an order: a product_id and a quantity. Your script 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: inside main, 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
fetch takes the address, then an object with method, headers and body; JSON.stringify makes the body's text. Declare response and data with let, since the second order reuses them. The answer's body is JSON: read it with await response.json() and take its order_id.


STEP 1 OF 12
    Ctrl + Enter to check

    Web Post Json in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free