HTTP and REST explained: your first API call with curl

What are HTTP and REST? Understand requests, responses, GET, POST and DELETE and status codes through a Java order API that you call with curl.

HTTP is the way an application talks to a server: one side sends a request, the other side sends back a response. REST is a way of naming those requests so they stay tidy: the path says which thing you work with, the method says what you want to do, and the status code says how it went.

I start from the Mộc café, the running example of this series (an illustrative situation, not a real café). The owner has an app on the phone for ordering drinks. When a customer taps order, the app must send the order to a program running on a server to save it, and that program is the backend that this series will build together. Before you write a single line of Spring code, you need to understand how an app and a server talk to each other. That is the job of this post.

If you do not know Java yet, you can still read this post, because I only use Java to build one very small server. If you want to learn Java first, see the page of the series Learn Java from scratch for backend developers.

What is in one HTTP call?

HTTP is a protocol of the kind "one question, one answer". The side that asks (called the client, for example an app on a phone or a browser) sends a request. The side that answers (the server) sends back a response. Both are text with a fixed structure.

The best way to see it is to look at it directly. I already built a small server (the code is in a later section) and I use curl, a command-line tool for sending requests, with the -v flag to print both directions. A line that starts with > is what the client sends, and a line that starts with < is what the server returns:

Call it and look at both directions
curl -sv http://localhost:8080/orders/2
Output (only the request and response lines are kept)
> GET /orders/2 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.77.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 17 Nov 2026 12:01:34 GMT
< Content-type: application/json; charset=utf-8
< Content-length: 56
<

A request has three parts. The first line, GET /orders/2 HTTP/1.1, is called the request line: it gives the method (GET), the path (/orders/2) and the protocol version. The following lines are headers, extra information such as which server (Host) and who is sending (User-Agent). The last part is the body, the content that comes with the request; this request is a GET, so it has no body.

A response has a similar structure. The first line is the status line, HTTP/1.1 200 OK, where 200 is the status code and OK is a descriptive word. Next come the headers of the response, for example Content-type: application/json says the returned content is JSON, and Content-length: 56 says it is 56 bytes long. After an empty line comes the body, the real data, which I left out above on purpose (you will see it below).

Two things to remember. One is that only the client starts a request; the server does not send anything to the client by itself (let's keep it at that for this post). The other is that every request is independent: the server does not "remember" the previous request unless you design it to. This will matter when I build login in later posts.

What is REST, and how is it different from HTTP?

HTTP is a protocol, meaning rules about how to send and receive. REST (Representational State Transfer) is a design style for APIs running on HTTP, described by Roy Fielding in his doctoral dissertation in 2000. It is not a mandatory standard and not a technology that you can install. When people say "REST API" in everyday work, they usually mean an API that uses HTTP, exchanges data as JSON and follows a few conventions. The three most important conventions for a newcomer are:

First, everything the API manages (here, orders) is a resource with its own path, written with nouns. The orders are /orders, and one specific order is /orders/2. You do not write /getOrder or /deleteOrder, because "what to do" has its own place in the next point.

Second, the HTTP method says the action. GET reads, POST creates, PUT replaces everything, PATCH changes part of it, DELETE removes. The same path /orders/2, but GET views it while DELETE removes it.

Third, the status code says the result. The client reads this number to know what happened without guessing from the words in the content. The codes you will meet often are 200 (success), 201 (created), 204 (success and nothing to return), 400 (a bad request), 404 (not found), 405 (method not supported) and 500 (a server error). The full list and the standard meanings are in RFC 9110 and the HTTP documentation on MDN.

There is one property of methods that interviews like to ask about: GET, PUT and DELETE are idempotent, meaning that calling once or several times in a row leaves the server in the same state (deleting order number 1 twice still makes the order disappear only once). POST is not: calling it twice creates two orders. So when the network is unreliable and a client resends a POST, an order may be created twice. I will come back to this problem in a later stage, when I talk about idempotency keys.

Build an order API in Java to try it

Instead of only reading theory, I build a real server. I use exactly the JDK you just installed (see the post on installing the JDK and running your first Java program) because it has a small HTTP server built in, so no library is needed. From the next post I will switch to Spring Boot, but to understand what Spring does for you, it is a good idea to do it by hand once.

This server keeps a few orders in memory and has four features: list the orders, view one order, create an order, delete an order. Each order uses a short form with four fields: id, customer (the customer name), item and quantity. You create a file called OrderServer.java in an empty folder and paste the whole code below into it:

OrderServer.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OrderServer {

    // record: a short way to declare a type that only holds values
    record Order(int id, String customer, String item, int quantity) {
        String toJson() {
            return "{\"id\":%d,\"customer\":\"%s\",\"item\":\"%s\",\"quantity\":%d}"
                    .formatted(id, customer, item, quantity);
        }
    }

    // The data lives in memory: turn the server off and it is gone.
    static final List<Order> orders = new ArrayList<>();
    static int nextId = 3;

    static final Pattern CUSTOMER = Pattern.compile("\"customer\"\\s*:\\s*\"([^\"]+)\"");
    static final Pattern ITEM = Pattern.compile("\"item\"\\s*:\\s*\"([^\"]+)\"");
    static final Pattern QUANTITY = Pattern.compile("\"quantity\"\\s*:\\s*(\\d+)");

    public static void main(String[] args) throws IOException {
        orders.add(new Order(1, "Lan", "Milk coffee", 2));
        orders.add(new Order(2, "Hung", "Bac xiu", 1));

        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/orders", OrderServer::handleOrders);
        server.createContext("/getOrder", OrderServer::handleBadStyle);
        server.start();
        System.out.println("Server running at http://localhost:8080");
    }

    // A naming style you should NOT use: a verb in the path, and an error that still returns 200.
    static void handleBadStyle(HttpExchange ex) throws IOException {
        send(ex, 200, "{\"error\":\"order not found\"}");
    }

    static void handleOrders(HttpExchange ex) throws IOException {
        String method = ex.getRequestMethod();
        String[] parts = ex.getRequestURI().getPath().split("/"); // "/orders/1" -> ["", "orders", "1"]

        if (parts.length == 2) {                       // /orders
            switch (method) {
                case "GET" -> send(ex, 200, listJson());
                case "POST" -> createOrder(ex);
                default -> methodNotAllowed(ex, "GET, POST");
            }
        } else if (parts.length == 3) {                // /orders/{id}
            int id;
            try {
                id = Integer.parseInt(parts[2]);
            } catch (NumberFormatException e) {
                send(ex, 400, "{\"error\":\"the id must be a number\"}");
                return;
            }
            switch (method) {
                case "GET" -> getOrder(ex, id);
                case "DELETE" -> deleteOrder(ex, id);
                default -> methodNotAllowed(ex, "GET, DELETE");
            }
        } else {
            send(ex, 404, "{\"error\":\"there is no such path\"}");
        }
    }

    static String listJson() {
        return "[" + String.join(",", orders.stream().map(Order::toJson).toList()) + "]";
    }

    static void getOrder(HttpExchange ex, int id) throws IOException {
        for (Order o : orders) {
            if (o.id() == id) {
                send(ex, 200, o.toJson());
                return;
            }
        }
        send(ex, 404, "{\"error\":\"order %d not found\"}".formatted(id));
    }

    static void createOrder(HttpExchange ex) throws IOException {
        String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
        Matcher customer = CUSTOMER.matcher(body);
        Matcher item = ITEM.matcher(body);
        Matcher quantity = QUANTITY.matcher(body);
        if (!customer.find() || !item.find() || !quantity.find() || Integer.parseInt(quantity.group(1)) < 1) {
            send(ex, 400, "{\"error\":\"customer, item and quantity are required (an integer from 1)\"}");
            return;
        }
        Order order = new Order(nextId++, customer.group(1), item.group(1), Integer.parseInt(quantity.group(1)));
        orders.add(order);
        ex.getResponseHeaders().set("Location", "/orders/" + order.id());
        send(ex, 201, order.toJson());
    }

    static void deleteOrder(HttpExchange ex, int id) throws IOException {
        if (orders.removeIf(o -> o.id() == id)) {
            send(ex, 204, "");
        } else {
            send(ex, 404, "{\"error\":\"order %d not found\"}".formatted(id));
        }
    }

    static void methodNotAllowed(HttpExchange ex, String allowed) throws IOException {
        ex.getResponseHeaders().set("Allow", allowed);
        send(ex, 405, "{\"error\":\"method not supported\"}");
    }

    static void send(HttpExchange ex, int status, String json) throws IOException {
        ex.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
        if (status == 204) {                           // 204 has no content
            ex.sendResponseHeaders(204, -1);
            ex.close();
            return;
        }
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        ex.sendResponseHeaders(status, bytes.length);
        try (var out = ex.getResponseBody()) {
            out.write(bytes);
        }
    }
}

This code is quite long, but its main ideas are only a few. The function handleOrders reads the method and the path of the request, and then chooses what to do: GET /orders returns the list, GET /orders/2 returns one order, POST /orders creates an order, DELETE /orders/2 deletes an order. The function send assembles the status code, the Content-Type header and the JSON content into a response. Reading the JSON with regular expressions (regex) is a crude approach, only for the demo: it will break with a name that contains a double quote. Spring Boot will do this work with a dedicated library, and that is one of the reasons we need a framework.

You start the server with one command. The flag -Dstdout.encoding=UTF-8 makes accented letters print correctly on Windows (I explained the reason in the previous post):

Start the server
java -Dstdout.encoding=UTF-8 OrderServer.java
Output
Server running at http://localhost:8080

The server is running and waiting for requests. Leave this window open, and open a second command window to call it.

Call each method and read the status codes

For every command below I use curl -si: the flag -i prints the headers of the response as well, and the flag -s turns off the progress bar to keep things clean. You only need to look at two places: the first line (which has the status code) and the last line (the body).

View the list of orders, then one specific order:

View the list and one order
curl -si http://localhost:8080/orders
curl -si http://localhost:8080/orders/1
Output of the first command
HTTP/1.1 200 OK
Date: Tue, 17 Nov 2026 12:01:34 GMT
Content-type: application/json; charset=utf-8
Content-length: 118

[{"id":1,"customer":"Lan","item":"Milk coffee","quantity":2},{"id":2,"customer":"Hung","item":"Bac xiu","quantity":1}]

Status 200, and the body is the list of the two orders of Lan and Hung. The second command also returns 200 with order number 1. Now ask for an order that does not exist:

View an order that does not exist
curl -si http://localhost:8080/orders/99
Output
HTTP/1.1 404 Not Found
Date: Tue, 17 Nov 2026 12:01:34 GMT
Content-type: application/json; charset=utf-8
Content-length: 30

{"error":"order 99 not found"}

The status is 404, which tells the client "it is not there" at once, without reading the words in the body. Now create a new order. I put the content in a file new-order.json (Vietnamese words in this file need one note, which I cover in a later section):

new-order.json
{"customer":"Mai","item":"Peach tea","quantity":3}
Create a new order with POST
curl -si -X POST http://localhost:8080/orders -H "Content-Type: application/json" -d @new-order.json
Output
HTTP/1.1 201 Created
Date: Tue, 17 Nov 2026 12:01:34 GMT
Content-type: application/json; charset=utf-8
Content-length: 57
Location: /orders/3

{"id":3,"customer":"Mai","item":"Peach tea","quantity":3}

Three things are worth looking at. The status is 201 Created and not 200, because an order was just created. The header Location: /orders/3 tells the client the path of the new order, so it can call it again later. And the body returns the order that was just created, with the id assigned by the server. Now send an order without quantity (the file incomplete-order.json has only customer and item):

Create an order with missing data
curl -si -X POST http://localhost:8080/orders -H "Content-Type: application/json" -d @incomplete-order.json
Output
HTTP/1.1 400 Bad Request
Date: Tue, 17 Nov 2026 12:01:34 GMT
Content-type: application/json; charset=utf-8
Content-length: 72

{"error":"customer, item and quantity are required (an integer from 1)"}

400 Bad Request means the fault is in the request of the client, so the server refuses it and says exactly what is missing. Next is deleting, and a method that the server does not support (the file edit-order.json holds {"customer":"Hung","item":"Bac xiu","quantity":2}):

Delete order 1, and try PUT (the server does not support it)
curl -si -X DELETE http://localhost:8080/orders/1
curl -si -X PUT http://localhost:8080/orders/2 -H "Content-Type: application/json" -d @edit-order.json
Output of DELETE
HTTP/1.1 204 No Content
Date: Tue, 17 Nov 2026 12:01:34 GMT
Content-type: application/json; charset=utf-8
Output of PUT
HTTP/1.1 405 Method Not Allowed
Date: Tue, 17 Nov 2026 12:01:34 GMT
Allow: GET, DELETE
Content-type: application/json; charset=utf-8
Content-length: 32

{"error":"method not supported"}

204 No Content means the delete succeeded and there is nothing to return, so the response has no body. 405 says that the path /orders/2 exists but does not accept PUT, and the Allow header lists the methods that are allowed. This is how a decent API talks: one specific code for each situation, and the client only has to read the number.

Why shouldn't you name a path /getOrder and return 200 for everything?

In the code, I added one deliberately wrong place: the path /getOrder, which has a verb in the URL and also returns 200 even when it reports an error. Try it:

The way you should not do it
curl -si "http://localhost:8080/getOrder?id=99"
Output
HTTP/1.1 200 OK
Date: Tue, 17 Nov 2026 12:01:35 GMT
Content-type: application/json; charset=utf-8
Content-length: 27

{"error":"order not found"}

Compare with GET /orders/99 above: both mean "not found", but one returns 404 and the other returns 200. Why does this difference matter? Because every tool along the way reads the status code to decide what to do: a mobile app will treat 200 as success and try to read quantity from a body that does not have it, a monitoring tool that counts errors by the 4xx and 5xx codes will not see any error, and a cache may keep a "success" that is really an error. Wrapping an error in the body of a 200 response forces everyone to read and interpret the words themselves, and that is the kind of API that teammates call annoying. I will come back to returning errors in a consistent way in a later post, when I build global error handling in Spring.

Why do Vietnamese letters break when you call with curl on Windows?

The first time I typed Vietnamese text straight on the command line, like -d '{"customer":"Mai","item":"Trà đào","quantity":3}', the order that was created stored the item name as Tr� d�o. The server still returned 201, so on the surface there is no error, and the wrong data sits quietly in memory. Here is what I got:

The last line of the response when the text is typed directly on the command line
{"id":4,"customer":"Mai","item":"Tr� d�o","quantity":3}

The cause is exactly the same as the broken letters in the previous post. On Windows, curl.exe receives the parameters from the command line in the encoding of the operating system (Windows-1252), while the server reads the body as UTF-8. The two sides understand the bytes differently, and letters such as à or đ are read wrong. The way to avoid it is to put the content in a file saved as UTF-8 and send it with -d @file-name, as I did above. For me, this is a small proof of a principle: data that crosses the border between two systems (the command line, the network, a file) is where the encoding most often breaks, so always state the encoding clearly (for example charset=utf-8 in the Content-Type header). If you only use plain English letters, you will not see this, but the day you handle a customer called Đức, you will.

How do you call the API with Postman?

curl is handy when you want to write a script, but for trying an API day to day, many people prefer an application with a graphical interface such as Postman or Bruno. Using either is quite similar: you choose the method in the box on the left, paste the path in the box next to it, and click Send. For a POST, you open the Body tab, choose the raw format and the JSON type, and paste the JSON content; the tool will add the header Content-Type: application/json by itself. The result appears in the lower part, with the status code, the headers and the body.

I state the limit plainly: I describe these steps in the way those tools work in general, and I did not take screenshots of each version, and the position of the buttons may differ between versions. Every result in this post comes from the curl commands that I ran. You can do one simple thing to check me: send the same requests as above with Postman and compare the status codes with the post.

What is the next step?

You have seen requests and responses, you know how REST uses paths, methods and status codes, and you hold a running API. But it has one big weakness: the data lives in memory. I turned the server off and on again, and the list that came back held only the two original orders of Lan and Hung. The order number 3 of Mai disappeared, and the order number 1 that I had deleted came back as if it was never touched.

GET /orders after turning the server off and on again
[{"id":1,"customer":"Lan","item":"Milk coffee","quantity":2},{"id":2,"customer":"Hung","item":"Bac xiu","quantity":1}]

A café cannot lose its orders every time the server restarts. To keep data for a long time, it must live in a database, and to work with a database you need to know SQL. That is the job of the later posts in the series Learn Spring Boot: build an order API from zero.

If you are preparing for interviews, try answering the question about how REST differs from HTTP and how POST differs from PUT in the interview question bank before you read the answer.

Get the next post by email.

One email a week, only when there is something worth reading. No spam.