Warp returning JSON and a status

I have a warp POST route where I'd like to return JSON in the response body and a 201 CREATED status.
I can return the JSON with a 200 status using Ok(warp::reply::json(&dog)).
I can return a plain string and a 201 status using Ok(warp::reply::with_status("success", StatusCode::CREATED)).
But I can't figured out how to do both.

with_status can take any kind of reply, not just a string. For example:

Ok(with_status(json(&dog), StatusCode::CREATED))

I think I left an important detail out of my question. The return type of the function this is inside is Result<Json, Rejection>, so it wants the value given to Ok to be a Json. Using your suggestion gives the error "expected struct warp::reply::Json, found struct warp::reply:WithStatus" which makes sense.

I think I need to change the return type of the function, but it's not clear to me what it should be.

I posted another PR with a couple options for return types: Here's some options for reply types by danbruder · Pull Request #2 · mvolkmann/rust-warp-demo · GitHub

The return value of warp::reply::with_status is WithStatus<T> where T is whatever you put inside it, so in your case it would be

Result<WithStatus<Json<...>>, Rejection>
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.