Crate axum_typed_multipart
source ·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
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
- tempfile::NamedTempFile (v3)
- uuid::Uuid (v1)
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, with the
exception of Option and Vec types, which will be set respectively as
Option::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 both the request body
size limit and the field size limit. The request body size limit can be
increased using the DefaultBodyLimit
middleware, while the field size limit can be increased using the limit
parameter of the form_data
attribute.
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::NamedTempFile;
#[derive(TryFromMultipart)]
struct UploadAssetRequest {
// The `unlimited arguments` means that this field will be limited to the
// total size of the request body. If you want to limit the size of this
// field to a specific value you can also specify a limit in bytes, like
// '5MiB' or '1GiB'.
#[form_data(limit = "unlimited")]
image: FieldData<NamedTempFile>,
// This field will be limited to the default size of 1MiB.
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();
}
Structs
- Used as as an argument for axum Handlers.
- Wrapper struct that allows to retrieve both the field contents and the additional metadata provided by the client.
- Additional information about the file supplied by the client in the request.
- Used as as an argument for axum Handlers.
Enums
- Error type for the TryFromMultipart trait.
Traits
- Types that can be created from an instance of Field.
- Types that can be created from an instance of Multipart.