Skip to content

Support upload file model#715

Merged
uncle-lv merged 10 commits intoapiflask:mainfrom
uncle-lv:pydantic-file-model
Mar 21, 2026
Merged

Support upload file model#715
uncle-lv merged 10 commits intoapiflask:mainfrom
uncle-lv:pydantic-file-model

Conversation

@uncle-lv
Copy link
Copy Markdown
Member

@uncle-lv uncle-lv commented Dec 2, 2025

Add FileModel for Pydantic.

Changes:

  • Add FileModel for Pydantic
  • Upgrade OPENAPI_VERSION to 3.1.0 for file upload in Swagger UI.
  • Fix OpenAPI link object tests, because parameters must be a string in 3.1.0.
image

Example:

import os
from typing import Annotated

from werkzeug.utils import secure_filename
from apiflask.fields import UploadFile
from apiflask.validators import validate_file_size
from apiflask.validators import validate_file_type
from apiflask import APIFlask
from pydantic import AfterValidator
from pydantic import BaseModel


app = APIFlask(__name__)


class Image(BaseModel):
    image: Annotated[
        UploadFile,
        AfterValidator(validate_file_type(['.png', '.jpg', '.jpeg', '.gif'])),
        AfterValidator(validate_file_size(max='5 MB')),
    ]


class ProfileIn(BaseModel):
    name: str
    avatar: Annotated[
        UploadFile,
        AfterValidator(validate_file_type(['.png', '.jpg', '.jpeg'])),
        AfterValidator(validate_file_size(max='2 MB')),
    ]


@app.post('/images')
@app.input(Image, location='files')
def upload_image(files_data: Image):
    f = files_data.image

    filename = secure_filename(f.filename)
    f.save(os.path.join(upload_dir, filename))

    return {'message': f'file {filename} saved.'}


@app.post('/profiles')
@app.input(ProfileIn, location='form_and_files')
def create_profile(form_and_files_data: ProfileIn):
    avatar_file = form_and_files_data.avatar
    name = form_and_files_data.name

    avatar_filename = secure_filename(avatar_file.filename)
    avatar_file.save(os.path.join(upload_dir, avatar_filename))

    return {'message': f"{name}'s profile created."}

fixes #701 .

Checklist:

  • Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.
  • Add or update relevant docs, in the docs folder and in code docstring.
  • Add an entry in CHANGES.md summarizing the change and linking to the issue.
  • Add *Version changed* or *Version added* note in any relevant docs and docstring.
  • Run pytest and tox, no tests failed.

@uncle-lv uncle-lv merged commit ff79da1 into apiflask:main Mar 21, 2026
17 checks passed
@uncle-lv uncle-lv deleted the pydantic-file-model branch March 26, 2026 08:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add FileModel for Pydantic

1 participant