Expand description
An extractor-based API layer for trillium.
This crate provides api, which wraps an async function into a trillium
Handler. The function receives a &mut Conn and an extracted value
(deserialized body, shared state, route parameters, etc.) and returns
any type that implements Handler.
use trillium_api::{api, Json};
use trillium::Conn;
/// An api handler that takes no input and returns a JSON response.
async fn hello(_conn: &mut Conn, _: ()) -> Json<&'static str> {
Json("hello, world")
}
/// An api handler that deserializes a JSON body and echoes it back.
async fn echo(_conn: &mut Conn, Json(body): Json<trillium_api::Value>) -> Json<trillium_api::Value> {
Json(body)
}
§How it works
When a request arrives, api does three things:
- Extract — calls
TryFromConnon the second parameter to pull typed data out of the conn (body, state, headers, etc.) - Call — passes
&mut Connand the extracted value to your function - Run — takes whatever your function returned (which must implement
Handler) and runs it on the conn
If extraction fails, your function is never called. Instead, the
TryFromConn::Error type — which must itself implement Handler — is
run on the conn, typically setting an error status.
§Guide
| Module | Topic |
|---|---|
extractors | Pulling data out of requests — Body, Json, State, tuples |
extractors::custom | Writing your own FromConn / TryFromConn implementations |
return_types | What you can return from an api handler |
error_handling | How extraction errors and Result return types work |
recipes | Patterns and ideas: middleware, type aliases, and more |
§Extractors at a glance
| Type | Extracts | Fallible? |
|---|---|---|
() | Nothing (no-op) | No |
Body<T> | Deserialized request body (content-type negotiated) | Yes |
Json<T> | Deserialized request body (JSON only) | Yes |
State<T> | A T from conn state (via take_state) | No* |
String | Request body as a string | Yes |
Vec<u8> | Request body as raw bytes | Yes |
Headers | Clone of request headers | No |
Method | The HTTP method | No |
(A, B, ...) | Multiple extractors as a tuple (up to 12) | Depends |
*State<T> returns None (halting the conn) if the state is missing.
§Formats supported
This crate supports receiving application/json and application/x-www-form-urlencoded, gated on
cargo features. Response serialization uses Accept header negotiation when Body<T> is used.
trillium-api does not enable any default features, but you likely want to select either serde_json
or sonic-rs to get the most out of this crate. sonic-rs is faster, and the serde_json feature
exists mostly for backwards compatability or for applications that cannot avoid compiling
serde_json.
It is quite easy to add additional negotiated content types to this crate, so please open an issue if you need that.
§cargo features
forms: enable form-urlencoded content negotiation (request/response bodies)url: implement TryFromConn forurl::Urlserde_json: useserde_jsonfor json bodiessonic-rs: usesonic-rsfor json bodies
note that rustdocs on docs.rs are generated with the following features enabled: forms, url, sonic-rs
Modules§
- error_
handling - Error handling
- extractors
- Extractors — pulling data out of Conns
- recipes
- Recipes
- return_
types - Return types — handlers all the way down
Macros§
- json
sonic-rs - Construct a
sonic_rs::Valuefrom a JSON literal.
Structs§
- ApiHandler
- An interface layer built on trillium
- Before
Send - Run a [
trillium::Handler] inbefore_send - Body
- Body extractor
- Cancel
OnDisconnect - A struct that cancels a handler if the client disconnects.
- Halt
- a struct that halts the Conn handler sequence. see [
Conn::halt] for more. - Json
serde_jsonorsonic-rs - A newtype wrapper struct for any
serde::Serializetype. Note that this currently must own the serializable type. Body extractor - State
- State extractor
- Value
sonic-rs - Represents any valid JSON value.
Enums§
- Error
- A serde-serializable error
Traits§
- ApiConn
Ext - Extension trait that adds api methods to [
trillium::Conn] - From
Conn - A trait to extract content from [
Conn]s to be used as the second argument to an api handler. Implement this for your types. - TryFrom
Conn - Like FromConn, but with an Error.
Functions§
- api
- constructs a new
ApiHandlerfrom the providedasync fn(&mut conn, TryFromConn) -> impl Handler - cancel_
on_ disconnect - Construct a new
CancelOnDisconnecthandler.