Parsing JSON requests
So far we’ve been looking at how to create and send JSON responses from our API, but in this next section of the book we’re going to explore things from the other side and discuss how to read and parse JSON requests from clients.
To help demonstrate this, we’re going to start working on the POST /v1/movies endpoint and createMovieHandler that we set up earlier.
| Method | URL Pattern | Handler | Action |
|---|---|---|---|
| GET | /v1/healthcheck | healthcheckHandler | Show application information |
| POST | /v1/movies | createMovieHandler | Create a new movie |
| GET | /v1/movies/:id | showMovieHandler | Show the details of a specific movie |
When a client calls this endpoint, we expect them to provide a JSON request body containing data for the movie they want to create in our system. So, for example, if a client wants to add a record for the movie Moana to our API, they would send a request body similar to this:
{
"title": "Moana",
"year": 2016,
"runtime": 107,
"genres": ["animation", "adventure"]
}
For now, we’ll just focus on the reading, parsing and validation aspects of dealing with this JSON request body. Specifically, you’ll learn:
How to read a request body and decode it to a native Go value using the
encoding/jsonpackage.How to deal with bad requests from clients and invalid JSON, and return clear, actionable, error messages.
How to create a reusable helper package for validating data to ensure it meets your business rules.
Different techniques for controlling and customizing how JSON is decoded.