pub struct Api { /* private fields */ }
Expand description
The entry point; you can create an instance of this and then add API routes to it
using Self::add()
. You can then get information about the routes that have been added
using Self::info()
, or handle an http::Request
using Self::handle()
.
Implementations§
source§impl Api
impl Api
sourcepub fn new_with_base_path<S: Into<String>>(base_path: S) -> Api
pub fn new_with_base_path<S: Into<String>>(base_path: S) -> Api
Instantiate a new API that will handle requests that begin with the provided base path.
For example, if the provided base_path
is “/foo/bar”, and a route with
the path “hi” is added, then an incoming http::Request
with the path
"/foo/bar/hi"
will match it.
sourcepub fn add<P: Into<String>>(&mut self, path: P) -> RouteBuilder<'_>
pub fn add<P: Into<String>>(&mut self, path: P) -> RouteBuilder<'_>
Add a new route to the API. You must provide a path to make this route available at,
and are given back a RouteBuilder
which can be used to give the route a handler
and a description.
Examples
// This route expects a JSON formatted string to be provided, and echoes it straight back.
api.add("some/route/name")
.description("This route takes some Foo's in and returns some Bar's")
.handler(|body: FromJson<String>| ToJson(body.0));
// This route delegates to an async fn to sum some values, so we can infer more types in the
// handler.
api.add("another.route")
.description("This route takes an array of values and sums them")
.handler(|body: FromJson<_>| sum(body.0));
async fn sum(ns: Vec<u64>) -> ToJson<u64> {
ToJson(ns.into_iter().sum())
}
sourcepub async fn handle<Body: AsyncReadBody>(
&self,
req: Request<Body>
) -> Result<Response<Vec<u8>>, RouteError<Body, ApiError>>
pub async fn handle<Body: AsyncReadBody>(
&self,
req: Request<Body>
) -> Result<Response<Vec<u8>>, RouteError<Body, ApiError>>
Match an incoming http::Request
against our API routes and run the relevant handler if a
matching one is found. We’ll get back bytes representing a JSON response back if all goes ok,
else we’ll get back a RouteError
, which will either be RouteError::NotFound
if no matching
route was found, or a RouteError::Err
if a matching route was found, but that handler emitted
an error.