Skip to main content

Crate trillium_api

Crate trillium_api 

Source
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:

  1. Extract — calls TryFromConn on the second parameter to pull typed data out of the conn (body, state, headers, etc.)
  2. Call — passes &mut Conn and the extracted value to your function
  3. 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

ModuleTopic
extractorsPulling data out of requests — Body, Json, State, tuples
extractors::customWriting your own FromConn / TryFromConn implementations
return_typesWhat you can return from an api handler
error_handlingHow extraction errors and Result return types work
recipesPatterns and ideas: middleware, type aliases, and more

§Extractors at a glance

TypeExtractsFallible?
()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*
StringRequest body as a stringYes
Vec<u8>Request body as raw bytesYes
HeadersClone of request headersNo
MethodThe HTTP methodNo
(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 for url::Url
  • serde_json: use serde_json for json bodies
  • sonic-rs: use sonic-rs for 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§

jsonsonic-rs
Construct a sonic_rs::Value from a JSON literal.

Structs§

ApiHandler
An interface layer built on trillium
BeforeSend
Run a [trillium::Handler] in before_send
Body
Body extractor
CancelOnDisconnect
A struct that cancels a handler if the client disconnects.
Halt
a struct that halts the Conn handler sequence. see [Conn::halt] for more.
Jsonserde_json or sonic-rs
A newtype wrapper struct for any serde::Serialize type. Note that this currently must own the serializable type. Body extractor
State
State extractor
Valuesonic-rs
Represents any valid JSON value.

Enums§

Error
A serde-serializable error

Traits§

ApiConnExt
Extension trait that adds api methods to [trillium::Conn]
FromConn
A trait to extract content from [Conn]s to be used as the second argument to an api handler. Implement this for your types.
TryFromConn
Like FromConn, but with an Error.

Functions§

api
constructs a new ApiHandler from the provided async fn(&mut conn, TryFromConn) -> impl Handler
cancel_on_disconnect
Construct a new CancelOnDisconnect handler.

Type Aliases§

Result
trait alias for a result with this crate’s Error