Handling JSON
One of the common tasks of web applications is handling APIs. APIs can return a lot of different formats, but modern APIs have converged into two common formats: JSON and XML.
Building an endpoint that returns JSON is pretty simple in the Rocket web framework. For handling the request body in JSON format, we can use rocket::serde::json::Json<T>
as a data guard. The generic T
type must implement the serde::Deserialize
trait or else the Rust compiler will refuse to compile.
For responding, we can do the same thing by responding with rocket::serde::json::Json<T>
. The generic T
type must only implement the serde::Serialize
trait when used as a response.
Let's see an example of how to handle JSON requests and responses. We want to create a single API endpoint, /api/users
. This endpoint can receive a JSON body similar to the structure of our_application::models::pagination::Pagination
, as follows:
{"next":"2022-02-22T22:22:22.222222Z...