The Request / Response Pattern

A web request and its response are simple text messages, each made of a header and an optional body.

Journeyman · REST API · Updated

Tools such as Postman, Insomnia and Visual Studio's .http files are great for testing API methods: they let us write requests, send them, save them, and run them again.

But the web request/response pattern behind them is a simple pattern. A request is just a simple text message that is sent to another computer over a network, and a response is a simple text message reply. Both messages consist of only two parts: 1) a header and 2) a body.

Header

The header is like information on the outside of a letter. It provides the information needed to send the letter, including the mailing address, and postage stamp.

Mailing address and stamp of a letter

The header of a request includes any information that is needed to send our request to the web server. Header information can include:

  • HTTP Verb: The type of request GET, POST, PUT, DELETE
  • URL: The "mailing address" of the request
  • Content-Type: this describes the format of the contents of the request (the body)
  • Authorization: this is a token that acts like an id card to verify your identity
GET http://localhost:8080/api/categories

The first line of a request header must include the HTTP Verb and the URL. This is the only line that is required.

The number after localhost: is the port your API listens on. It's 8080 here, and yours may be different: a C# project's port is in Properties/launchSettings.json, and a Spring Boot app uses 8080 unless server.port in application.properties sets another.

Body

Both the Request and Response can contain a body, but they are not required. If the Request does not include a body, then the header should provide all of the information the server needs.

The contents of an envelope

The body is like the contents of an envelope or package. For instance, if we want to add a new category to the database, the body contains all of the information about the new category. Adding a new category requires a POST request.

POST http://localhost:8080/api/categories
Content-Type: application/json

{
  "categoryName": "Sports Equipment",
  "description": "All outdoor sports"
}

Note that the header includes an additional line describing the body format. The header ends when an empty line is encountered, and the body begins on the following line.

Key terms