Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/aide/src/axum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,21 @@
//! // ...
//! ```
//!
//! # Multipart/form-data
//!
//! Aide has built-in support for `axum::extract::Multipart` via the `axum-multipart`
//! feature, but it only generates a generic schema without typed fields.
//!
//! For **typed multipart/form-data** with proper per-field OpenAPI schemas, you can either:
//!
//! - Use the community-maintained [`aide-axum-typed-multipart-2`](https://crates.io/crates/aide-axum-typed-multipart-2)
//! crate, which provides drop-in replacements for `axum_typed_multipart`'s
//! `TypedMultipart` and `FieldData` that implement [`OperationInput`](crate::OperationInput)
//! and `JsonSchema` respectively.
//!
//! - Implement [`OperationInput`](crate::OperationInput) manually with a newtype wrapper.
//! See the `example-axum-multipart` example for a complete working setup.
//!
//! # Composability
//!
//! Just like in `axum`, nesting and merging routers is possible,
Expand Down
18 changes: 18 additions & 0 deletions examples/example-axum-multipart/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "example-axum-multipart"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
aide = { path = "../../crates/aide", features = [
"axum-json",
"scalar",
] }
axum = "0.8.1"
axum_typed_multipart = "0.16"
indexmap = "2"
schemars = "1.0.4"
serde = { version = "1.0.144", features = ["derive"] }
serde_json = "1.0.85"
tokio = { version = "1.21.0", features = ["macros", "rt-multi-thread"] }
65 changes: 65 additions & 0 deletions examples/example-axum-multipart/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::sync::Arc;

use aide::{
axum::{routing::post_with, ApiRouter, IntoApiResponse},
openapi::OpenApi,
};
use axum::{Extension, Json};
use axum_typed_multipart::TryFromMultipart;
use schemars::JsonSchema;
use tokio::net::TcpListener;

// Can be replaced with `aide_axum_typed_multipart_2::TypedMultipart` once
// the crate is updated to aide 0.16 + schemars 1.x.
mod multipart;
use multipart::DocTypedMultipart;

#[derive(TryFromMultipart, JsonSchema)]
struct UploadForm {
/// A description of the uploaded file.
description: String,
/// The file to upload (max 5 MiB).
#[form_data(limit = "5MiB")]
#[schemars(with = "Vec<u8>")]
file: axum::body::Bytes,
}

async fn upload(DocTypedMultipart(form): DocTypedMultipart<UploadForm>) -> impl IntoApiResponse {
Json(serde_json::json!({
"description": form.description,
"size": form.file.len(),
}))
}

async fn serve_api(Extension(api): Extension<Arc<OpenApi>>) -> impl IntoApiResponse {
Json(api.as_ref().clone())
}

#[tokio::main]
async fn main() {
aide::generate::extract_schemas(true);

let mut api = OpenApi::default();

let app = ApiRouter::new()
.api_route(
"/upload",
post_with(upload, |op| {
op.description("Upload a file with a description.")
.response_with::<200, Json<serde_json::Value>, _>(|res| {
res.description("Upload result with file size")
})
}),
)
.route("/api.json", axum::routing::get(serve_api))
.finish_api_with(&mut api, |api| {
api.title("Multipart Upload Example")
.summary("Demonstrates typed multipart/form-data with aide")
})
.layer(Extension(Arc::new(api)));

println!("Docs available at http://127.0.0.1:3000/api.json");

let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
57 changes: 57 additions & 0 deletions examples/example-axum-multipart/src/multipart.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Manual OperationInput + FromRequest wrapper for TypedMultipart.
//
// This can be replaced with a single import once `aide-axum-typed-multipart-2`
// is updated to aide 0.16 + schemars 1.x:
//
// use aide_axum_typed_multipart_2::TypedMultipart;

use aide::{
openapi::{MediaType, Operation, RequestBody, SchemaObject},
operation::set_body,
OperationInput,
};
use axum::extract::{FromRequest, Request};
use axum_typed_multipart::TypedMultipart;
use indexmap::IndexMap;
use schemars::JsonSchema;

pub struct DocTypedMultipart<T>(pub T);

impl<T: JsonSchema> OperationInput for DocTypedMultipart<T> {
fn operation_input(ctx: &mut aide::generate::GenContext, operation: &mut Operation) {
let schema = ctx.schema.subschema_for::<T>();
set_body(
ctx,
operation,
RequestBody {
description: Some("Multipart file upload".into()),
content: IndexMap::from_iter([(
"multipart/form-data".into(),
MediaType {
schema: Some(SchemaObject {
json_schema: schema.try_into().expect("invalid schema"),
external_docs: None,
example: None,
}),
..Default::default()
},
)]),
required: true,
extensions: IndexMap::default(),
},
);
}
}

impl<T, S> FromRequest<S> for DocTypedMultipart<T>
where
TypedMultipart<T>: FromRequest<S>,
S: Send + Sync,
{
type Rejection = <TypedMultipart<T> as FromRequest<S>>::Rejection;

async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let TypedMultipart(inner) = TypedMultipart::from_request(req, state).await?;
Ok(Self(inner))
}
}