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
27 changes: 19 additions & 8 deletions fastapi/_compat/v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,25 @@ class GenerateJsonSchema(_GenerateJsonSchema):
# TODO: remove when this is merged (or equivalent): https://github.com/pydantic/pydantic/pull/12841
# and dropping support for any version of Pydantic before that one (so, in a very long time)
def bytes_schema(self, schema: CoreSchema) -> JsonSchemaValue:
json_schema = {"type": "string", "contentMediaType": "application/octet-stream"}
bytes_mode = (
self._config.ser_json_bytes
if self.mode == "serialization"
else self._config.val_json_bytes
)
if bytes_mode == "base64":
json_schema["contentEncoding"] = "base64"
is_file_upload = schema.get("metadata", {}).get("fastapi_file_upload", False)
if is_file_upload:
json_schema: JsonSchemaValue = {
"type": "string",
"format": "binary",
"contentMediaType": "application/octet-stream",
}
else:
json_schema = {
"type": "string",
"contentMediaType": "application/octet-stream",
}
bytes_mode = (
self._config.ser_json_bytes
if self.mode == "serialization"
else self._config.val_json_bytes
)
if bytes_mode == "base64":
json_schema["contentEncoding"] = "base64"
self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes)
return json_schema

Expand Down
6 changes: 5 additions & 1 deletion fastapi/datastructures.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,11 @@ def _validate(cls, __input_value: Any, _: Any) -> "UploadFile":
def __get_pydantic_json_schema__(
cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler
) -> dict[str, Any]:
return {"type": "string", "contentMediaType": "application/octet-stream"}
return {
"type": "string",
"format": "binary", # For compatibility with OAS 3.0
"contentMediaType": "application/octet-stream",
}

@classmethod
def __get_pydantic_core_schema__(
Expand Down
29 changes: 28 additions & 1 deletion fastapi/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from enum import Enum
from typing import Annotated, Any, Literal
from typing import Annotated, Any, Literal, cast

from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.openapi.models import Example
Expand Down Expand Up @@ -660,6 +660,32 @@ def __init__(
)


class _FileUploadMarker:
"Pydantic metadata marker to tag bytes CoreSchemas as file uploads."

@classmethod
def __get_pydantic_core_schema__(
cls, source: type[Any], handler: Any
) -> dict[str, Any]:
schema = cast(dict[str, Any], handler(source))

# Find the inner type schema (if nullable or list)
inner_type_schema = schema
if inner_type_schema.get("type") != "bytes":
if inner_type_schema.get("type") == "list":
inner_type_schema = inner_type_schema["items_schema"]
elif "schema" in inner_type_schema:
inner_type_schema = inner_type_schema["schema"]
if inner_type_schema.get("type") == "list":
inner_type_schema = inner_type_schema["items_schema"]

# If the inner type is bytes, add the file upload marker metadata
if inner_type_schema.get("type") == "bytes":
metadata: dict[str, Any] = inner_type_schema.setdefault("metadata", {})
metadata["fastapi_file_upload"] = True
return schema


class File(Form): # type: ignore[misc]
def __init__(
self,
Expand Down Expand Up @@ -740,6 +766,7 @@ def __init__(
json_schema_extra=json_schema_extra,
**extra,
)
self.metadata.append(_FileUploadMarker())


@dataclass(frozen=True)
Expand Down
117 changes: 65 additions & 52 deletions tests/test_request_params/test_file/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pytest
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
from inline_snapshot import Is, snapshot

from .utils import get_body_model_name

Expand Down Expand Up @@ -33,21 +34,24 @@ def test_list_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)

assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p": {
"type": "array",
"items": {
"type": "string",
"contentMediaType": "application/octet-stream",
assert app.openapi()["components"]["schemas"][body_model_name] == snapshot(
{
"properties": {
"p": {
"type": "array",
"items": {
"type": "string",
"format": "binary",
"contentMediaType": "application/octet-stream",
},
"title": "P",
},
"title": "P",
},
},
"required": ["p"],
"title": body_model_name,
"type": "object",
}
"required": ["p"],
"title": Is(body_model_name),
"type": "object",
}
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -114,21 +118,24 @@ def test_list_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)

assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p_alias": {
"type": "array",
"items": {
"type": "string",
"contentMediaType": "application/octet-stream",
assert app.openapi()["components"]["schemas"][body_model_name] == snapshot(
{
"properties": {
"p_alias": {
"type": "array",
"items": {
"type": "string",
"format": "binary",
"contentMediaType": "application/octet-stream",
},
"title": "P Alias",
},
"title": "P Alias",
},
},
"required": ["p_alias"],
"title": body_model_name,
"type": "object",
}
"required": ["p_alias"],
"title": Is(body_model_name),
"type": "object",
}
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -223,21 +230,24 @@ def test_list_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)

assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p_val_alias": {
"type": "array",
"items": {
"type": "string",
"contentMediaType": "application/octet-stream",
assert app.openapi()["components"]["schemas"][body_model_name] == snapshot(
{
"properties": {
"p_val_alias": {
"type": "array",
"items": {
"type": "string",
"format": "binary",
"contentMediaType": "application/octet-stream",
},
"title": "P Val Alias",
},
"title": "P Val Alias",
},
},
"required": ["p_val_alias"],
"title": body_model_name,
"type": "object",
}
"required": ["p_val_alias"],
"title": Is(body_model_name),
"type": "object",
}
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -343,21 +353,24 @@ def test_list_alias_and_validation_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)

assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p_val_alias": {
"type": "array",
"items": {
"type": "string",
"contentMediaType": "application/octet-stream",
assert app.openapi()["components"]["schemas"][body_model_name] == snapshot(
{
"properties": {
"p_val_alias": {
"type": "array",
"items": {
"type": "string",
"format": "binary",
"contentMediaType": "application/octet-stream",
},
"title": "P Val Alias",
},
"title": "P Val Alias",
},
},
"required": ["p_val_alias"],
"title": body_model_name,
"type": "object",
}
"required": ["p_val_alias"],
"title": Is(body_model_name),
"type": "object",
}
)


@pytest.mark.parametrize(
Expand Down
Loading
Loading