json-resp

Crates.iojson-resp
lib.rsjson-resp
version0.1.2
sourcesrc
created_at2023-02-09 07:30:17.280257
updated_at2023-02-09 11:22:30.965884
descriptionA utility to generate easy json response/errors
homepage
repositoryhttps://github.com/pooyamb/json-resp/
max_upload_size
id780566
size24,204
Pouya Mobasher Behrouz (pooyamb)

documentation

https://docs.rs/json-resp

README

Json-resp

This crate provides a success and an error response for Apis, with utilities and macros to ease the generation of responses and openapi docs(with openapi feature).(Only axum supported right now)

Check out the examples for full explanation.

Success

The success response looks like:

{
    "status": 200,
    "content": C, // C should implement serde::Serialize
    "meta": M // M should implement serde::Serialize
}

And can be produces with builder pattern:

JsonResponse::with_content(content).meta(meta)

Errors

The error response looks like:

{
    "status": 404,
    "code": "error code here",
    "hint": "do something", // Optional
    "content": C // C should implement serde::Serialize
}

And can be produces with a derive macro, openapi docs will be generated too.

#[derive(JsonError)]
enum MyAppErrors{
    // status can be either a number or http::StatusCode
    #[json_error(request, status=StatusCode::NOT_FOUND, code="does-not-exist", hint="some hint")]
    DoesNotExist,

    #[json_error(request, status=409, code="does-not-exist")]
    Validation(ValidationErrors),

    #[json_error(internal)]
    SomethingWentWrong
}

And just use it in your handlers:

async fn my_handler() -> Result<MyResponse, MyAppErrors>{
    Err(MyAppErrors::DoesNotExist)
}
Commit count: 14

cargo fmt