Skip to main content

ApiMethodRouter

Struct ApiMethodRouter 

Source
pub struct ApiMethodRouter { /* private fields */ }
Available on crate feature openapi only.
Expand description

A version of MethodRouter that supports OpenAPI.

This is a core construct for building APIs that can be automatically described using OpenAPI.

This router allows you to register different handlers for different HTTP methods at the same path. When a request is received, the router will dispatch it to the handler registered for that HTTP method. Similarly, for OpenAPI specs, it will generate the appropriate operation for each method.

If no handler is registered for a particular method, the router will return a 405 Method Not Allowed response. If no handler is registered for HEAD requests, the router will return the response generated by the handler for GET requests.

See crate::openapi module documentation for more details on how to generate OpenAPI specs automatically.

§Examples

use cot::json::Json;
use cot::router::method::openapi::api_post;
use cot::router::{Route, Router};
use cot::test::TestRequestBuilder;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, schemars::JsonSchema)]
struct AddRequest {
    a: i32,
    b: i32,
}

#[derive(Serialize, schemars::JsonSchema)]
struct AddResponse {
    result: i32,
}

async fn add(Json(add_request): Json<AddRequest>) -> Json<AddResponse> {
    Json(AddResponse {
        result: add_request.a + add_request.b,
    })
}

let router = Router::with_urls([Route::with_api_handler("/", api_post(add))]);

let request = TestRequestBuilder::post("/")
    .json(&AddRequest { a: 123, b: 123 })
    .router(router.clone())
    .build();
assert_eq!(
    router
        .handle(request)
        .await?
        .into_body()
        .into_bytes()
        .await?,
    "{\"result\":246}"
);

Implementations§

Source§

impl ApiMethodRouter

Source

pub fn new() -> Self

Create a new ApiMethodRouter.

You might consider using api_get, api_post, or one of the other functions defined in cot::router::method::openapi which serve as convenient constructors for a ApiMethodRouter with a specific handler.

§Examples
use cot::json::Json;
use cot::router::method::MethodRouter;
use cot::router::method::openapi::ApiMethodRouter;
use cot::router::{Route, Router};
use cot::test::TestRequestBuilder;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().get(test_handler);

let router = Router::with_urls([Route::with_api_handler("/", method_router)]);

let request = TestRequestBuilder::get("/").router(router.clone()).build();
assert_eq!(
    router
        .handle(request)
        .await?
        .into_body()
        .into_bytes()
        .await?,
    "null"
);
Source

pub fn get<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the GET HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().get(test_handler);
Source

pub fn head<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the HEAD HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().head(test_handler);
Source

pub fn delete<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the DELETE HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().delete(test_handler);
Source

pub fn options<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the OPTIONS HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().options(test_handler);
Source

pub fn patch<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the PATCH HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().patch(test_handler);
Source

pub fn post<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the POST HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().post(test_handler);
Source

pub fn put<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the PUT HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().put(test_handler);
Source

pub fn trace<HandlerParams, ApiParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, ApiParams: 'static, H: RequestHandler<HandlerParams> + AsApiOperation<ApiParams> + Send + Sync + 'static,

Set a handler for the TRACE HTTP method with OpenAPI specification.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().trace(test_handler);
Source

pub fn connect<HandlerParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, H: RequestHandler<HandlerParams> + Send + Sync + 'static,

Set a handler for the CONNECT HTTP method with OpenAPI specification.

Note that CONNECT is not supported in OpenAPI and hence this method does not require the handler to implement AsApiOperation.

§Examples
use cot::json::Json;
use cot::router::method::openapi::ApiMethodRouter;

async fn test_handler() -> Json<()> {
    Json(())
}

let method_router = ApiMethodRouter::new().connect(test_handler);
Source

pub fn fallback<HandlerParams, H>(self, handler: H) -> Self
where HandlerParams: 'static, H: RequestHandler<HandlerParams> + Send + Sync + 'static,

Set a fallback handler that gets called when no other handler matches.

§Examples
use cot::html::Html;
use cot::router::method::openapi::ApiMethodRouter;
use cot::router::{Route, Router};
use cot::test::TestRequestBuilder;
use cot::{Body, StatusCode};

async fn fallback_handler() -> Html {
    Html::new("fallback")
}

let method_router = ApiMethodRouter::new().fallback(fallback_handler);

let router = Router::with_urls([Route::with_api_handler("/", method_router)]);

let request = TestRequestBuilder::get("/").router(router.clone()).build();
assert_eq!(
    router
        .handle(request)
        .await?
        .into_body()
        .into_bytes()
        .await?,
    "fallback"
);

Trait Implementations§

Source§

impl AsApiRoute for ApiMethodRouter

Source§

fn as_api_route( &self, route_context: &RouteContext<'_>, schema_generator: &mut SchemaGenerator, ) -> PathItem

Returns the OpenAPI path item for the route. Read more
Source§

impl Debug for ApiMethodRouter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ApiMethodRouter

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl RequestHandler for ApiMethodRouter

Source§

fn handle( &self, request: Request, ) -> impl Future<Output = Result<Response>> + Send

Handle the request and returns a response. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoApi for T

Source§

fn into_api<A>(self) -> UseApi<T, A>
where T: Sized,

into UseApi
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoField<Auto<T>> for T

Source§

fn into_field(self) -> Auto<T>

Available on crate feature db only.
Converts the type to the field type.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more