Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

rest - Return JSON with an HTTP status other than 200 in Rocket

I want my Rocket API to have a route like this:

#[post("create/thing", format = "application/json", data="<thing>")]

When the client sends { "name": "mything" }, everything should be alright and I know how to do that, but when it sends { "name": "foo" } it should respond with something like this:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
  "errors": [
    {
      "status": "422",
      "title":  "Invalid thing name",
      "detail": "The name for a thing must be at least 4 characters long."
    }
  ]
}

How do I respond with a result like a JSON object and a HTTP status code different than 200 in Rocket?

This is what I tried so far:

  • impl FromRequest for my Thing type. This lets me choose a status code as I can write my own from_request function, but I can't return anything else.
  • Registering an error catcher like in this example, but this way I only can react to one HTTP status code without context. I have too many failure modes to reserve one HTTP status code for each.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With @hellow's help, I figured it out. The solution is to implement the Responder trait for a new struct ApiResponse, which contains a status code as well the Json. This way I can do exactly what I wanted:

#[post("/create/thing", format = "application/json", data = "<thing>")]
fn put(thing: Json<Thing>) -> ApiResponse {
    let thing: Thing = thing.into_inner();
    match thing.name.len() {
        0...3 => ApiResponse {
            json: json!({"error": {"short": "Invalid Name", "long": "A thing must have a name that is at least 3 characters long"}}),
            status: Status::UnprocessableEntity,
        },
        _ => ApiResponse {
            json: json!({"status": "success"}),
            status: Status::Ok,
        },
    }
}

Here is the full code:

#![feature(proc_macro_hygiene)]
#![feature(decl_macro)]

#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

use rocket::http::{ContentType, Status};
use rocket::request::Request;
use rocket::response;
use rocket::response::{Responder, Response};
use rocket_contrib::json::{Json, JsonValue};

#[derive(Serialize, Deserialize, Debug)]
pub struct Thing {
    pub name: String,
}

#[derive(Debug)]
struct ApiResponse {
    json: JsonValue,
    status: Status,
}

impl<'r> Responder<'r> for ApiResponse {
    fn respond_to(self, req: &Request) -> response::Result<'r> {
        Response::build_from(self.json.respond_to(&req).unwrap())
            .status(self.status)
            .header(ContentType::JSON)
            .ok()
    }
}

#[post("/create/thing", format = "application/json", data = "<thing>")]
fn put(thing: Json<Thing>) -> ApiResponse {
    let thing: Thing = thing.into_inner();
    match thing.name.len() {
        0...3 => ApiResponse {
            json: json!({"error": {"short": "Invalid Name", "long": "A thing must have a name that is at least 3 characters long"}}),
            status: Status::UnprocessableEntity,
        },
        _ => ApiResponse {
            json: json!({"status": "success"}),
            status: Status::Ok,
        },
    }
}

fn main() {
    rocket::ignite().mount("/", routes![put]).launch();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...