#web #actix-web #restful #toolkit #build #macro #opiniated

macro actix-web-rest-macros

Opiniated toolkit to build restful API using actix-web

3 releases (breaking)

0.3.0 Jun 25, 2023
0.2.0 Jun 17, 2023
0.1.0 Jun 17, 2023

#36 in #restful

31 downloads per month
Used in actix-web-rest

Custom license

16KB
302 lines

actix-web-rest - Opiniated toolkit to build restful API using actix-web.

This crate contains utility to speed up the development of RESTful API using actix-web:

  • rest_error attribute macros

Why ?

⚡ Gotta go fast!

🧑‍🎓 Learn procedural macros.

Getting started

# Create a new project.
cargo init my_api && cd my_api

# Add actix-web-rest to your project.
cargo add actix-web-rest actix-web anyhow thiserror

Then overwrite main.rs with the following content:

use actix_web::{web, App, HttpResponse, HttpServer, ResponseError};
use actix_web_rest::{actix_web, http::StatusCode, rest_error};
use anyhow::anyhow;

#[allow(clippy::enum_variant_names)]
#[rest_error(internal_error)] // internal_error add an InternalError(#[from] anyhow::Error).
enum MyEndpointError {
    #[rest(status_code = StatusCode::OK)]
    #[error("error foo")]
    FooError,

    #[rest(status_code = StatusCode::OK)]
    #[error("error bar")]
    BarError,
}

async fn handler(path: web::Path<String>) -> Result<HttpResponse, impl ResponseError> {
    let path_param = path.into_inner();
    match path_param.as_ref() {
        "foo" => Err(MyEndpointError::FooError),
        "bar" => Err(MyEndpointError::BarError),
        _ => Err(MyEndpointError::from(anyhow!(
            "unexpected path params: {path_param}"
        ))),
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/{error}", web::get().to(handler)))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}
curl -i http://localhost:8080/foo
curl -i http://localhost:8080/bar
curl -i http://localhost:8080/baz

Contributing

If you want to contribute to actix-web-rest to add a feature or improve the code contact me at negrel.dev@protonmail.com, open an issue or make a pull request.

🌠 Show your support

Please give a ⭐ if this project helped you!

buy me a coffee

📜 License

MIT © Alexandre Negrel

Dependencies

~0.9–1.6MB
~32K SLoC