Sobes.tech
Senior

What is usually contained in the request body in REST?

sobes.tech AI

Answer from AI

In REST, the request body usually contains data that the client sends to the server to create or update a resource. The format is most often JSON or XML, but JSON is the most common.

Typical content of the request body:

  • Representation of the resource with the necessary fields (e.g., a JSON object with parameters).
  • For POST requests — data of the new resource.
  • For PUT/PATCH — updated fields of the resource.

Example of a JSON request body for creating a user:

{
  "name": "Ivan Ivanov",
  "email": "ivan@example.com",
  "age": 30
}

In Go, when working with REST API, the request body is usually read and deserialized into a structure:

Type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int    `json:"age"`
}

func handler(w http.ResponseWriter, r *http.Request) {
    var user User
    err := json.NewDecoder(r.Body).Decode(&user)
    if err != nil {
        http.Error(w, "Invalid request body", http.StatusBadRequest)
        return
    }
    // process user
}

Thus, the request body in REST contains the data necessary to perform an operation on the resource.

What is usually contained in the request body in… - sobes.tech