1 unstable release
0.1.1 | Dec 3, 2024 |
---|
#639 in Procedural macros
130 downloads per month
Used in fastapi
690KB
14K
SLoC
fastapi - Auto-generated OpenAPI documentation
Want to have your API documented with OpenAPI? But don't want to be bothered
with manual YAML or JSON tweaking? Would like it to be so easy that it would almost
be utopic? Don't worry: fastapi is here to fill this gap. It aims to do, if not all, then
most of the heavy lifting for you, enabling you to focus on writing the actual API logic instead of
documentation. It aims to be minimal, simple and fast. It uses simple proc
macros which
you can use to annotate your code to have items documented.
The fastapi
crate provides auto-generated OpenAPI documentation for Rust REST APIs. It treats
code-first approach as a first class citizen and simplifies API documentation by providing
simple macros for generating the documentation from your code.
It also contains Rust types of the OpenAPI spec, allowing you to write the OpenAPI spec only using Rust if auto generation is not your flavor or does not fit your purpose.
Long term goal of the library is to be the place to go when OpenAPI documentation is needed in any Rust codebase.
Fastapi is framework-agnostic, and could be used together with any web framework, or even without one. While being portable and standalone, one of its key aspects is simple integration with web frameworks.
Choose your flavor and document your API with ice-cold IPA
Flavor | Support |
---|---|
actix-web | Parse path, path parameters and query parameters, recognize request body and response body, fastapi-actix-web bindings. See more at docs |
axum | Parse path and query parameters, recognize request body and response body, fastapi-axum bindings. See more at docs |
rocket | Parse path, path parameters and query parameters, recognize request body and response body. See more at docs |
Others* | Plain fastapi without extra flavor. This gives you all the basic benefits listed below in Features section but with little less automation. |
Others* = For example warp but could be anything.
Refer to the existing examples to find out more.
Features
- OpenAPI 3.1
- Pluggable, easy setup and integration with frameworks.
- No bloat, enable what you need.
- Support for generic types
- Note!
Tuples, arrays and slices cannot be used as generic arguments on types. Types implementingToSchema
manually should not have generic arguments, as they are not composeable and will result compile error.
- Note!
- Automatic schema collection from usages recursively.
- Request body from either handler function arguments (if supported by framework) or from
request_body
attribute. - Response body from response
body
attribute or responsecontent
attribute.
- Request body from either handler function arguments (if supported by framework) or from
- Various OpenAPI visualization tools supported out of the box.
- Rust type aliases via
fastapi-config
.
Crate Features
macros
Enablefastapi-gen
macros. This is enabled by default.yaml
: Enables serde_yaml serialization of OpenAPI objects.actix_extras
: Enhances actix-web integration with being able to parsepath
,path
andquery
parameters from actix web path attribute macros. See docs or examples for more details.rocket_extras
: Enhances rocket framework integration with being able to parsepath
,path
andquery
parameters from rocket path attribute macros. See docs or examples for more details.axum_extras
: Enhances axum framework integration allowing users to useIntoParams
without defining theparameter_in
attribute. See docs or examples for more details.debug
: Add extra traits such as debug traits to openapi definitions and elsewhere.chrono
: Add support for chronoDateTime
,Date
,NaiveDate
,NaiveDateTime
,NaiveTime
andDuration
types. By default these types are parsed tostring
types with additionalformat
information.format: date-time
forDateTime
andNaiveDateTime
andformat: date
forDate
andNaiveDate
according RFC3339 asISO-8601
. To override defaultstring
representation users have to usevalue_type
attribute to override the type. See docs for more details.time
: Add support for timeOffsetDateTime
,PrimitiveDateTime
,Date
, andDuration
types. By default these types are parsed asstring
.OffsetDateTime
andPrimitiveDateTime
will usedate-time
format.Date
will usedate
format andDuration
will not have any format. To override defaultstring
representation users have to usevalue_type
attribute to override the type. See docs for more details.decimal
: Add support for rust_decimalDecimal
type. By default it is interpreted asString
. If you wish to change the format you need to override the type. See thevalue_type
in component derive docs.decimal_float
: Add support for rust_decimalDecimal
type. By default it is interpreted asNumber
. This feature is mutually exclusive with decimal and allow to change the default type used in your documentation forDecimal
much likeserde_with_float
feature exposed by rust_decimal.uuid
: Add support for uuid.Uuid
type will be presented asString
with formatuuid
in OpenAPI spec.ulid
: Add support for ulid.Ulid
type will be presented asString
with formatulid
in OpenAPI spec.url
: Add support for url.Url
type will be presented asString
with formaturi
in OpenAPI spec.smallvec
: Add support for smallvec.SmallVec
will be treated asVec
.openapi_extensions
: Adds traits and functions that provide extra convenience functions. See therequest_body
docs for an example.repr
: Add support for repr_serde'srepr(u*)
andrepr(i*)
attributes to unit type enums for C-like enum representation. See docs for more details.preserve_order
: Preserve order of properties when serializing the schema for a component. When enabled, the properties are listed in order of fields in the corresponding struct definition. When disabled, the properties are listed in alphabetical order.preserve_path_order
: Preserve order of OpenAPI Paths according to order they have been introduced to the#[openapi(paths(...))]
macro attribute. If disabled the paths will be ordered in alphabetical order. However the operations order under the path will be always constant according to specificationindexmap
: Add support for indexmap. When enabledIndexMap
will be rendered as a map similar toBTreeMap
andHashMap
.non_strict_integers
: Add support for non-standard integer formatsint8
,int16
,uint8
,uint16
,uint32
, anduint64
.rc_schema
: AddToSchema
support forArc<T>
andRc<T>
types. Note! serderc
feature flag must be enabled separately to allow serialization and deserialization ofArc<T>
andRc<T>
types. See more about serde feature flags.config
Enablesfastapi-config
for the project which allows defining global configuration options forfastapi
.
Default Library Support
- Implicit partial support for
serde
attributes. See docs for more details. - Support for http
StatusCode
in responses.
Install
Add dependency declaration to Cargo.toml
.
[dependencies]
fastapi = "0.1.1"
Examples
Create type with ToSchema
and use it in #[fastapi::path(...)]
that is registered to the OpenApi
.
use fastapi::{OpenApi, ToSchema};
#[derive(ToSchema)]
struct Pet {
id: u64,
name: String,
age: Option<i32>,
}
mod pet_api {
/// Get pet by id
///
/// Get pet from database by pet id
#[fastapi::path(
get,
path = "/pets/{id}",
responses(
(status = 200, description = "Pet found successfully", body = Pet),
(status = NOT_FOUND, description = "Pet was not found")
),
params(
("id" = u64, Path, description = "Pet database id to get Pet for"),
)
)]
async fn get_pet_by_id(pet_id: u64) -> Result<Pet, NotFound> {
Ok(Pet {
id: pet_id,
age: None,
name: "lightning".to_string(),
})
}
}
#[derive(OpenApi)]
#[openapi(paths(pet_api::get_pet_by_id))]
struct ApiDoc;
println!("{}", ApiDoc::openapi().to_pretty_json().unwrap());
Above example will produce an OpenAPI doc like this:
{
"openapi": "3.1.0",
"info": {
"title": "application name from Cargo.toml",
"description": "description from Cargo.toml",
"contact": {
"name": "author name from Cargo.toml",
"email": "author email from Cargo.toml"
},
"license": {
"name": "license from Cargo.toml"
},
"version": "version from Cargo.toml"
},
"paths": {
"/pets/{id}": {
"get": {
"tags": [
"pet_api"
],
"summary": "Get pet by id",
"description": "Get pet from database by pet id",
"operationId": "get_pet_by_id",
"parameters": [
{
"name": "id",
"in": "path",
"description": "Pet database id to get Pet for",
"required": true,
"schema": {
"type": "integer",
"format": "int64",
"minimum": 0
}
}
],
"responses": {
"200": {
"description": "Pet found successfully",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
}
},
"404": {
"description": "Pet was not found"
}
}
}
}
},
"components": {
"schemas": {
"Pet": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"age": {
"type": [
"integer",
"null"
],
"format": "int32"
},
"id": {
"type": "integer",
"format": "int64",
"minimum": 0
},
"name": {
"type": "string"
}
}
}
}
}
}
Modify OpenAPI at runtime
You can modify generated OpenAPI at runtime either via generated types directly or using Modify trait.
Modify generated OpenAPI via types directly.
#[derive(OpenApi)]
#[openapi(
info(description = "My Api description"),
)]
struct ApiDoc;
let mut doc = ApiDoc::openapi();
doc.info.title = String::from("My Api");
You can even convert the generated OpenApi to OpenApiBuilder.
let builder: OpenApiBuilder = ApiDoc::openapi().into();
See Modify trait for examples on how to modify generated OpenAPI via it.
Go beyond the surface
- See how to serve OpenAPI doc via Swagger UI check fastapi-swagger-ui crate for more details.
- Browse to examples for more comprehensive examples.
- Check IntoResponses and ToResponse for examples on deriving responses.
- More about OpenAPI security in security documentation.
- Dump generated API doc to file at build time. See issue 214 comment.
FAQ
Swagger UI returns 404 NotFound from built binary
This is highly probably due to RustEmbed
not embedding the Swagger UI to the executable. This is natural since the RustEmbed
library does not by default embed files on debug builds. To get around this you can do one of the following.
- Build your executable in
--release
mode
Find fastapi-swagger-ui
feature flags here.
License
Licensed under either of Apache 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, shall be dual licensed, without any additional terms or conditions.
Dependencies
~0.2–2MB
~39K SLoC