Skip to main content

Crate resty

Crate resty 

Source
Expand description

§resty

resty is a fast and lightweight framework for concurrent and multithreadable REST APIs.

Its capable of manual routing aswell as path based routing similiar to Next.js or Tanstack Router. It also capable of generating a JSON description of the API that can be used for client snippet and documentation generation. To do so set RESTY_DECL_GEN=output.json as environment variable during compilation.

Known issues with rust-analyzer:

rust-analyzer currently does not support getting the sourcefile path of a Span. This is vital for path based routing and can be worked around by setting RESTY_PATH_ROUTING_HINT to the base directory of your API routes.

Example settings for vscode

{
    "rust-analyzer.server.extraEnv": {
        "RESTY_PATH_ROUTING_HINT": "src/routes/"
    }
}

§Example

#[resty::router]
static ROUTER: LazyLock<Router>;

#[resty::endpoint(
    Route("/"),
    Router(ROUTER),
    Method(GET),
    Header("Content-Type", "text/html; charset=utf-8")
)]
async fn get_hello_world<'a>(_req: &mut Request<'a>, res: &mut Response<'a>) -> resty::Result {
    res.ok(&"Hello World!").await?;

    Ok(())
}

fn main() -> ExitCode {
    const ADDR: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 3333);

    if let Err(error) = resty::bind::<TcpSocket>(ADDR, &ROUTER) {
        println!("{error:?}");
        return ExitCode::FAILURE;
    }
    
    println!("Listening on port 3333");

    let _: Vec<_> = std::thread::available_parallelism()
        .ok()
        .map(|n| 0..n.get())
        .unwrap_or(0..1)
        .map(|_| resty::spawn_thread())
        .collect();

    std::thread::park();

    return ExitCode::SUCCESS;
}

Re-exports§

pub use routing::HandlerOrMiddleware::*;

Structs§

EventManager
Naive implementation for a thread safe, multi producer event queue for server sent events
NoBody
A content type for responses that have no body. Mostly used for generic HTTP Errors
Request
An partially parsed Request with headers, cookies and path parameters.
Response
An HTTP response. Provides a set of high level APIs to send or stream reponse data.
Router
A router that routes a path to an endpoint while resolving path parameters
ServerSentEvent
A struct that serializes into a single message for a server sent event Server sent events can be implemented by streaming an iterator over these
ServerSentEvents
TcpScocket
Implementation for a TCP transport layer
UnixSocket
Implementation for using Unix sockets as transport layer

Enums§

Error
HandlerOrMiddleware
HttpMethod
Enum for every valid HTTP method with a variant for invalid methods

Traits§

AsyncIterator
AsyncReadExt
Extension trait for AsyncRead.
AsyncWriteExt
Extension trait for AsyncWrite.
ContentType
Implementing ContentType lets the response infer the content type header this is implemented by an extractor like Json or XML The content type trait makes no assumption about how and if a given T can be serialized
Deserialize
DeserializeBuffered
The main trait to deserialize Self from a request.
EventSource
Parse
This trait reads a Self from the request stream. This can be used to read something like a new line delimited JSON stream sequentially
RestResponse
A REST API response as defined by the openapi spec. By deriving this trait resty can auto generate the openapi spec for this response
Serialize
Socket
The Socket trait allows for implementation of custom transport layers

Functions§

bind
spawn_thread
Spawns a worker thread to handle the async task queue.

Type Aliases§

DeserializeStream
EndpointTask
Type alias for the Future returned by a Handler
Result
RouteSlice
Type alias for the description of a Route

Attribute Macros§

endpoint
Macro to register new endpoint handler
middleware
Macro to register new middleware
router

Derive Macros§

Response
Schema