Start learning free

LESSON 8 OF 173 · BACKEND: HOW THE WEB WORKS

Send Data with POST in C#

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.

http.PostAsJsonAsync works like http.GetAsync: the address first, then what to send. Pass it an object, for example one made with new { … }, and it turns the object into JSON text, puts it in the request's body, and adds the header Content-Type: application/json; charset=utf-8 so the server knows how to read it. The object's names become the JSON keys. For example, to send a note to a notes service:

var note = new { text = "Call the supplier", pinned = true };
var reply = await http.PostAsJsonAsync("https://notes.example/notes", 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. 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: 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
PostAsJsonAsync takes the address, then the object to send. The answer's body is JSON: read it with await response.Content.ReadFromJsonAsync<JsonElement>() and take its "order_id" with GetProperty.


STEP 1 OF 8
    Ctrl + Enter to check

    Web Post Json in C#

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