Expand description
Convert the value into a Reply
with the value encoded as JSON.
The passed value must implement Serialize
. Many
collections do, and custom domain types can have Serialize
derived.
Example
use warp::Filter;
// GET /ids returns a `200 OK` with a JSON array of ids:
// `[1, 3, 7, 13]`
let route = warp::path("ids")
.map(|| {
let our_ids = vec![1, 3, 7, 13];
warp::reply::json(&our_ids)
});
Note
If a type fails to be serialized into JSON, the error is logged at the
error
level, and the returned impl Reply
will be an empty
500 Internal Server Error
response.
Examples found in repository?
More examples
examples/body.rs (line 26)
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
async fn main() {
pretty_env_logger::init();
// POST /employees/:rate {"name":"Sean","rate":2}
let promote = warp::post()
.and(warp::path("employees"))
.and(warp::path::param::<u32>())
// Only accept bodies smaller than 16kb...
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::json())
.map(|rate, mut employee: Employee| {
employee.rate = rate;
warp::reply::json(&employee)
});
warp::serve(promote).run(([127, 0, 0, 1], 3030)).await
}
examples/rejections.rs (lines 20-23)
≺ ≻
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
async fn main() {
let math = warp::path!("math" / u16);
let div_with_header = math
.and(warp::get())
.and(div_by())
.map(|num: u16, denom: NonZeroU16| {
warp::reply::json(&Math {
op: format!("{} / {}", num, denom),
output: num / denom.get(),
})
});
let div_with_body =
math.and(warp::post())
.and(warp::body::json())
.map(|num: u16, body: DenomRequest| {
warp::reply::json(&Math {
op: format!("{} / {}", num, body.denom),
output: num / body.denom.get(),
})
});
let routes = div_with_header.or(div_with_body).recover(handle_rejection);
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
/// Extract a denominator from a "div-by" header, or reject with DivideByZero.
fn div_by() -> impl Filter<Extract = (NonZeroU16,), Error = Rejection> + Copy {
warp::header::<u16>("div-by").and_then(|n: u16| async move {
if let Some(denom) = NonZeroU16::new(n) {
Ok(denom)
} else {
Err(reject::custom(DivideByZero))
}
})
}
#[derive(Deserialize)]
struct DenomRequest {
pub denom: NonZeroU16,
}
#[derive(Debug)]
struct DivideByZero;
impl reject::Reject for DivideByZero {}
// JSON replies
/// A successful math operation.
#[derive(Serialize)]
struct Math {
op: String,
output: u16,
}
/// An API error serializable to JSON.
#[derive(Serialize)]
struct ErrorMessage {
code: u16,
message: String,
}
// This function receives a `Rejection` and tries to return a custom
// value, otherwise simply passes the rejection along.
async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
let code;
let message;
if err.is_not_found() {
code = StatusCode::NOT_FOUND;
message = "NOT_FOUND";
} else if let Some(DivideByZero) = err.find() {
code = StatusCode::BAD_REQUEST;
message = "DIVIDE_BY_ZERO";
} else if let Some(e) = err.find::<warp::filters::body::BodyDeserializeError>() {
// This error happens if the body could not be deserialized correctly
// We can use the cause to analyze the error and customize the error message
message = match e.source() {
Some(cause) => {
if cause.to_string().contains("denom") {
"FIELD_ERROR: denom"
} else {
"BAD_REQUEST"
}
}
None => "BAD_REQUEST",
};
code = StatusCode::BAD_REQUEST;
} else if let Some(_) = err.find::<warp::reject::MethodNotAllowed>() {
// We can handle a specific error, here METHOD_NOT_ALLOWED,
// and render it however we want
code = StatusCode::METHOD_NOT_ALLOWED;
message = "METHOD_NOT_ALLOWED";
} else {
// We should have expected this... Just log and say its a 500
eprintln!("unhandled rejection: {:?}", err);
code = StatusCode::INTERNAL_SERVER_ERROR;
message = "UNHANDLED_REJECTION";
}
let json = warp::reply::json(&ErrorMessage {
code: code.as_u16(),
message: message.into(),
});
Ok(warp::reply::with_status(json, code))
}