Expand description
Designed to seamlessly integrate with Axum, this crate
simplifies the process of handling multipart/form-data
requests in your web application by
allowing you to parse the request body into a type-safe struct.
§Installation
cargo add axum_typed_multipart
§Features
All features are enabled by default.
chrono_0_4
: Enables support for chrono::DateTime (v0.4)tempfile_3
: Enables support for tempfile::NamedTempFile (v3)uuid_1
: Enables support for uuid::Uuid (v1)rust_decimal_1
: Enables support for rust_decimal::Decimal (v1)
§Usage
§Getting started
To get started you will need to define a struct with the desired fields and implement the TryFromMultipart trait. In the vast majority of cases you will want to use the derive macro to generate the implementation automatically.
To be able to derive the TryFromMultipart trait every field in the struct must implement the TryFromField trait.
The TryFromField trait is implemented by default for the following types:
- i8, i16, i32, i64, i128, isize
- u8, u16, u32, u64, u128, usize
- f32, f64
- bool
- char
- String
- axum::body::Bytes
- chrono::DateTime (feature:
chrono_0_4
) - tempfile::NamedTempFile (feature:
tempfile_3
) - uuid::Uuid (feature:
uuid_1
)
If the request body is malformed the request will be aborted with an error.
An error will be returned if at least one field is missing, except for Option and
Vec types, which will be set respectively as None and []
.
use axum::http::StatusCode;
use axum::routing::post;
use axum::Router;
use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
#[derive(TryFromMultipart)]
struct CreateUserRequest {
first_name: String,
last_name: String,
}
async fn create_user(data: TypedMultipart<CreateUserRequest>) -> StatusCode {
println!("name: '{} {}'", data.first_name, data.last_name); // Your logic here.
StatusCode::CREATED
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/create", post(create_user)).into_make_service();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
§Optional fields
If a field is declared as an Option the value will default to None when the field is missing from the request body.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
first_name: Option<String>,
}
§Renaming fields
If you would like to assign a custom name for the source field you can use the field_name
parameter of the form_data
attribute.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
#[form_data(field_name = "first_name")]
name: Option<String>,
}
The rename_all
parameter from the try_from_multipart
attribute can be used to automatically
rename each field of your struct to a specific case. It works the same way as
#[serde(rename_all = "...")]
.
Supported cases:
snake_case
camelCase
PascalCase
kebab-case
UPPERCASE
lowercase
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
#[try_from_multipart(rename_all = "UPPERCASE")]
struct RequestData {
name: Option<String>, // Will be renamed to `NAME` in the request.
}
NOTE: If the #[form_data(field_name = "...")]
attribute is specified, the rename_all
rule
will not be applied.
§Default values
If the default
parameter in the form_data
attribute is present the value will be populated
using the type’s Default implementation when the field is not supplied in the request.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
struct RequestData {
#[form_data(default)]
name: String, // defaults to ""
}
§Field metadata
If you need access to the field metadata (e.g. the field headers like file name or content type) you can use the FieldData struct to wrap your field.
use axum::body::Bytes;
use axum_typed_multipart::{FieldData, TryFromMultipart};
#[derive(TryFromMultipart)]
struct RequestData {
image: FieldData<Bytes>,
}
§Large uploads
For large uploads you can save the contents of the field to the file system using tempfile::NamedTempFile. This will efficiently stream the field data directly to the file system, without needing to fit all the data in memory. Once the upload is complete, you can then save the contents to a location of your choice. For more information check out the NamedTempFile documentation.
§Warning
Field size limits for Vec fields are applied to each occurrence of the field. This means that if you have a 1GiB field limit and the field contains 5 entries, the total size of the request body will be 5GiB.
§Note
When handling large uploads you will need to increase the request body size limit using the
DefaultBodyLimit middleware. Field size limits are disabled by default,
but can be enabled using the limit
parameter of the form_data
attribute if desired.
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::routing::post;
use axum::Router;
use axum_typed_multipart::{FieldData, TryFromMultipart, TypedMultipart};
use std::path::Path;
use tempfile_3::NamedTempFile;
#[derive(TryFromMultipart)]
struct UploadAssetRequest {
// Field size limits are disabled by default. The `limit` parameter can be used
// to set a specific size limit in bytes, like '5MiB' or '1GiB'. The value
// "unlimited" explicitly disables the limit (same as the default behavior).
#[form_data(limit = "unlimited")]
image: FieldData<NamedTempFile>,
// This field has no size limit since limits are disabled by default.
author: String,
}
async fn upload_asset(
TypedMultipart(UploadAssetRequest { image, author }): TypedMultipart<UploadAssetRequest>,
) -> StatusCode {
let file_name = image.metadata.file_name.unwrap_or(String::from("data.bin"));
let path = Path::new("/tmp").join(author).join(file_name);
match image.contents.persist(path) {
Ok(_) => StatusCode::CREATED,
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", post(upload_asset))
// The default axum body size limit is 2MiB, so we increase it to 1GiB.
.layer(DefaultBodyLimit::max(1024 * 1024 * 1024))
.into_make_service();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
§Lists
If the incoming request will include multiple fields that share the same name (AKA lists) the field can be declared as a Vec, allowing for all occurrences of the field to be stored.
§Warning
Field size limits for Vec fields are applied to each occurrence of the field. This means that if you have a 1GiB field limit and the field contains 5 entries, the total size of the request body will be 5GiB.
use axum::http::StatusCode;
use axum_typed_multipart::{TryFromMultipart, TypedMultipart};
#[derive(TryFromMultipart)]
struct RequestData {
names: Vec<String>,
}
§Strict mode
By default, the derive macro will store the last occurrence of a field, and it will ignore
unknown fields. This behavior can be changed by using the strict
parameter in the derive
macro. This will make the macro throw an error if the request contains multiple fields with the
same name or if it contains unknown fields. In addition, when using strict mode sending fields
with a missing or empty name will result in an error.
use axum_typed_multipart::TryFromMultipart;
#[derive(TryFromMultipart)]
#[try_from_multipart(strict)]
struct RequestData {
name: String,
}
§Enums
axum_typed_multipart
also supports custom enum parsing by deriving the
TryFromField
trait:
use axum_typed_multipart::{TryFromField, TryFromMultipart};
#[derive(TryFromField)]
enum Sex {
Male,
Female,
}
#[derive(TryFromMultipart)]
struct Person {
name: String,
sex: Sex,
}
Enum fields can be renamed in two ways:
use axum_typed_multipart::TryFromField;
#[derive(TryFromField)]
// Using the `#[try_from_field(rename_all = "...")]` renaming attribute.
// It works the same as way as the `TryFromMultipart` implementation.
#[try_from_field(rename_all = "snake_case")]
enum AccountType {
// Or using the `#[field(rename = "...")]` attribute.
#[field(rename = "administrator")]
Admin,
Moderator,
Plain
}
§Custom types
If you would like to use a custom type for a field you need to implement the TryFromField trait for your type. This will allow the derive macro to generate the TryFromMultipart implementation automatically. Instead of implementing the trait directly, it is recommended to implement the TryFromChunks trait and the TryFromField trait will be implemented automatically. This is recommended since you won’t need to manually implement the size limit logic.
To implement the TryFromChunks trait for external types you will need to create a newtype wrapper and implement the trait for the wrapper.
§Custom error format
When using TypedMultipart as an argument for your handlers, when the request is malformed, the error will be serialized as a string. If you would like to customize the error format you can use the BaseMultipart struct instead. This struct is used internally by TypedMultipart and it can be used to customize the error type.
To customize the error you will need to define a custom error type and implement
IntoResponse and From<TypedMultipartError>
.
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use axum_typed_multipart::{BaseMultipart, TryFromMultipart, TypedMultipartError};
use serde::Serialize;
// Step 1: Define a custom error type.
#[derive(Serialize)]
struct CustomError {
message: String,
status: u16,
}
// Step 2: Implement `IntoResponse` for the custom error type.
impl IntoResponse for CustomError {
fn into_response(self) -> Response {
Json(self).into_response()
}
}
// Step 3: Implement `From<TypedMultipartError>` for the custom error type.
impl From<TypedMultipartError> for CustomError {
fn from(error: TypedMultipartError) -> Self {
Self { message: error.to_string(), status: error.get_status().into() }
}
}
// Step 4: Define a type alias for the multipart request (Optional).
type CustomMultipart<T> = BaseMultipart<T, CustomError>;
#[derive(TryFromMultipart)]
struct UpdatePositionRequest {
name: String,
position: u32,
}
// Step 5: Define a handler that takes the custom multipart as argument.
// If the request is malformed, a `CustomError` will be returned.
async fn update_position(data: CustomMultipart<UpdatePositionRequest>) -> StatusCode {
println!("name = '{}'", data.name);
println!("position = '{}'", data.position);
StatusCode::OK
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/position/update", post(update_position)).into_make_service();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
§Usage with utoipa
If you would like to use axum_typed_multipart
as part of a documented API then
utoipa
can provide a simple way to add documentation to
an API and automatically generate openapi.json
specifications. axum_typed_multipart
can
be used in conjunction with utoipa
easily. An example implementation is included.
Note: File uploads in utoipa
require a type of Vec<u8>
which is incompatible with
axum_typed_multipart
which uses either Bytes
or tempfile::NamedTempFile
as above. It is possible to get the best of both worlds as shown in the example.
The example can be found in the example directory.
§Validation
In order to perform validation on the various attributes of a field, I would recommend using the validator crate together with the axum-valid crate. A nice example can be found at docs.rs.
Structs§
- Base
Multipart - Used as an argument for axum Handlers.
- Field
Data - Wrapper struct that allows to retrieve both the field contents and the additional metadata provided by the client.
- Field
Metadata - Additional information about the file supplied by the client in the request.
- Typed
Multipart - Used as an argument for axum Handlers.
Enums§
- Typed
Multipart Error - Error type for the TryFromMultipart trait.
Traits§
- TryFrom
Chunks - Types that can be created from a Stream of Bytes.
- TryFrom
Field - Types that can be created from an instance of Field.
- TryFrom
Multipart - Types that can be created from an instance of Multipart.