In a Rocket POST route I want to return JSON and set the response status to 201 (CREATED).
I am using rocket_contrib::json::Json
to create and return the JSON, but I haven't found a way to also set the status to something other than the default of 200.
The line in my code that does this is here: rust-rocket-demo/main.rs at master · mvolkmann/rust-rocket-demo · GitHub
You use rocket::response::status::Created
in the same manner as WithStatus
in the other thread. See the status
module for other response codes as well.
The details of this in Rocket are unclear to me. It seems like perhaps I need to replace this:
Json(dog)
with something like this:
let mut res = Response::new();
res.set_header(ContentType::JSON);
res.set_status(Status::Created);
res.set_raw_body(Json(dog));
res
but the set_raw_body
part is wrong. Seems like there should be a way to add the status code in a single line of code, but I can't find it.
It seems to me that changing Json(dog)
to this should work:
use rocket::response::status::Created;
let url = url_of_new_dog;
Created(url, Some(Json(dog)))