Skip to main content

APIRouter

Struct APIRouter 

Source
pub struct APIRouter { /* private fields */ }
Expand description

Router for grouping related routes with shared configuration.

APIRouter allows you to organize routes into logical groups with common prefixes, tags, dependencies, and other shared settings.

§Example

let users_router = APIRouter::new()
    .prefix("/users")
    .tags(vec!["users"])
    .get("", list_users)
    .get("/{id}", get_user)
    .post("", create_user);

let items_router = APIRouter::new()
    .prefix("/items")
    .tags(vec!["items"])
    .get("", list_items);

let app = App::builder()
    .include_router(users_router)
    .include_router(items_router)
    .build();

Implementations§

Source§

impl APIRouter

Source

pub fn new() -> Self

Creates a new empty router.

Source

pub fn with_prefix(prefix: impl Into<String>) -> Self

Creates a new router with the given prefix.

Source

pub fn prefix(self, prefix: impl Into<String>) -> Self

Sets the URL prefix for all routes.

The prefix is prepended to all route paths when the router is included in an application.

Source

pub fn tags(self, tags: Vec<impl Into<String>>) -> Self

Sets the default tags for all routes.

Tags are used for organizing routes in OpenAPI documentation. Route-specific tags are merged with these router-level tags.

Source

pub fn tag(self, tag: impl Into<String>) -> Self

Adds a single tag to the default tags.

Source

pub fn dependency(self, dep: RouterDependency) -> Self

Adds a dependency that runs before all routes.

Dependencies are executed in the order they are added. If a dependency returns an error response, subsequent dependencies and the route handler are not executed.

Source

pub fn dependencies(self, deps: Vec<RouterDependency>) -> Self

Adds multiple dependencies.

Source

pub fn response(self, status_code: u16, def: ResponseDef) -> Self

Adds a response definition for OpenAPI documentation.

Source

pub fn responses(self, responses: HashMap<u16, ResponseDef>) -> Self

Sets shared response definitions.

Source

pub fn deprecated(self, deprecated: bool) -> Self

Marks all routes as deprecated.

Source

pub fn include_in_schema(self, include: bool) -> Self

Sets whether routes should be included in OpenAPI schema.

Source

pub fn route<H, Fut>( self, path: impl Into<String>, method: Method, handler: H, ) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a route with the given method and path.

Source

pub fn get<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a GET route.

Source

pub fn post<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a POST route.

Source

pub fn put<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a PUT route.

Source

pub fn delete<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a DELETE route.

Source

pub fn patch<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a PATCH route.

Source

pub fn options<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds an OPTIONS route.

Source

pub fn head<H, Fut>(self, path: impl Into<String>, handler: H) -> Self
where H: Fn(&RequestContext, &mut Request) -> Fut + Send + Sync + 'static, Fut: Future<Output = Response> + Send + 'static,

Adds a HEAD route.

Source

pub fn include_router(self, other: APIRouter) -> Self

Includes another router’s routes with an optional additional prefix.

This allows nesting routers for hierarchical organization.

§Example
let v1_users = APIRouter::new()
    .prefix("/users")
    .get("", list_users);

let v1_router = APIRouter::new()
    .prefix("/v1")
    .include_router(v1_users);

// Routes: /v1/users
Source

pub fn include_router_with_config( self, other: APIRouter, config: IncludeConfig, ) -> Self

Includes another router with configuration overrides.

This allows applying additional configuration when including a router, such as prepending a prefix, adding tags, or injecting dependencies.

§Merge Rules

Following FastAPI’s merge semantics:

  1. prefix: config.prefix + router.prefix + route.path
  2. tags: config.tags + router.tags + route.tags
  3. dependencies: config.deps + router.deps + route.deps
  4. responses: route > router > config (later values win)
  5. deprecated: config overrides router if set
  6. include_in_schema: config overrides router if set
§Example
let users_router = APIRouter::new()
    .prefix("/users")
    .get("", list_users);

let config = IncludeConfig::new()
    .prefix("/api/v1")
    .tags(vec!["api"])
    .dependency(auth_dep);

let app_router = APIRouter::new()
    .include_router_with_config(users_router, config);

// Routes: /api/v1/users with ["api", "users"] tags
Source

pub fn get_prefix(&self) -> &str

Returns the prefix for this router.

Source

pub fn get_tags(&self) -> &[String]

Returns the tags for this router.

Source

pub fn get_dependencies(&self) -> &[RouterDependency]

Returns the dependencies for this router.

Source

pub fn get_responses(&self) -> &HashMap<u16, ResponseDef>

Returns the response definitions.

Source

pub fn is_deprecated(&self) -> Option<bool>

Returns whether routes are deprecated.

Source

pub fn get_include_in_schema(&self) -> bool

Returns whether routes should be included in schema.

Source

pub fn get_routes(&self) -> &[RouterRoute]

Returns the routes in this router.

Source

pub fn into_route_entries(self) -> Vec<RouteEntry>

Converts router routes to RouteEntry values for the app.

This applies the router’s prefix, tags, and dependencies to all routes. The returned routes can be added to an AppBuilder.

Trait Implementations§

Source§

impl Debug for APIRouter

Source§

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

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

impl Default for APIRouter

Source§

fn default() -> APIRouter

Returns the “default value” for a type. 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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> ResponseProduces<T> for T