repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py
import importlib import pytest from dirty_equals import IsStr from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial015_an_py39"), pytest.param("tutorial015_an_py310", marks=[needs_py310]), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_get_random_item(client: TestClient): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"id": IsStr(), "name": IsStr()} def test_get_item(client: TestClient): response = client.get("/items?id=isbn-9781529046137") assert response.status_code == 200, response.text assert response.json() == { "id": "isbn-9781529046137", "name": "The Hitchhiker's Guide to the Galaxy", } def test_get_item_does_not_exist(client: TestClient): response = client.get("/items?id=isbn-nope") assert response.status_code == 200, response.text assert response.json() == {"id": "isbn-nope", "name": None} def test_get_invalid_item(client: TestClient): response = client.get("/items?id=wtf-yes") assert response.status_code == 422, response.text assert response.json() == snapshot( { "detail": [ { "type": "value_error", "loc": ["query", "id"], "msg": 'Value error, Invalid ID format, it must start with "isbn-" or "imdb-"', "input": "wtf-yes", "ctx": {"error": {}}, } ] } ) def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "name": "id", "in": "query", "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Id", }, } ], "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError" }, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial005.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ pytest.param("tutorial005_py39"), pytest.param("tutorial005_an_py39"), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_query(client: TestClient): response = client.get("/items/", params={"q": "query"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "query", } def test_query_params_str_validations_q_short(client: TestClient): response = client.get("/items/", params={"q": "fa"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_short", "loc": ["query", "q"], "msg": "String should have at least 3 characters", "input": "fa", "ctx": {"min_length": 3}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "type": "string", "default": "fixedquery", "minLength": 3, "title": "Q", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial006.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ pytest.param("tutorial006_py39"), pytest.param("tutorial006_an_py39"), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": None, } ] } def test_query_params_str_validations_q_fixedquery(client: TestClient): response = client.get("/items/", params={"q": "fixedquery"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_fixedquery_too_short(client: TestClient): response = client.get("/items/", params={"q": "fa"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_short", "loc": ["query", "q"], "msg": "String should have at least 3 characters", "input": "fa", "ctx": {"min_length": 3}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": True, "schema": { "type": "string", "minLength": 3, "title": "Q", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial011_py39"), pytest.param("tutorial011_py310", marks=needs_py310), pytest.param("tutorial011_an_py39"), pytest.param("tutorial011_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": None} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "anyOf": [ {"type": "array", "items": {"type": "string"}}, {"type": "null"}, ], "title": "Q", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ "tutorial013_py39", "tutorial013_an_py39", ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": []} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "title": "Q", "type": "array", "items": {}, "default": [], }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial009.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial009_py39"), pytest.param("tutorial009_py310", marks=needs_py310), pytest.param("tutorial009_an_py39"), pytest.param("tutorial009_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_item_query_fixedquery(client: TestClient): response = client.get("/items/", params={"item-query": "fixedquery"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_fixedquery(client: TestClient): response = client.get("/items/", params={"q": "fixedquery"}) assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "schema": { "anyOf": [ {"type": "string"}, {"type": "null"}, ], "title": "Item-Query", }, "required": False, "name": "item-query", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/__init__.py
tests/test_tutorial/test_query_params_str_validations/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py
import importlib import pytest from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial010_py39"), pytest.param("tutorial010_py310", marks=needs_py310), pytest.param("tutorial010_an_py39"), pytest.param("tutorial010_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_item_query_fixedquery(client: TestClient): response = client.get("/items/", params={"item-query": "fixedquery"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_fixedquery(client: TestClient): response = client.get("/items/", params={"q": "fixedquery"}) assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): response = client.get("/items/", params={"item-query": "nonregexquery"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_pattern_mismatch", "loc": ["query", "item-query"], "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "description": "Query string for the items to search in the database that have a good match", "required": False, "deprecated": True, "schema": { "anyOf": [ { "type": "string", "minLength": 3, "maxLength": 50, "pattern": "^fixedquery$", }, {"type": "null"}, ], "title": "Query string", "description": "Query string for the items to search in the database that have a good match", # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. **( {"deprecated": True} if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) else {} ), }, "name": "item-query", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial004.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial004_py39"), pytest.param("tutorial004_py310", marks=needs_py310), pytest.param("tutorial004_an_py39"), pytest.param("tutorial004_an_py310", marks=needs_py310), pytest.param( "tutorial004_regex_an_py310", marks=( needs_py310, pytest.mark.filterwarnings( "ignore:`regex` has been deprecated, please use `pattern` instead:fastapi.exceptions.FastAPIDeprecationWarning" ), ), ), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_q_fixedquery(client: TestClient): response = client.get("/items/", params={"q": "fixedquery"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_nonregexquery(client: TestClient): response = client.get("/items/", params={"q": "nonregexquery"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_pattern_mismatch", "loc": ["query", "q"], "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "anyOf": [ { "type": "string", "minLength": 3, "maxLength": 50, "pattern": "^fixedquery$", }, {"type": "null"}, ], "title": "Q", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial008.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial008_py39"), pytest.param("tutorial008_py310", marks=needs_py310), pytest.param("tutorial008_an_py39"), pytest.param("tutorial008_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_q_fixedquery(client: TestClient): response = client.get("/items/", params={"q": "fixedquery"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "fixedquery", } def test_query_params_str_validations_q_fixedquery_too_short(client: TestClient): response = client.get("/items/", params={"q": "fa"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_short", "loc": ["query", "q"], "msg": "String should have at least 3 characters", "input": "fa", "ctx": {"min_length": 3}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "description": "Query string for the items to search in the database that have a good match", "required": False, "schema": { "anyOf": [ { "type": "string", "minLength": 3, }, {"type": "null"}, ], "title": "Query string", "description": "Query string for the items to search in the database that have a good match", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial003.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial003_py39"), pytest.param("tutorial003_py310", marks=needs_py310), pytest.param("tutorial003_an_py39"), pytest.param("tutorial003_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations_no_query(client: TestClient): response = client.get("/items/") assert response.status_code == 200 assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} def test_query_params_str_validations_q_query(client: TestClient): response = client.get("/items/", params={"q": "query"}) assert response.status_code == 200 assert response.json() == { "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], "q": "query", } def test_query_params_str_validations_q_too_short(client: TestClient): response = client.get("/items/", params={"q": "qu"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_short", "loc": ["query", "q"], "msg": "String should have at least 3 characters", "input": "qu", "ctx": {"min_length": 3}, } ] } def test_query_params_str_validations_q_too_long(client: TestClient): response = client.get("/items/", params={"q": "q" * 51}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_long", "loc": ["query", "q"], "msg": "String should have at most 50 characters", "input": "q" * 51, "ctx": {"max_length": 50}, } ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "anyOf": [ { "type": "string", "minLength": 3, "maxLength": 50, }, {"type": "null"}, ], "title": "Q", }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ pytest.param("tutorial012_py39"), pytest.param("tutorial012_an_py39"), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.query_params_str_validations.{request.param}" ) client = TestClient(mod.app) return client def test_default_query_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} def test_multi_query_values(client: TestClient): url = "/items/?q=baz&q=foobar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["baz", "foobar"]} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Read Items", "operationId": "read_items_items__get", "parameters": [ { "required": False, "schema": { "title": "Q", "type": "array", "items": {"type": "string"}, "default": ["foo", "bar"], }, "name": "q", "in": "query", } ], } } }, "components": { "schemas": { "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/test_tutorial002.py
tests/test_tutorial/test_request_files/test_tutorial002.py
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient @pytest.fixture( name="app", params=[ "tutorial002_py39", "tutorial002_an_py39", ], ) def get_app(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_files.{request.param}") return mod.app @pytest.fixture(name="client") def get_client(app: FastAPI): client = TestClient(app) return client def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "files"], "msg": "Field required", "input": None, } ] } def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "files"], "msg": "Field required", "input": None, } ] } def test_post_files(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/files/", files=( ("files", ("test.txt", file)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"file_sizes": [14, 15]} def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/uploadfiles/", files=( ("files", ("test.txt", file)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"filenames": ["test.txt", "test2.txt"]} def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"<form" in response.content def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Files", "operationId": "create_files_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_files_files__post" } } }, "required": True, }, } }, "/uploadfiles/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Upload Files", "operationId": "create_upload_files_uploadfiles__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_upload_files_uploadfiles__post" } } }, "required": True, }, } }, "/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "summary": "Main", "operationId": "main__get", } }, }, "components": { "schemas": { "Body_create_upload_files_uploadfiles__post": { "title": "Body_create_upload_files_uploadfiles__post", "required": ["files"], "type": "object", "properties": { "files": { "title": "Files", "type": "array", "items": {"type": "string", "format": "binary"}, } }, }, "Body_create_files_files__post": { "title": "Body_create_files_files__post", "required": ["files"], "type": "object", "properties": { "files": { "title": "Files", "type": "array", "items": {"type": "string", "format": "binary"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/test_tutorial001.py
tests/test_tutorial/test_request_files/test_tutorial001.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ "tutorial001_py39", "tutorial001_an_py39", ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_files.{request.param}") client = TestClient(mod.app) return client def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "file"], "msg": "Field required", "input": None, } ] } def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "file"], "msg": "Field required", "input": None, } ] } def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} def test_post_large_file(tmp_path, client: TestClient): default_pydantic_max_size = 2**16 path = tmp_path / "test.txt" path.write_bytes(b"x" * (default_pydantic_max_size + 1)) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": default_pydantic_max_size + 1} def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create File", "operationId": "create_file_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_file_files__post" } } }, "required": True, }, } }, "/uploadfile/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create Upload File", "operationId": "create_upload_file_uploadfile__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" } } }, "required": True, }, } }, }, "components": { "schemas": { "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "required": ["file"], "type": "object", "properties": { "file": {"title": "File", "type": "string", "format": "binary"} }, }, "Body_create_file_files__post": { "title": "Body_create_file_files__post", "required": ["file"], "type": "object", "properties": { "file": {"title": "File", "type": "string", "format": "binary"} }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/test_tutorial001_02.py
tests/test_tutorial/test_request_files/test_tutorial001_02.py
import importlib from pathlib import Path import pytest from fastapi.testclient import TestClient from inline_snapshot import snapshot from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial001_02_py39"), pytest.param("tutorial001_02_py310", marks=needs_py310), pytest.param("tutorial001_02_an_py39"), pytest.param("tutorial001_02_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_files.{request.param}") client = TestClient(mod.app) return client def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 200, response.text assert response.json() == {"message": "No file sent"} def test_post_uploadfile_no_body(client: TestClient): response = client.post("/uploadfile/") assert response.status_code == 200, response.text assert response.json() == {"message": "No upload file sent"} def test_post_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} def test_post_upload_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "summary": "Create File", "operationId": "create_file_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_file_files__post" } } } }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/uploadfile/": { "post": { "summary": "Create Upload File", "operationId": "create_upload_file_uploadfile__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" } } } }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_create_file_files__post": { "title": "Body_create_file_files__post", "type": "object", "properties": { "file": { "title": "File", "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], } }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "type": "object", "properties": { "file": { "title": "File", "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], } }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": { "$ref": "#/components/schemas/ValidationError" }, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/test_tutorial001_03.py
tests/test_tutorial/test_request_files/test_tutorial001_03.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ "tutorial001_03_py39", "tutorial001_03_an_py39", ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_files.{request.param}") client = TestClient(mod.app) return client def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "summary": "Create File", "operationId": "create_file_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_file_files__post" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/uploadfile/": { "post": { "summary": "Create Upload File", "operationId": "create_upload_file_uploadfile__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_create_file_files__post": { "title": "Body_create_file_files__post", "required": ["file"], "type": "object", "properties": { "file": { "title": "File", "type": "string", "description": "A file read as bytes", "format": "binary", } }, }, "Body_create_upload_file_uploadfile__post": { "title": "Body_create_upload_file_uploadfile__post", "required": ["file"], "type": "object", "properties": { "file": { "title": "File", "type": "string", "description": "A file read as UploadFile", "format": "binary", } }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/__init__.py
tests/test_tutorial/test_request_files/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_files/test_tutorial003.py
tests/test_tutorial/test_request_files/test_tutorial003.py
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient @pytest.fixture( name="app", params=[ "tutorial003_py39", "tutorial003_an_py39", ], ) def get_app(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_files.{request.param}") return mod.app @pytest.fixture(name="client") def get_client(app: FastAPI): client = TestClient(app) return client def test_post_files(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/files/", files=( ("files", ("test.txt", file)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"file_sizes": [14, 15]} def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") path2 = tmp_path / "test2.txt" path2.write_bytes(b"<file content2>") client = TestClient(app) with path.open("rb") as file, path2.open("rb") as file2: response = client.post( "/uploadfiles/", files=( ("files", ("test.txt", file)), ("files", ("test2.txt", file2)), ), ) assert response.status_code == 200, response.text assert response.json() == {"filenames": ["test.txt", "test2.txt"]} def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"<form" in response.content def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "summary": "Create Files", "operationId": "create_files_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_files_files__post" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/uploadfiles/": { "post": { "summary": "Create Upload Files", "operationId": "create_upload_files_uploadfiles__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_upload_files_uploadfiles__post" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/": { "get": { "summary": "Main", "operationId": "main__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, }, "components": { "schemas": { "Body_create_files_files__post": { "title": "Body_create_files_files__post", "required": ["files"], "type": "object", "properties": { "files": { "title": "Files", "type": "array", "items": {"type": "string", "format": "binary"}, "description": "Multiple files as bytes", } }, }, "Body_create_upload_files_uploadfiles__post": { "title": "Body_create_upload_files_uploadfiles__post", "required": ["files"], "type": "object", "properties": { "files": { "title": "Files", "type": "array", "items": {"type": "string", "format": "binary"}, "description": "Multiple files as UploadFile", } }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py
import importlib import pytest from fastapi import FastAPI from fastapi.testclient import TestClient @pytest.fixture( name="app", params=[ "tutorial001_py39", "tutorial001_an_py39", ], ) def get_app(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_forms_and_files.{request.param}") return mod.app @pytest.fixture(name="client") def get_client(app: FastAPI): client = TestClient(app) return client def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "file"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, }, ] } def test_post_form_no_file(client: TestClient): response = client.post("/files/", data={"token": "foo"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "file"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, }, ] } def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "file"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, }, ] } def test_post_file_no_token(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"<file content>") client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "fileb"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "token"], "msg": "Field required", "input": None, }, ] } def test_post_files_and_token(tmp_path, app: FastAPI): patha = tmp_path / "test.txt" pathb = tmp_path / "testb.txt" patha.write_text("<file content>") pathb.write_text("<file b content>") client = TestClient(app) with patha.open("rb") as filea, pathb.open("rb") as fileb: response = client.post( "/files/", data={"token": "foo"}, files={"file": filea, "fileb": ("testb.txt", fileb, "text/plain")}, ) assert response.status_code == 200, response.text assert response.json() == { "file_size": 14, "token": "foo", "fileb_content_type": "text/plain", } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/files/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create File", "operationId": "create_file_files__post", "requestBody": { "content": { "multipart/form-data": { "schema": { "$ref": "#/components/schemas/Body_create_file_files__post" } } }, "required": True, }, } } }, "components": { "schemas": { "Body_create_file_files__post": { "title": "Body_create_file_files__post", "required": ["file", "fileb", "token"], "type": "object", "properties": { "file": {"title": "File", "type": "string", "format": "binary"}, "fileb": { "title": "Fileb", "type": "string", "format": "binary", }, "token": {"title": "Token", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_forms_and_files/__init__.py
tests/test_tutorial/test_request_forms_and_files/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_cors/test_tutorial001.py
tests/test_tutorial/test_cors/test_tutorial001.py
from fastapi.testclient import TestClient from docs_src.cors.tutorial001_py39 import app def test_cors(): client = TestClient(app) # Test pre-flight response headers = { "Origin": "https://localhost.tiangolo.com", "Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "X-Example", } response = client.options("/", headers=headers) assert response.status_code == 200, response.text assert response.text == "OK" assert ( response.headers["access-control-allow-origin"] == "https://localhost.tiangolo.com" ) assert response.headers["access-control-allow-headers"] == "X-Example" # Test standard response headers = {"Origin": "https://localhost.tiangolo.com"} response = client.get("/", headers=headers) assert response.status_code == 200, response.text assert response.json() == {"message": "Hello World"} assert ( response.headers["access-control-allow-origin"] == "https://localhost.tiangolo.com" ) # Test non-CORS response response = client.get("/") assert response.status_code == 200, response.text assert response.json() == {"message": "Hello World"} assert "access-control-allow-origin" not in response.headers
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_cors/__init__.py
tests/test_tutorial/test_cors/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
tests/test_tutorial/test_testing_dependencies/test_tutorial001.py
import importlib from types import ModuleType import pytest from ...utils import needs_py310 @pytest.fixture( name="test_module", params=[ pytest.param("tutorial001_py39"), pytest.param("tutorial001_py310", marks=needs_py310), pytest.param("tutorial001_an_py39"), pytest.param("tutorial001_an_py310", marks=needs_py310), ], ) def get_test_module(request: pytest.FixtureRequest) -> ModuleType: mod: ModuleType = importlib.import_module( f"docs_src.dependency_testing.{request.param}" ) return mod def test_override_in_items_run(test_module: ModuleType): test_override_in_items = test_module.test_override_in_items test_override_in_items() def test_override_in_items_with_q_run(test_module: ModuleType): test_override_in_items_with_q = test_module.test_override_in_items_with_q test_override_in_items_with_q() def test_override_in_items_with_params_run(test_module: ModuleType): test_override_in_items_with_params = test_module.test_override_in_items_with_params test_override_in_items_with_params() def test_override_in_users(test_module: ModuleType): client = test_module.client response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": None, "skip": 5, "limit": 10}, } def test_override_in_users_with_q(test_module: ModuleType): client = test_module.client response = client.get("/users/?q=foo") assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_override_in_users_with_params(test_module: ModuleType): client = test_module.client response = client.get("/users/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Users!", "params": {"q": "foo", "skip": 5, "limit": 10}, } def test_normal_app(test_module: ModuleType): app = test_module.app client = test_module.client app.dependency_overrides = None response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text assert response.json() == { "message": "Hello Items!", "params": {"q": "foo", "skip": 100, "limit": 200}, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_testing_dependencies/__init__.py
tests/test_tutorial/test_testing_dependencies/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
tests/test_tutorial/test_schema_extra_example/test_tutorial002.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial002_py39"), pytest.param("tutorial002_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") client = TestClient(mod.app) return client def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ) assert response.status_code == 200 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text # insert_assert(response.json()) assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "name": "item_id", "in": "path", "required": True, "schema": {"type": "integer", "title": "Item Id"}, } ], "requestBody": { "required": True, "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": { "name": { "type": "string", "title": "Name", "examples": ["Foo"], }, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", "examples": ["A very nice Item"], }, "price": { "type": "number", "title": "Price", "examples": [35.4], }, "tax": { "anyOf": [{"type": "number"}, {"type": "null"}], "title": "Tax", "examples": [3.2], }, }, "type": "object", "required": ["name", "price"], "title": "Item", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
tests/test_tutorial/test_schema_extra_example/test_tutorial001.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial001_py39"), pytest.param("tutorial001_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") client = TestClient(mod.app) return client def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ) assert response.status_code == 200 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text # insert_assert(response.json()) assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "name": "item_id", "in": "path", "required": True, "schema": {"type": "integer", "title": "Item Id"}, } ], "requestBody": { "required": True, "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": { "name": {"type": "string", "title": "Name"}, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", }, "price": {"type": "number", "title": "Price"}, "tax": { "anyOf": [{"type": "number"}, {"type": "null"}], "title": "Tax", }, }, "type": "object", "required": ["name", "price"], "title": "Item", "examples": [ { "description": "A very nice Item", "name": "Foo", "price": 35.4, "tax": 3.2, } ], }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
tests/test_tutorial/test_schema_extra_example/test_tutorial005.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial005_py39"), pytest.param("tutorial005_py310", marks=needs_py310), pytest.param("tutorial005_an_py39"), pytest.param("tutorial005_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") client = TestClient(mod.app) return client def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ) assert response.status_code == 200 def test_openapi_schema(client: TestClient) -> None: response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "integer"}, "name": "item_id", "in": "path", } ], "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"}, "examples": { "normal": { "summary": "A normal example", "description": "A **normal** item works correctly.", "value": { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, }, "converted": { "summary": "An example with converted data", "description": "FastAPI can convert price `strings` to actual `numbers` automatically", "value": {"name": "Bar", "price": "35.4"}, }, "invalid": { "summary": "Invalid data is rejected with an error", "value": { "name": "Baz", "price": "thirty five point four", }, }, }, } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/__init__.py
tests/test_tutorial/test_schema_extra_example/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
tests/test_tutorial/test_schema_extra_example/test_tutorial004.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial004_py39"), pytest.param("tutorial004_py310", marks=needs_py310), pytest.param("tutorial004_an_py39"), pytest.param("tutorial004_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") client = TestClient(mod.app) return client def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ) assert response.status_code == 200 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "required": True, "schema": {"title": "Item Id", "type": "integer"}, "name": "item_id", "in": "path", } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", "examples": [ { "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, {"name": "Bar", "price": "35.4"}, { "name": "Baz", "price": "thirty five point four", }, ], } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
tests/test_tutorial/test_schema_extra_example/test_tutorial003.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial003_py39"), pytest.param("tutorial003_py310", marks=needs_py310), pytest.param("tutorial003_an_py39"), pytest.param("tutorial003_an_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") client = TestClient(mod.app) return client def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ "name": "Foo", "description": "A very nice Item", "price": 35.4, "tax": 3.2, }, ) assert response.status_code == 200 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text # insert_assert(response.json()) assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/{item_id}": { "put": { "summary": "Update Item", "operationId": "update_item_items__item_id__put", "parameters": [ { "name": "item_id", "in": "path", "required": True, "schema": {"type": "integer", "title": "Item Id"}, } ], "requestBody": { "required": True, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Item", "examples": [ { "description": "A very nice Item", "name": "Foo", "price": 35.4, "tax": 3.2, } ], }, } }, }, "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": {"$ref": "#/components/schemas/ValidationError"}, "type": "array", "title": "Detail", } }, "type": "object", "title": "HTTPValidationError", }, "Item": { "properties": { "name": {"type": "string", "title": "Name"}, "description": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "Description", }, "price": {"type": "number", "title": "Price"}, "tax": { "anyOf": [{"type": "number"}, {"type": "null"}], "title": "Tax", }, }, "type": "object", "required": ["name", "price"], "title": "Item", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, "type": "array", "title": "Location", }, "msg": {"type": "string", "title": "Message"}, "type": {"type": "string", "title": "Error Type"}, }, "type": "object", "required": ["loc", "msg", "type"], "title": "ValidationError", }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_forms/test_tutorial001.py
tests/test_tutorial/test_request_forms/test_tutorial001.py
import importlib import pytest from fastapi.testclient import TestClient @pytest.fixture( name="client", params=[ "tutorial001_py39", "tutorial001_an_py39", ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module(f"docs_src.request_forms.{request.param}") client = TestClient(mod.app) return client def test_post_body_form(client: TestClient): response = client.post("/login/", data={"username": "Foo", "password": "secret"}) assert response.status_code == 200 assert response.json() == {"username": "Foo"} def test_post_body_form_no_password(client: TestClient): response = client.post("/login/", data={"username": "Foo"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, } ] } def test_post_body_form_no_username(client: TestClient): response = client.post("/login/", data={"password": "secret"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, } ] } def test_post_body_form_no_data(client: TestClient): response = client.post("/login/") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, }, ] } def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, }, ] } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/login/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Login", "operationId": "login_login__post", "requestBody": { "content": { "application/x-www-form-urlencoded": { "schema": { "$ref": "#/components/schemas/Body_login_login__post" } } }, "required": True, }, } } }, "components": { "schemas": { "Body_login_login__post": { "title": "Body_login_login__post", "required": ["username", "password"], "type": "object", "properties": { "username": {"title": "Username", "type": "string"}, "password": {"title": "Password", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_request_forms/__init__.py
tests/test_tutorial/test_request_forms/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_response_cookies/test_tutorial002.py
tests/test_tutorial/test_response_cookies/test_tutorial002.py
from fastapi.testclient import TestClient from docs_src.response_cookies.tutorial002_py39 import app client = TestClient(app) def test_path_operation(): response = client.post("/cookie-and-object/") assert response.status_code == 200, response.text assert response.json() == {"message": "Come to the dark side, we have cookies"} assert response.cookies["fakesession"] == "fake-cookie-session-value"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_response_cookies/test_tutorial001.py
tests/test_tutorial/test_response_cookies/test_tutorial001.py
from fastapi.testclient import TestClient from docs_src.response_cookies.tutorial001_py39 import app client = TestClient(app) def test_path_operation(): response = client.post("/cookie/") assert response.status_code == 200, response.text assert response.json() == {"message": "Come to the dark side, we have cookies"} assert response.cookies["fakesession"] == "fake-cookie-session-value"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_response_cookies/__init__.py
tests/test_tutorial/test_response_cookies/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial002.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial002_py39"), pytest.param("tutorial002_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest) -> TestClient: mod = importlib.import_module( f"docs_src.path_operation_configuration.{request.param}" ) return TestClient(mod.app) def test_post_items(client: TestClient): response = client.post( "/items/", json={ "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": ["bar", "baz"], }, ) assert response.status_code == 200, response.text assert response.json() == { "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": IsList("bar", "baz", check_order=False), } def test_get_items(client: TestClient): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == [{"name": "Foo", "price": 42}] def test_get_users(client: TestClient): response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == [{"username": "johndoe"}] def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "tags": ["items"], "summary": "Read Items", "operationId": "read_items_items__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, }, "post": { "tags": ["items"], "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, "/users/": { "get": { "tags": ["users"], "summary": "Read Users", "operationId": "read_users_users__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError", }, "title": "Detail", "type": "array", }, }, "title": "HTTPValidationError", "type": "object", }, "Item": { "properties": { "description": { "anyOf": [ { "type": "string", }, { "type": "null", }, ], "title": "Description", }, "name": { "title": "Name", "type": "string", }, "price": { "title": "Price", "type": "number", }, "tags": { "default": [], "items": { "type": "string", }, "title": "Tags", "type": "array", "uniqueItems": True, }, "tax": { "anyOf": [ { "type": "number", }, { "type": "null", }, ], "title": "Tax", }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [ { "type": "string", }, { "type": "integer", }, ], }, "title": "Location", "type": "array", }, "msg": { "title": "Message", "type": "string", }, "type": { "title": "Error Type", "type": "string", }, }, "required": [ "loc", "msg", "type", ], "title": "ValidationError", "type": "object", }, }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial001.py
import importlib import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial001_py39"), pytest.param("tutorial001_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest) -> TestClient: mod = importlib.import_module( f"docs_src.path_operation_configuration.{request.param}" ) return TestClient(mod.app) def test_post_items(client: TestClient): response = client.post( "/items/", json={ "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": ["bar", "baz"], }, ) assert response.status_code == 201, response.text assert response.json() == { "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": IsList("bar", "baz", check_order=False), } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "summary": "Create Item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, "responses": { "201": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError", }, "title": "Detail", "type": "array", }, }, "title": "HTTPValidationError", "type": "object", }, "Item": { "properties": { "description": { "anyOf": [ { "type": "string", }, { "type": "null", }, ], "title": "Description", }, "name": { "title": "Name", "type": "string", }, "price": { "title": "Price", "type": "number", }, "tags": { "default": [], "items": { "type": "string", }, "title": "Tags", "type": "array", "uniqueItems": True, }, "tax": { "anyOf": [ { "type": "number", }, { "type": "null", }, ], "title": "Tax", }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [ { "type": "string", }, { "type": "integer", }, ], }, "title": "Location", "type": "array", }, "msg": { "title": "Message", "type": "string", }, "type": { "title": "Error Type", "type": "string", }, }, "required": [ "loc", "msg", "type", ], "title": "ValidationError", "type": "object", }, }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py
import importlib import pytest from fastapi.testclient import TestClient from ...utils import needs_py310 @pytest.fixture( name="client", params=[ pytest.param("tutorial005_py39"), pytest.param("tutorial005_py310", marks=needs_py310), ], ) def get_client(request: pytest.FixtureRequest): mod = importlib.import_module( f"docs_src.path_operation_configuration.{request.param}" ) client = TestClient(mod.app) return client def test_query_params_str_validations(client: TestClient): response = client.post("/items/", json={"name": "Foo", "price": 42}) assert response.status_code == 200, response.text assert response.json() == { "name": "Foo", "price": 42, "description": None, "tax": None, "tags": [], } def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "responses": { "200": { "description": "The created item", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Create an item", "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, } } }, "components": { "schemas": { "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "description": { "title": "Description", "anyOf": [{"type": "string"}, {"type": "null"}], }, "price": {"title": "Price", "type": "number"}, "tax": { "title": "Tax", "anyOf": [{"type": "number"}, {"type": "null"}], }, "tags": { "title": "Tags", "uniqueItems": True, "type": "array", "items": {"type": "string"}, "default": [], }, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial006.py
import pytest from fastapi.testclient import TestClient from docs_src.path_operation_configuration.tutorial006_py39 import app client = TestClient(app) @pytest.mark.parametrize( "path,expected_status,expected_response", [ ("/items/", 200, [{"name": "Foo", "price": 42}]), ("/users/", 200, [{"username": "johndoe"}]), ("/elements/", 200, [{"item_id": "Foo"}]), ], ) def test_query_params_str_validations(path, expected_status, expected_response): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "tags": ["items"], "summary": "Read Items", "operationId": "read_items_items__get", } }, "/users/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "tags": ["users"], "summary": "Read Users", "operationId": "read_users_users__get", } }, "/elements/": { "get": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, "tags": ["items"], "summary": "Read Elements", "operationId": "read_elements_elements__get", "deprecated": True, } }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/__init__.py
tests/test_tutorial/test_path_operation_configurations/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial003_tutorial004.py
import importlib from textwrap import dedent import pytest from dirty_equals import IsList from fastapi.testclient import TestClient from ...utils import needs_py310 DESCRIPTIONS = { "tutorial003": "Create an item with all the information, name, description, price, tax and a set of unique tags", "tutorial004": dedent(""" Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """).strip(), } @pytest.fixture( name="mod_name", params=[ pytest.param("tutorial003_py39"), pytest.param("tutorial003_py310", marks=needs_py310), pytest.param("tutorial004_py39"), pytest.param("tutorial004_py310", marks=needs_py310), ], ) def get_mod_name(request: pytest.FixtureRequest) -> str: return request.param @pytest.fixture(name="client") def get_client(mod_name: str) -> TestClient: mod = importlib.import_module(f"docs_src.path_operation_configuration.{mod_name}") return TestClient(mod.app) def test_post_items(client: TestClient): response = client.post( "/items/", json={ "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": ["bar", "baz"], }, ) assert response.status_code == 200, response.text assert response.json() == { "name": "Foo", "description": "Item description", "price": 42.0, "tax": 3.2, "tags": IsList("bar", "baz", check_order=False), } def test_openapi_schema(client: TestClient, mod_name: str): mod_name = mod_name[:11] response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "post": { "summary": "Create an item", "description": DESCRIPTIONS[mod_name], "operationId": "create_item_items__post", "requestBody": { "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {"$ref": "#/components/schemas/Item"} } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, }, }, }, "components": { "schemas": { "HTTPValidationError": { "properties": { "detail": { "items": { "$ref": "#/components/schemas/ValidationError", }, "title": "Detail", "type": "array", }, }, "title": "HTTPValidationError", "type": "object", }, "Item": { "properties": { "description": { "anyOf": [ { "type": "string", }, { "type": "null", }, ], "title": "Description", }, "name": { "title": "Name", "type": "string", }, "price": { "title": "Price", "type": "number", }, "tags": { "default": [], "items": { "type": "string", }, "title": "Tags", "type": "array", "uniqueItems": True, }, "tax": { "anyOf": [ { "type": "number", }, { "type": "null", }, ], "title": "Tax", }, }, "required": [ "name", "price", ], "title": "Item", "type": "object", }, "ValidationError": { "properties": { "loc": { "items": { "anyOf": [ { "type": "string", }, { "type": "integer", }, ], }, "title": "Location", "type": "array", }, "msg": { "title": "Message", "type": "string", }, "type": { "title": "Error Type", "type": "string", }, }, "required": [ "loc", "msg", "type", ], "title": "ValidationError", "type": "object", }, }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
tests/test_tutorial/test_path_operation_configurations/test_tutorial002b.py
from fastapi.testclient import TestClient from docs_src.path_operation_configuration.tutorial002b_py39 import app client = TestClient(app) def test_get_items(): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == ["Portal gun", "Plumbus"] def test_get_users(): response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == ["Rick", "Morty"] def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/items/": { "get": { "tags": ["items"], "summary": "Get Items", "operationId": "get_items_items__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, "/users/": { "get": { "tags": ["users"], "summary": "Read Users", "operationId": "read_users_users__get", "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, } }, } }, }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/benchmarks/test_general_performance.py
tests/benchmarks/test_general_performance.py
import json import sys from collections.abc import Iterator from typing import Annotated, Any import pytest from fastapi import Depends, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel if "--codspeed" not in sys.argv: pytest.skip( "Benchmark tests are skipped by default; run with --codspeed.", allow_module_level=True, ) LARGE_ITEMS: list[dict[str, Any]] = [ { "id": i, "name": f"item-{i}", "values": list(range(25)), "meta": { "active": True, "group": i % 10, "tag": f"t{i % 5}", }, } for i in range(300) ] LARGE_METADATA: dict[str, Any] = { "source": "benchmark", "version": 1, "flags": {"a": True, "b": False, "c": True}, "notes": ["x" * 50, "y" * 50, "z" * 50], } LARGE_PAYLOAD: dict[str, Any] = {"items": LARGE_ITEMS, "metadata": LARGE_METADATA} def dep_a(): return 40 def dep_b(a: Annotated[int, Depends(dep_a)]): return a + 2 class ItemIn(BaseModel): name: str value: int class ItemOut(BaseModel): name: str value: int dep: int class LargeIn(BaseModel): items: list[dict[str, Any]] metadata: dict[str, Any] class LargeOut(BaseModel): items: list[dict[str, Any]] metadata: dict[str, Any] app = FastAPI() @app.post("/sync/validated", response_model=ItemOut) def sync_validated(item: ItemIn, dep: Annotated[int, Depends(dep_b)]): return ItemOut(name=item.name, value=item.value, dep=dep) @app.get("/sync/dict-no-response-model") def sync_dict_no_response_model(): return {"name": "foo", "value": 123} @app.get("/sync/dict-with-response-model", response_model=ItemOut) def sync_dict_with_response_model( dep: Annotated[int, Depends(dep_b)], ): return {"name": "foo", "value": 123, "dep": dep} @app.get("/sync/model-no-response-model") def sync_model_no_response_model(dep: Annotated[int, Depends(dep_b)]): return ItemOut(name="foo", value=123, dep=dep) @app.get("/sync/model-with-response-model", response_model=ItemOut) def sync_model_with_response_model(dep: Annotated[int, Depends(dep_b)]): return ItemOut(name="foo", value=123, dep=dep) @app.post("/async/validated", response_model=ItemOut) async def async_validated( item: ItemIn, dep: Annotated[int, Depends(dep_b)], ): return ItemOut(name=item.name, value=item.value, dep=dep) @app.post("/sync/large-receive") def sync_large_receive(payload: LargeIn): return {"received": len(payload.items)} @app.post("/async/large-receive") async def async_large_receive(payload: LargeIn): return {"received": len(payload.items)} @app.get("/sync/large-dict-no-response-model") def sync_large_dict_no_response_model(): return LARGE_PAYLOAD @app.get("/sync/large-dict-with-response-model", response_model=LargeOut) def sync_large_dict_with_response_model(): return LARGE_PAYLOAD @app.get("/sync/large-model-no-response-model") def sync_large_model_no_response_model(): return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA) @app.get("/sync/large-model-with-response-model", response_model=LargeOut) def sync_large_model_with_response_model(): return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA) @app.get("/async/large-dict-no-response-model") async def async_large_dict_no_response_model(): return LARGE_PAYLOAD @app.get("/async/large-dict-with-response-model", response_model=LargeOut) async def async_large_dict_with_response_model(): return LARGE_PAYLOAD @app.get("/async/large-model-no-response-model") async def async_large_model_no_response_model(): return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA) @app.get("/async/large-model-with-response-model", response_model=LargeOut) async def async_large_model_with_response_model(): return LargeOut(items=LARGE_ITEMS, metadata=LARGE_METADATA) @app.get("/async/dict-no-response-model") async def async_dict_no_response_model(): return {"name": "foo", "value": 123} @app.get("/async/dict-with-response-model", response_model=ItemOut) async def async_dict_with_response_model( dep: Annotated[int, Depends(dep_b)], ): return {"name": "foo", "value": 123, "dep": dep} @app.get("/async/model-no-response-model") async def async_model_no_response_model( dep: Annotated[int, Depends(dep_b)], ): return ItemOut(name="foo", value=123, dep=dep) @app.get("/async/model-with-response-model", response_model=ItemOut) async def async_model_with_response_model( dep: Annotated[int, Depends(dep_b)], ): return ItemOut(name="foo", value=123, dep=dep) @pytest.fixture(scope="module") def client() -> Iterator[TestClient]: with TestClient(app) as client: yield client def _bench_get(benchmark, client: TestClient, path: str) -> tuple[int, bytes]: warmup = client.get(path) assert warmup.status_code == 200 def do_request() -> tuple[int, bytes]: response = client.get(path) return response.status_code, response.content return benchmark(do_request) def _bench_post_json( benchmark, client: TestClient, path: str, json: dict[str, Any] ) -> tuple[int, bytes]: warmup = client.post(path, json=json) assert warmup.status_code == 200 def do_request() -> tuple[int, bytes]: response = client.post(path, json=json) return response.status_code, response.content return benchmark(do_request) def test_sync_receiving_validated_pydantic_model(benchmark, client: TestClient) -> None: status_code, body = _bench_post_json( benchmark, client, "/sync/validated", json={"name": "foo", "value": 123}, ) assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_sync_return_dict_without_response_model(benchmark, client: TestClient) -> None: status_code, body = _bench_get(benchmark, client, "/sync/dict-no-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123}' def test_sync_return_dict_with_response_model(benchmark, client: TestClient) -> None: status_code, body = _bench_get(benchmark, client, "/sync/dict-with-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_sync_return_model_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get(benchmark, client, "/sync/model-no-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_sync_return_model_with_response_model(benchmark, client: TestClient) -> None: status_code, body = _bench_get(benchmark, client, "/sync/model-with-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_async_receiving_validated_pydantic_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_post_json( benchmark, client, "/async/validated", json={"name": "foo", "value": 123} ) assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_async_return_dict_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get(benchmark, client, "/async/dict-no-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123}' def test_async_return_dict_with_response_model(benchmark, client: TestClient) -> None: status_code, body = _bench_get(benchmark, client, "/async/dict-with-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_async_return_model_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get(benchmark, client, "/async/model-no-response-model") assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_async_return_model_with_response_model(benchmark, client: TestClient) -> None: status_code, body = _bench_get( benchmark, client, "/async/model-with-response-model" ) assert status_code == 200 assert body == b'{"name":"foo","value":123,"dep":42}' def test_sync_receiving_large_payload(benchmark, client: TestClient) -> None: status_code, body = _bench_post_json( benchmark, client, "/sync/large-receive", json=LARGE_PAYLOAD, ) assert status_code == 200 assert body == b'{"received":300}' def test_async_receiving_large_payload(benchmark, client: TestClient) -> None: status_code, body = _bench_post_json( benchmark, client, "/async/large-receive", json=LARGE_PAYLOAD, ) assert status_code == 200 assert body == b'{"received":300}' def _expected_large_payload_json_bytes() -> bytes: return json.dumps( LARGE_PAYLOAD, ensure_ascii=False, allow_nan=False, separators=(",", ":"), ).encode("utf-8") def test_sync_return_large_dict_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/sync/large-dict-no-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_sync_return_large_dict_with_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/sync/large-dict-with-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_sync_return_large_model_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/sync/large-model-no-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_sync_return_large_model_with_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/sync/large-model-with-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_async_return_large_dict_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/async/large-dict-no-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_async_return_large_dict_with_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/async/large-dict-with-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_async_return_large_model_without_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/async/large-model-no-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes() def test_async_return_large_model_with_response_model( benchmark, client: TestClient ) -> None: status_code, body = _bench_get( benchmark, client, "/async/large-model-with-response-model" ) assert status_code == 200 assert body == _expected_large_payload_json_bytes()
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/benchmarks/__init__.py
tests/benchmarks/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/__init__.py
tests/test_request_params/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_cookie/test_optional_list.py
tests/test_request_params/test_cookie/test_optional_list.py
# Currently, there is no way to pass multiple cookies with the same name. # The only way to pass multiple values for cookie params is to serialize them using # a comma as a delimiter, but this is not currently supported by Starlette.
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_cookie/test_list.py
tests/test_request_params/test_cookie/test_list.py
# Currently, there is no way to pass multiple cookies with the same name. # The only way to pass multiple values for cookie params is to serialize them using # a comma as a delimiter, but this is not currently supported by Starlette.
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_cookie/__init__.py
tests/test_request_params/test_cookie/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_cookie/test_required_str.py
tests/test_request_params/test_cookie/test_required_str.py
from typing import Annotated import pytest from dirty_equals import IsOneOf from fastapi import Cookie, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/required-str") async def read_required_str(p: Annotated[str, Cookie()]): return {"p": p} class CookieModelRequiredStr(BaseModel): p: str @app.get("/model-required-str") async def read_model_required_str(p: Annotated[CookieModelRequiredStr, Cookie()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P", "type": "string"}, "name": "p", "in": "cookie", } ] @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["cookie", "p"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/required-alias") async def read_required_alias(p: Annotated[str, Cookie(alias="p_alias")]): return {"p": p} class CookieModelRequiredAlias(BaseModel): p: str = Field(alias="p_alias") @app.get("/model-required-alias") async def read_model_required_alias(p: Annotated[CookieModelRequiredAlias, Cookie()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Alias", "type": "string"}, "name": "p_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["cookie", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["cookie", "p_alias"], "msg": "Field required", "input": IsOneOf( None, {"p": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_alias(path: str): client = TestClient(app) client.cookies.set("p_alias", "hello") response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/required-validation-alias") def read_required_validation_alias( p: Annotated[str, Cookie(validation_alias="p_val_alias")], ): return {"p": p} class CookieModelRequiredValidationAlias(BaseModel): p: str = Field(validation_alias="p_val_alias") @app.get("/model-required-validation-alias") def read_model_required_validation_alias( p: Annotated[CookieModelRequiredValidationAlias, Cookie()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-validation-alias", "/model-required-validation-alias"], ) def test_required_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "cookie", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["cookie", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) client.cookies.set("p_val_alias", "hello") response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/required-alias-and-validation-alias") def read_required_alias_and_validation_alias( p: Annotated[str, Cookie(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class CookieModelRequiredAliasAndValidationAlias(BaseModel): p: str = Field(alias="p_alias", validation_alias="p_val_alias") @app.get("/model-required-alias-and-validation-alias") def read_model_required_alias_and_validation_alias( p: Annotated[CookieModelRequiredAliasAndValidationAlias, Cookie()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "cookie", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "cookie", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, {"p": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) client.cookies.set("p_alias", "hello") response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["cookie", "p_val_alias"], "msg": "Field required", "input": IsOneOf( None, {"p_alias": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) client.cookies.set("p_val_alias", "hello") response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_cookie/test_optional_str.py
tests/test_request_params/test_cookie/test_optional_str.py
from typing import Annotated, Optional import pytest from fastapi import Cookie, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/optional-str") async def read_optional_str(p: Annotated[Optional[str], Cookie()] = None): return {"p": p} class CookieModelOptionalStr(BaseModel): p: Optional[str] = None @app.get("/model-optional-str") async def read_model_optional_str(p: Annotated[CookieModelOptionalStr, Cookie()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P", }, "name": "p", "in": "cookie", } ] @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/optional-alias") async def read_optional_alias( p: Annotated[Optional[str], Cookie(alias="p_alias")] = None, ): return {"p": p} class CookieModelOptionalAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias") @app.get("/model-optional-alias") async def read_model_optional_alias(p: Annotated[CookieModelOptionalAlias, Cookie()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Alias", }, "name": "p_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias", "/model-optional-alias", ], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) client.cookies.set("p_alias", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/optional-validation-alias") def read_optional_validation_alias( p: Annotated[Optional[str], Cookie(validation_alias="p_val_alias")] = None, ): return {"p": p} class CookieModelOptionalValidationAlias(BaseModel): p: Optional[str] = Field(None, validation_alias="p_val_alias") @app.get("/model-optional-validation-alias") def read_model_optional_validation_alias( p: Annotated[CookieModelOptionalValidationAlias, Cookie()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) client.cookies.set("p_val_alias", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/optional-alias-and-validation-alias") def read_optional_alias_and_validation_alias( p: Annotated[ Optional[str], Cookie(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class CookieModelOptionalAliasAndValidationAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias", validation_alias="p_val_alias") @app.get("/model-optional-alias-and-validation-alias") def read_model_optional_alias_and_validation_alias( p: Annotated[CookieModelOptionalAliasAndValidationAlias, Cookie()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "cookie", } ] @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) client.cookies.set("p", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) client.cookies.set("p_alias", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) client.cookies.set("p_val_alias", "hello") response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/test_optional_list.py
tests/test_request_params/test_body/test_optional_list.py
from typing import Annotated, Optional import pytest from fastapi import Body, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-list-str", operation_id="optional_list_str") async def read_optional_list_str( p: Annotated[Optional[list[str]], Body(embed=True)] = None, ): return {"p": p} class BodyModelOptionalListStr(BaseModel): p: Optional[list[str]] = None @app.post("/model-optional-list-str", operation_id="model_optional_list_str") async def read_model_optional_list_str(p: BodyModelOptionalListStr): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P", }, }, "title": body_model_name, "type": "object", } def test_optional_list_str_missing(): client = TestClient(app) response = client.post("/optional-list-str") assert response.status_code == 200, response.text assert response.json() == {"p": None} def test_model_optional_list_str_missing(): client = TestClient(app) response = client.post("/model-optional-list-str") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.post("/optional-list-alias", operation_id="optional_list_alias") async def read_optional_list_alias( p: Annotated[Optional[list[str]], Body(embed=True, alias="p_alias")] = None, ): return {"p": p} class BodyModelOptionalListAlias(BaseModel): p: Optional[list[str]] = Field(None, alias="p_alias") @app.post("/model-optional-list-alias", operation_id="model_optional_list_alias") async def read_model_optional_list_alias(p: BodyModelOptionalListAlias): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias", "/model-optional-list-alias", ], ) def test_optional_list_str_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_list_alias_missing(): client = TestClient(app) response = client.post("/optional-list-alias") assert response.status_code == 200, response.text assert response.json() == {"p": None} def test_model_optional_list_alias_missing(): client = TestClient(app) response = client.post("/model-optional-list-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.post( "/optional-list-validation-alias", operation_id="optional_list_validation_alias" ) def read_optional_list_validation_alias( p: Annotated[ Optional[list[str]], Body(embed=True, validation_alias="p_val_alias") ] = None, ): return {"p": p} class BodyModelOptionalListValidationAlias(BaseModel): p: Optional[list[str]] = Field(None, validation_alias="p_val_alias") @app.post( "/model-optional-list-validation-alias", operation_id="model_optional_list_validation_alias", ) def read_model_optional_list_validation_alias( p: BodyModelOptionalListValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_list_validation_alias_missing(): client = TestClient(app) response = client.post("/optional-list-validation-alias") assert response.status_code == 200, response.text assert response.json() == {"p": None} def test_model_optional_list_validation_alias_missing(): client = TestClient(app) response = client.post("/model-optional-list-validation-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-validation-alias", "/model-optional-list-validation-alias", ], ) def test_optional_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-validation-alias", "/model-optional-list-validation-alias", ], ) def test_optional_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.post( "/optional-list-alias-and-validation-alias", operation_id="optional_list_alias_and_validation_alias", ) def read_optional_list_alias_and_validation_alias( p: Annotated[ Optional[list[str]], Body(embed=True, alias="p_alias", validation_alias="p_val_alias"), ] = None, ): return {"p": p} class BodyModelOptionalListAliasAndValidationAlias(BaseModel): p: Optional[list[str]] = Field( None, alias="p_alias", validation_alias="p_val_alias" ) @app.post( "/model-optional-list-alias-and-validation-alias", operation_id="model_optional_list_alias_and_validation_alias", ) def read_model_optional_list_alias_and_validation_alias( p: BodyModelOptionalListAliasAndValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_list_alias_and_validation_alias_missing(): client = TestClient(app) response = client.post("/optional-list-alias-and-validation-alias") assert response.status_code == 200, response.text assert response.json() == {"p": None} def test_model_optional_list_alias_and_validation_alias_missing(): client = TestClient(app) response = client.post("/model-optional-list-alias-and-validation-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == { "p": [ "hello", "world", ] }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/test_list.py
tests/test_request_params/test_body/test_list.py
from typing import Annotated, Union import pytest from dirty_equals import IsOneOf, IsPartialDict from fastapi import Body, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/required-list-str", operation_id="required_list_str") async def read_required_list_str(p: Annotated[list[str], Body(embed=True)]): return {"p": p} class BodyModelRequiredListStr(BaseModel): p: list[str] @app.post("/model-required-list-str", operation_id="model_required_list_str") def read_model_required_list_str(p: BodyModelRequiredListStr): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_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": { "items": {"type": "string"}, "title": "P", "type": "array", }, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_missing(path: str, json: Union[dict, None]): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body", "p"], ["body"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.post("/required-list-alias", operation_id="required_list_alias") async def read_required_list_alias( p: Annotated[list[str], Body(embed=True, alias="p_alias")], ): return {"p": p} class BodyModelRequiredListAlias(BaseModel): p: list[str] = Field(alias="p_alias") @app.post("/model-required-list-alias", operation_id="model_required_list_alias") async def read_model_required_list_alias(p: BodyModelRequiredListAlias): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_str_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": { "items": {"type": "string"}, "title": "P Alias", "type": "array", }, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_missing(path: str, json: Union[dict, None]): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body", "p_alias"], ["body"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.post( "/required-list-validation-alias", operation_id="required_list_validation_alias" ) def read_required_list_validation_alias( p: Annotated[list[str], Body(embed=True, validation_alias="p_val_alias")], ): return {"p": p} class BodyModelRequiredListValidationAlias(BaseModel): p: list[str] = Field(validation_alias="p_val_alias") @app.post( "/model-required-list-validation-alias", operation_id="model_required_list_validation_alias", ) async def read_model_required_list_validation_alias( p: BodyModelRequiredListValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_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": { "items": {"type": "string"}, "title": "P Val Alias", "type": "array", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_missing(path: str, json: Union[dict, None]): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body"], ["body", "p_val_alias"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})), } ] } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.post( "/required-list-alias-and-validation-alias", operation_id="required_list_alias_and_validation_alias", ) def read_required_list_alias_and_validation_alias( p: Annotated[ list[str], Body(embed=True, alias="p_alias", validation_alias="p_val_alias") ], ): return {"p": p} class BodyModelRequiredListAliasAndValidationAlias(BaseModel): p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-required-list-alias-and-validation-alias", operation_id="model_required_list_alias_and_validation_alias", ) def read_model_required_list_alias_and_validation_alias( p: BodyModelRequiredListAliasAndValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_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": { "items": {"type": "string"}, "title": "P Val Alias", "type": "array", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_missing(path: str, json): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body"], ["body", "p_val_alias"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {"p": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": ["hello", "world"]}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p_alias": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/utils.py
tests/test_request_params/test_body/utils.py
from typing import Any def get_body_model_name(openapi: dict[str, Any], path: str) -> str: body = openapi["paths"][path]["post"]["requestBody"] body_schema = body["content"]["application/json"]["schema"] return body_schema.get("$ref", "").split("/")[-1]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/__init__.py
tests/test_request_params/test_body/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/test_required_str.py
tests/test_request_params/test_body/test_required_str.py
from typing import Annotated, Any, Union import pytest from dirty_equals import IsOneOf from fastapi import Body, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/required-str", operation_id="required_str") async def read_required_str(p: Annotated[str, Body(embed=True)]): return {"p": p} class BodyModelRequiredStr(BaseModel): p: str @app.post("/model-required-str", operation_id="model_required_str") async def read_model_required_str(p: BodyModelRequiredStr): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_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": {"title": "P", "type": "string"}, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_missing(path: str, json: Union[dict[str, Any], None]): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body"], ["body", "p"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.post("/required-alias", operation_id="required_alias") async def read_required_alias( p: Annotated[str, Body(embed=True, alias="p_alias")], ): return {"p": p} class BodyModelRequiredAlias(BaseModel): p: str = Field(alias="p_alias") @app.post("/model-required-alias", operation_id="model_required_alias") async def read_model_required_alias(p: BodyModelRequiredAlias): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_str_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": {"title": "P Alias", "type": "string"}, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_missing(path: str, json: Union[dict[str, Any], None]): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body", "p_alias"], ["body"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.post("/required-validation-alias", operation_id="required_validation_alias") def read_required_validation_alias( p: Annotated[str, Body(embed=True, validation_alias="p_val_alias")], ): return {"p": p} class BodyModelRequiredValidationAlias(BaseModel): p: str = Field(validation_alias="p_val_alias") @app.post( "/model-required-validation-alias", operation_id="model_required_validation_alias" ) def read_model_required_validation_alias( p: BodyModelRequiredValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-validation-alias", "/model-required-validation-alias"], ) def test_required_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": {"title": "P Val Alias", "type": "string"}, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_missing( path: str, json: Union[dict[str, Any], None] ): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body", "p_val_alias"], ["body"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.post( "/required-alias-and-validation-alias", operation_id="required_alias_and_validation_alias", ) def read_required_alias_and_validation_alias( p: Annotated[ str, Body(embed=True, alias="p_alias", validation_alias="p_val_alias") ], ): return {"p": p} class BodyModelRequiredAliasAndValidationAlias(BaseModel): p: str = Field(alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-required-alias-and-validation-alias", operation_id="model_required_alias_and_validation_alias", ) def read_model_required_alias_and_validation_alias( p: BodyModelRequiredAliasAndValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_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": {"title": "P Val Alias", "type": "string"}, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize("json", [None, {}]) @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing( path: str, json: Union[dict[str, Any], None] ): client = TestClient(app) response = client.post(path, json=json) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": IsOneOf(["body"], ["body", "p_val_alias"]), "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": "hello"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p_alias": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_body/test_optional_str.py
tests/test_request_params/test_body/test_optional_str.py
from typing import Annotated, Optional import pytest from fastapi import Body, FastAPI from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-str", operation_id="optional_str") async def read_optional_str(p: Annotated[Optional[str], Body(embed=True)] = None): return {"p": p} class BodyModelOptionalStr(BaseModel): p: Optional[str] = None @app.post("/model-optional-str", operation_id="model_optional_str") async def read_model_optional_str(p: BodyModelOptionalStr): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P", }, }, "title": body_model_name, "type": "object", } def test_optional_str_missing(): client = TestClient(app) response = client.post("/optional-str") assert response.status_code == 200, response.text assert response.json() == {"p": None} def test_model_optional_str_missing(): client = TestClient(app) response = client.post("/model-optional-str") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.post("/optional-alias", operation_id="optional_alias") async def read_optional_alias( p: Annotated[Optional[str], Body(embed=True, alias="p_alias")] = None, ): return {"p": p} class BodyModelOptionalAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias") @app.post("/model-optional-alias", operation_id="model_optional_alias") async def read_model_optional_alias(p: BodyModelOptionalAlias): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias", "/model-optional-alias", ], ) def test_optional_str_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_alias_missing(): client = TestClient(app) response = client.post("/optional-alias") assert response.status_code == 200 assert response.json() == {"p": None} def test_model_optional_alias_missing(): client = TestClient(app) response = client.post("/model-optional-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_model_optional_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.post("/optional-validation-alias", operation_id="optional_validation_alias") def read_optional_validation_alias( p: Annotated[ Optional[str], Body(embed=True, validation_alias="p_val_alias") ] = None, ): return {"p": p} class BodyModelOptionalValidationAlias(BaseModel): p: Optional[str] = Field(None, validation_alias="p_val_alias") @app.post( "/model-optional-validation-alias", operation_id="model_optional_validation_alias" ) def read_model_optional_validation_alias( p: BodyModelOptionalValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_validation_alias_missing(): client = TestClient(app) response = client.post("/optional-validation-alias") assert response.status_code == 200 assert response.json() == {"p": None} def test_model_optional_validation_alias_missing(): client = TestClient(app) response = client.post("/model-optional-validation-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_model_optional_validation_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.post( "/optional-alias-and-validation-alias", operation_id="optional_alias_and_validation_alias", ) def read_optional_alias_and_validation_alias( p: Annotated[ Optional[str], Body(embed=True, alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class BodyModelOptionalAliasAndValidationAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-optional-alias-and-validation-alias", operation_id="model_optional_alias_and_validation_alias", ) def read_model_optional_alias_and_validation_alias( p: BodyModelOptionalAliasAndValidationAlias, ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } def test_optional_alias_and_validation_alias_missing(): client = TestClient(app) response = client.post("/optional-alias-and-validation-alias") assert response.status_code == 200 assert response.json() == {"p": None} def test_model_optional_alias_and_validation_alias_missing(): client = TestClient(app) response = client.post("/model-optional-alias-and-validation-alias") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "input": None, "loc": ["body"], "msg": "Field required", "type": "missing", }, ], } @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_model_optional_alias_and_validation_alias_missing_empty_dict(path: str): client = TestClient(app) response = client.post(path, json={}) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, json={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_query/test_optional_list.py
tests/test_request_params/test_query/test_optional_list.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Query from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/optional-list-str") async def read_optional_list_str( p: Annotated[Optional[list[str]], Query()] = None, ): return {"p": p} class QueryModelOptionalListStr(BaseModel): p: Optional[list[str]] = None @app.get("/model-optional-list-str") async def read_model_optional_list_str( p: Annotated[QueryModelOptionalListStr, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P", }, "name": "p", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.get("/optional-list-alias") async def read_optional_list_alias( p: Annotated[Optional[list[str]], Query(alias="p_alias")] = None, ): return {"p": p} class QueryModelOptionalListAlias(BaseModel): p: Optional[list[str]] = Field(None, alias="p_alias") @app.get("/model-optional-list-alias") async def read_model_optional_list_alias( p: Annotated[QueryModelOptionalListAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Alias", }, "name": "p_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias", "/model-optional-list-alias", ], ) def test_optional_list_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello&p_alias=world") assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.get("/optional-list-validation-alias") def read_optional_list_validation_alias( p: Annotated[Optional[list[str]], Query(validation_alias="p_val_alias")] = None, ): return {"p": p} class QueryModelOptionalListValidationAlias(BaseModel): p: Optional[list[str]] = Field(None, validation_alias="p_val_alias") @app.get("/model-optional-list-validation-alias") def read_model_optional_list_validation_alias( p: Annotated[QueryModelOptionalListValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-validation-alias", "/model-optional-list-validation-alias", ], ) def test_optional_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello&p_val_alias=world") assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.get("/optional-list-alias-and-validation-alias") def read_optional_list_alias_and_validation_alias( p: Annotated[ Optional[list[str]], Query(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class QueryModelOptionalListAliasAndValidationAlias(BaseModel): p: Optional[list[str]] = Field( None, alias="p_alias", validation_alias="p_val_alias" ) @app.get("/model-optional-list-alias-and-validation-alias") def read_model_optional_list_alias_and_validation_alias( p: Annotated[QueryModelOptionalListAliasAndValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello&p_alias=world") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello&p_val_alias=world") assert response.status_code == 200, response.text assert response.json() == { "p": [ "hello", "world", ] }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_query/test_list.py
tests/test_request_params/test_query/test_list.py
from typing import Annotated import pytest from dirty_equals import IsOneOf from fastapi import FastAPI, Query from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/required-list-str") async def read_required_list_str(p: Annotated[list[str], Query()]): return {"p": p} class QueryModelRequiredListStr(BaseModel): p: list[str] @app.get("/model-required-list-str") def read_model_required_list_str(p: Annotated[QueryModelRequiredListStr, Query()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P", "type": "array", "items": {"type": "string"}, }, "name": "p", "in": "query", } ] @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.get("/required-list-alias") async def read_required_list_alias(p: Annotated[list[str], Query(alias="p_alias")]): return {"p": p} class QueryModelRequiredListAlias(BaseModel): p: list[str] = Field(alias="p_alias") @app.get("/model-required-list-alias") async def read_model_required_list_alias( p: Annotated[QueryModelRequiredListAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello&p_alias=world") assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.get("/required-list-validation-alias") def read_required_list_validation_alias( p: Annotated[list[str], Query(validation_alias="p_val_alias")], ): return {"p": p} class QueryModelRequiredListValidationAlias(BaseModel): p: list[str] = Field(validation_alias="p_val_alias") @app.get("/model-required-list-validation-alias") async def read_model_required_list_validation_alias( p: Annotated[QueryModelRequiredListValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_list_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Val Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello&p_val_alias=world") assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.get("/required-list-alias-and-validation-alias") def read_required_list_alias_and_validation_alias( p: Annotated[list[str], Query(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class QueryModelRequiredListAliasAndValidationAlias(BaseModel): p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias") @app.get("/model-required-list-alias-and-validation-alias") def read_model_required_list_alias_and_validation_alias( p: Annotated[QueryModelRequiredListAliasAndValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Val Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello&p=world") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, { "p": [ "hello", "world", ] }, ), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello&p_alias=world") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_val_alias"], "msg": "Field required", "input": IsOneOf( None, {"p_alias": ["hello", "world"]}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello&p_val_alias=world") assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_query/__init__.py
tests/test_request_params/test_query/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_query/test_required_str.py
tests/test_request_params/test_query/test_required_str.py
from typing import Annotated import pytest from dirty_equals import IsOneOf from fastapi import FastAPI, Query from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/required-str") async def read_required_str(p: str): return {"p": p} class QueryModelRequiredStr(BaseModel): p: str @app.get("/model-required-str") async def read_model_required_str(p: Annotated[QueryModelRequiredStr, Query()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P", "type": "string"}, "name": "p", "in": "query", } ] @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/required-alias") async def read_required_alias(p: Annotated[str, Query(alias="p_alias")]): return {"p": p} class QueryModelRequiredAlias(BaseModel): p: str = Field(alias="p_alias") @app.get("/model-required-alias") async def read_model_required_alias(p: Annotated[QueryModelRequiredAlias, Query()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Alias", "type": "string"}, "name": "p_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_alias"], "msg": "Field required", "input": IsOneOf( None, {"p": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello") assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/required-validation-alias") def read_required_validation_alias( p: Annotated[str, Query(validation_alias="p_val_alias")], ): return {"p": p} class QueryModelRequiredValidationAlias(BaseModel): p: str = Field(validation_alias="p_val_alias") @app.get("/model-required-validation-alias") def read_model_required_validation_alias( p: Annotated[QueryModelRequiredValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-validation-alias", "/model-required-validation-alias"], ) def test_required_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello") assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/required-alias-and-validation-alias") def read_required_alias_and_validation_alias( p: Annotated[str, Query(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class QueryModelRequiredAliasAndValidationAlias(BaseModel): p: str = Field(alias="p_alias", validation_alias="p_val_alias") @app.get("/model-required-alias-and-validation-alias") def read_model_required_alias_and_validation_alias( p: Annotated[QueryModelRequiredAliasAndValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "query", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, {"p": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello") assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["query", "p_val_alias"], "msg": "Field required", "input": IsOneOf( None, {"p_alias": "hello"}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello") assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_query/test_optional_str.py
tests/test_request_params/test_query/test_optional_str.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Query from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/optional-str") async def read_optional_str(p: Optional[str] = None): return {"p": p} class QueryModelOptionalStr(BaseModel): p: Optional[str] = None @app.get("/model-optional-str") async def read_model_optional_str(p: Annotated[QueryModelOptionalStr, Query()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P", }, "name": "p", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/optional-alias") async def read_optional_alias( p: Annotated[Optional[str], Query(alias="p_alias")] = None, ): return {"p": p} class QueryModelOptionalAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias") @app.get("/model-optional-alias") async def read_model_optional_alias(p: Annotated[QueryModelOptionalAlias, Query()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Alias", }, "name": "p_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias", "/model-optional-alias", ], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello") assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/optional-validation-alias") def read_optional_validation_alias( p: Annotated[Optional[str], Query(validation_alias="p_val_alias")] = None, ): return {"p": p} class QueryModelOptionalValidationAlias(BaseModel): p: Optional[str] = Field(None, validation_alias="p_val_alias") @app.get("/model-optional-validation-alias") def read_model_optional_validation_alias( p: Annotated[QueryModelOptionalValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello") assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/optional-alias-and-validation-alias") def read_optional_alias_and_validation_alias( p: Annotated[ Optional[str], Query(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class QueryModelOptionalAliasAndValidationAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias", validation_alias="p_val_alias") @app.get("/model-optional-alias-and-validation-alias") def read_model_optional_alias_and_validation_alias( p: Annotated[QueryModelOptionalAliasAndValidationAlias, Query()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "query", } ] @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(f"{path}?p=hello") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_alias=hello") assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(f"{path}?p_val_alias=hello") assert response.status_code == 200 assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/test_optional_list.py
tests/test_request_params/test_form/test_optional_list.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-list-str", operation_id="optional_list_str") async def read_optional_list_str( p: Annotated[Optional[list[str]], Form()] = None, ): return {"p": p} class FormModelOptionalListStr(BaseModel): p: Optional[list[str]] = None @app.post("/model-optional-list-str", operation_id="model_optional_list_str") async def read_model_optional_list_str(p: Annotated[FormModelOptionalListStr, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.post("/optional-list-alias", operation_id="optional_list_alias") async def read_optional_list_alias( p: Annotated[Optional[list[str]], Form(alias="p_alias")] = None, ): return {"p": p} class FormModelOptionalListAlias(BaseModel): p: Optional[list[str]] = Field(None, alias="p_alias") @app.post("/model-optional-list-alias", operation_id="model_optional_list_alias") async def read_model_optional_list_alias( p: Annotated[FormModelOptionalListAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias", "/model-optional-list-alias", ], ) def test_optional_list_str_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.post( "/optional-list-validation-alias", operation_id="optional_list_validation_alias" ) def read_optional_list_validation_alias( p: Annotated[Optional[list[str]], Form(validation_alias="p_val_alias")] = None, ): return {"p": p} class FormModelOptionalListValidationAlias(BaseModel): p: Optional[list[str]] = Field(None, validation_alias="p_val_alias") @app.post( "/model-optional-list-validation-alias", operation_id="model_optional_list_validation_alias", ) def read_model_optional_list_validation_alias( p: Annotated[FormModelOptionalListValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-validation-alias", "/model-optional-list-validation-alias", ], ) def test_optional_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.post( "/optional-list-alias-and-validation-alias", operation_id="optional_list_alias_and_validation_alias", ) def read_optional_list_alias_and_validation_alias( p: Annotated[ Optional[list[str]], Form(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class FormModelOptionalListAliasAndValidationAlias(BaseModel): p: Optional[list[str]] = Field( None, alias="p_alias", validation_alias="p_val_alias" ) @app.post( "/model-optional-list-alias-and-validation-alias", operation_id="model_optional_list_alias_and_validation_alias", ) def read_model_optional_list_alias_and_validation_alias( p: Annotated[FormModelOptionalListAliasAndValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == { "p": [ "hello", "world", ] }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/test_list.py
tests/test_request_params/test_form/test_list.py
from typing import Annotated import pytest from dirty_equals import IsOneOf, IsPartialDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/required-list-str", operation_id="required_list_str") async def read_required_list_str(p: Annotated[list[str], Form()]): return {"p": p} class FormModelRequiredListStr(BaseModel): p: list[str] @app.post("/model-required-list-str", operation_id="model_required_list_str") def read_model_required_list_str(p: Annotated[FormModelRequiredListStr, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_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": { "items": {"type": "string"}, "title": "P", "type": "array", }, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.post("/required-list-alias", operation_id="required_list_alias") async def read_required_list_alias(p: Annotated[list[str], Form(alias="p_alias")]): return {"p": p} class FormModelRequiredListAlias(BaseModel): p: list[str] = Field(alias="p_alias") @app.post("/model-required-list-alias", operation_id="model_required_list_alias") async def read_model_required_list_alias( p: Annotated[FormModelRequiredListAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_str_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": { "items": {"type": "string"}, "title": "P Alias", "type": "array", }, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.post( "/required-list-validation-alias", operation_id="required_list_validation_alias" ) def read_required_list_validation_alias( p: Annotated[list[str], Form(validation_alias="p_val_alias")], ): return {"p": p} class FormModelRequiredListValidationAlias(BaseModel): p: list[str] = Field(validation_alias="p_val_alias") @app.post( "/model-required-list-validation-alias", operation_id="model_required_list_validation_alias", ) async def read_model_required_list_validation_alias( p: Annotated[FormModelRequiredListValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_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": { "items": {"type": "string"}, "title": "P Val Alias", "type": "array", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})), } ] } @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.post( "/required-list-alias-and-validation-alias", operation_id="required_list_alias_and_validation_alias", ) def read_required_list_alias_and_validation_alias( p: Annotated[list[str], Form(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class FormModelRequiredListAliasAndValidationAlias(BaseModel): p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-required-list-alias-and-validation-alias", operation_id="model_required_list_alias_and_validation_alias", ) def read_model_required_list_alias_and_validation_alias( p: Annotated[FormModelRequiredListAliasAndValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_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": { "items": {"type": "string"}, "title": "P Val Alias", "type": "array", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, {"p": ["hello", "world"]}, ), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p_alias": ["hello", "world"]}), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": ["hello", "world"]}) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/utils.py
tests/test_request_params/test_form/utils.py
from typing import Any def get_body_model_name(openapi: dict[str, Any], path: str) -> str: body = openapi["paths"][path]["post"]["requestBody"] body_schema = body["content"]["application/x-www-form-urlencoded"]["schema"] return body_schema.get("$ref", "").split("/")[-1]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/__init__.py
tests/test_request_params/test_form/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/test_required_str.py
tests/test_request_params/test_form/test_required_str.py
from typing import Annotated import pytest from dirty_equals import IsOneOf from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/required-str", operation_id="required_str") async def read_required_str(p: Annotated[str, Form()]): return {"p": p} class FormModelRequiredStr(BaseModel): p: str @app.post("/model-required-str", operation_id="model_required_str") async def read_model_required_str(p: Annotated[FormModelRequiredStr, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_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": {"title": "P", "type": "string"}, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.post("/required-alias", operation_id="required_alias") async def read_required_alias(p: Annotated[str, Form(alias="p_alias")]): return {"p": p} class FormModelRequiredAlias(BaseModel): p: str = Field(alias="p_alias") @app.post("/model-required-alias", operation_id="model_required_alias") async def read_model_required_alias(p: Annotated[FormModelRequiredAlias, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_str_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": {"title": "P Alias", "type": "string"}, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.post("/required-validation-alias", operation_id="required_validation_alias") def read_required_validation_alias( p: Annotated[str, Form(validation_alias="p_val_alias")], ): return {"p": p} class FormModelRequiredValidationAlias(BaseModel): p: str = Field(validation_alias="p_val_alias") @app.post( "/model-required-validation-alias", operation_id="model_required_validation_alias" ) def read_model_required_validation_alias( p: Annotated[FormModelRequiredValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-validation-alias", "/model-required-validation-alias"], ) def test_required_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": {"title": "P Val Alias", "type": "string"}, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.post( "/required-alias-and-validation-alias", operation_id="required_alias_and_validation_alias", ) def read_required_alias_and_validation_alias( p: Annotated[str, Form(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class FormModelRequiredAliasAndValidationAlias(BaseModel): p: str = Field(alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-required-alias-and-validation-alias", operation_id="model_required_alias_and_validation_alias", ) def read_model_required_alias_and_validation_alias( p: Annotated[FormModelRequiredAliasAndValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_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": {"title": "P Val Alias", "type": "string"}, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": IsOneOf(None, {"p": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": "hello"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, {"p_alias": "hello"}), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_form/test_optional_str.py
tests/test_request_params/test_form/test_optional_str.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Form from fastapi.testclient import TestClient from pydantic import BaseModel, Field from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-str", operation_id="optional_str") async def read_optional_str(p: Annotated[Optional[str], Form()] = None): return {"p": p} class FormModelOptionalStr(BaseModel): p: Optional[str] = None @app.post("/model-optional-str", operation_id="model_optional_str") async def read_model_optional_str(p: Annotated[FormModelOptionalStr, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.post("/optional-alias", operation_id="optional_alias") async def read_optional_alias( p: Annotated[Optional[str], Form(alias="p_alias")] = None, ): return {"p": p} class FormModelOptionalAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias") @app.post("/model-optional-alias", operation_id="model_optional_alias") async def read_model_optional_alias(p: Annotated[FormModelOptionalAlias, Form()]): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias", "/model-optional-alias", ], ) def test_optional_str_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.post("/optional-validation-alias", operation_id="optional_validation_alias") def read_optional_validation_alias( p: Annotated[Optional[str], Form(validation_alias="p_val_alias")] = None, ): return {"p": p} class FormModelOptionalValidationAlias(BaseModel): p: Optional[str] = Field(None, validation_alias="p_val_alias") @app.post( "/model-optional-validation-alias", operation_id="model_optional_validation_alias" ) def read_model_optional_validation_alias( p: Annotated[FormModelOptionalValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.post( "/optional-alias-and-validation-alias", operation_id="optional_alias_and_validation_alias", ) def read_optional_alias_and_validation_alias( p: Annotated[ Optional[str], Form(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class FormModelOptionalAliasAndValidationAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias", validation_alias="p_val_alias") @app.post( "/model-optional-alias-and-validation-alias", operation_id="model_optional_alias_and_validation_alias", ) def read_model_optional_alias_and_validation_alias( p: Annotated[FormModelOptionalAliasAndValidationAlias, Form()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, data={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, data={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/test_optional_list.py
tests/test_request_params/test_file/test_optional_list.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, File, UploadFile from fastapi.testclient import TestClient from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-list-bytes") async def read_optional_list_bytes(p: Annotated[Optional[list[bytes]], File()] = None): return {"file_size": [len(file) for file in p] if p else None} @app.post("/optional-list-uploadfile") async def read_optional_list_uploadfile( p: Annotated[Optional[list[UploadFile]], File()] = None, ): return {"file_size": [file.size for file in p] if p else None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes", "/optional-list-uploadfile", ], ) def test_optional_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": { "anyOf": [ { "type": "array", "items": {"type": "string", "format": "binary"}, }, {"type": "null"}, ], "title": "P", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-list-bytes", "/optional-list-uploadfile", ], ) def test_optional_list_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes", "/optional-list-uploadfile", ], ) def test_optional_list(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 200 assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Alias @app.post("/optional-list-bytes-alias") async def read_optional_list_bytes_alias( p: Annotated[Optional[list[bytes]], File(alias="p_alias")] = None, ): return {"file_size": [len(file) for file in p] if p else None} @app.post("/optional-list-uploadfile-alias") async def read_optional_list_uploadfile_alias( p: Annotated[Optional[list[UploadFile]], File(alias="p_alias")] = None, ): return {"file_size": [file.size for file in p] if p else None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias", "/optional-list-uploadfile-alias", ], ) def test_optional_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": { "anyOf": [ { "type": "array", "items": {"type": "string", "format": "binary"}, }, {"type": "null"}, ], "title": "P Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias", "/optional-list-uploadfile-alias", ], ) def test_optional_list_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias", "/optional-list-uploadfile-alias", ], ) def test_optional_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias", "/optional-list-uploadfile-alias", ], ) def test_optional_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello"), ("p_alias", b"world")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Validation alias @app.post("/optional-list-bytes-validation-alias") def read_optional_list_bytes_validation_alias( p: Annotated[Optional[list[bytes]], File(validation_alias="p_val_alias")] = None, ): return {"file_size": [len(file) for file in p] if p else None} @app.post("/optional-list-uploadfile-validation-alias") def read_optional_list_uploadfile_validation_alias( p: Annotated[ Optional[list[UploadFile]], File(validation_alias="p_val_alias") ] = None, ): return {"file_size": [file.size for file in p] if p else None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-validation-alias", "/optional-list-uploadfile-validation-alias", ], ) def test_optional_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": { "anyOf": [ { "type": "array", "items": {"type": "string", "format": "binary"}, }, {"type": "null"}, ], "title": "P Val Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-list-bytes-validation-alias", "/optional-list-uploadfile-validation-alias", ], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-validation-alias", "/optional-list-uploadfile-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-validation-alias", "/optional-list-uploadfile-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post( path, files=[("p_val_alias", b"hello"), ("p_val_alias", b"world")] ) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Alias and validation alias @app.post("/optional-list-bytes-alias-and-validation-alias") def read_optional_list_bytes_alias_and_validation_alias( p: Annotated[ Optional[list[bytes]], File(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"file_size": [len(file) for file in p] if p else None} @app.post("/optional-list-uploadfile-alias-and-validation-alias") def read_optional_list_uploadfile_alias_and_validation_alias( p: Annotated[ Optional[list[UploadFile]], File(alias="p_alias", validation_alias="p_val_alias"), ] = None, ): return {"file_size": [file.size for file in p] if p else None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias-and-validation-alias", "/optional-list-uploadfile-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [ { "type": "array", "items": {"type": "string", "format": "binary"}, }, {"type": "null"}, ], "title": "P Val Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias-and-validation-alias", "/optional-list-uploadfile-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias-and-validation-alias", "/optional-list-uploadfile-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias-and-validation-alias", "/optional-list-uploadfile-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello"), ("p_alias", b"world")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-list-bytes-alias-and-validation-alias", "/optional-list-uploadfile-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post( path, files=[("p_val_alias", b"hello"), ("p_val_alias", b"world")] ) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/test_optional.py
tests/test_request_params/test_file/test_optional.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, File, UploadFile from fastapi.testclient import TestClient from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/optional-bytes", operation_id="optional_bytes") async def read_optional_bytes(p: Annotated[Optional[bytes], File()] = None): return {"file_size": len(p) if p else None} @app.post("/optional-uploadfile", operation_id="optional_uploadfile") async def read_optional_uploadfile(p: Annotated[Optional[UploadFile], File()] = None): return {"file_size": p.size if p else None} @pytest.mark.parametrize( "path", [ "/optional-bytes", "/optional-uploadfile", ], ) def test_optional_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": { "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], "title": "P", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-bytes", "/optional-uploadfile", ], ) def test_optional_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes", "/optional-uploadfile", ], ) def test_optional(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 200 assert response.json() == {"file_size": 5} # ===================================================================================== # Alias @app.post("/optional-bytes-alias", operation_id="optional_bytes_alias") async def read_optional_bytes_alias( p: Annotated[Optional[bytes], File(alias="p_alias")] = None, ): return {"file_size": len(p) if p else None} @app.post("/optional-uploadfile-alias", operation_id="optional_uploadfile_alias") async def read_optional_uploadfile_alias( p: Annotated[Optional[UploadFile], File(alias="p_alias")] = None, ): return {"file_size": p.size if p else None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias", "/optional-uploadfile-alias", ], ) def test_optional_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": { "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], "title": "P Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-bytes-alias", "/optional-uploadfile-alias", ], ) def test_optional_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias", "/optional-uploadfile-alias", ], ) def test_optional_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias", "/optional-uploadfile-alias", ], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5} # ===================================================================================== # Validation alias @app.post( "/optional-bytes-validation-alias", operation_id="optional_bytes_validation_alias" ) def read_optional_bytes_validation_alias( p: Annotated[Optional[bytes], File(validation_alias="p_val_alias")] = None, ): return {"file_size": len(p) if p else None} @app.post( "/optional-uploadfile-validation-alias", operation_id="optional_uploadfile_validation_alias", ) def read_optional_uploadfile_validation_alias( p: Annotated[Optional[UploadFile], File(validation_alias="p_val_alias")] = None, ): return {"file_size": p.size if p else None} @pytest.mark.parametrize( "path", [ "/optional-bytes-validation-alias", "/optional-uploadfile-validation-alias", ], ) def test_optional_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": { "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], "title": "P Val Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-bytes-validation-alias", "/optional-uploadfile-validation-alias", ], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-validation-alias", "/optional-uploadfile-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-validation-alias", "/optional-uploadfile-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_val_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5} # ===================================================================================== # Alias and validation alias @app.post( "/optional-bytes-alias-and-validation-alias", operation_id="optional_bytes_alias_and_validation_alias", ) def read_optional_bytes_alias_and_validation_alias( p: Annotated[ Optional[bytes], File(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"file_size": len(p) if p else None} @app.post( "/optional-uploadfile-alias-and-validation-alias", operation_id="optional_uploadfile_alias_and_validation_alias", ) def read_optional_uploadfile_alias_and_validation_alias( p: Annotated[ Optional[UploadFile], File(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"file_size": p.size if p else None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias-and-validation-alias", "/optional-uploadfile-alias-and-validation-alias", ], ) def test_optional_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": { "anyOf": [ {"type": "string", "format": "binary"}, {"type": "null"}, ], "title": "P Val Alias", } }, "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/optional-bytes-alias-and-validation-alias", "/optional-uploadfile-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias-and-validation-alias", "/optional-uploadfile-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias-and-validation-alias", "/optional-uploadfile-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": None} @pytest.mark.parametrize( "path", [ "/optional-bytes-alias-and-validation-alias", "/optional-uploadfile-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_val_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/test_required.py
tests/test_request_params/test_file/test_required.py
from typing import Annotated import pytest from fastapi import FastAPI, File, UploadFile from fastapi.testclient import TestClient from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/required-bytes", operation_id="required_bytes") async def read_required_bytes(p: Annotated[bytes, File()]): return {"file_size": len(p)} @app.post("/required-uploadfile", operation_id="required_uploadfile") async def read_required_uploadfile(p: Annotated[UploadFile, File()]): return {"file_size": p.size} @pytest.mark.parametrize( "path", [ "/required-bytes", "/required-uploadfile", ], ) def test_required_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": {"title": "P", "type": "string", "format": "binary"}, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-bytes", "/required-uploadfile", ], ) def test_required_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes", "/required-uploadfile", ], ) def test_required(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 200 assert response.json() == {"file_size": 5} # ===================================================================================== # Alias @app.post("/required-bytes-alias", operation_id="required_bytes_alias") async def read_required_bytes_alias(p: Annotated[bytes, File(alias="p_alias")]): return {"file_size": len(p)} @app.post("/required-uploadfile-alias", operation_id="required_uploadfile_alias") async def read_required_uploadfile_alias( p: Annotated[UploadFile, File(alias="p_alias")], ): return {"file_size": p.size} @pytest.mark.parametrize( "path", [ "/required-bytes-alias", "/required-uploadfile-alias", ], ) def test_required_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": {"title": "P Alias", "type": "string", "format": "binary"}, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-bytes-alias", "/required-uploadfile-alias", ], ) def test_required_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-alias", "/required-uploadfile-alias", ], ) def test_required_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-alias", "/required-uploadfile-alias", ], ) def test_required_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5} # ===================================================================================== # Validation alias @app.post( "/required-bytes-validation-alias", operation_id="required_bytes_validation_alias" ) def read_required_bytes_validation_alias( p: Annotated[bytes, File(validation_alias="p_val_alias")], ): return {"file_size": len(p)} @app.post( "/required-uploadfile-validation-alias", operation_id="required_uploadfile_validation_alias", ) def read_required_uploadfile_validation_alias( p: Annotated[UploadFile, File(validation_alias="p_val_alias")], ): return {"file_size": p.size} @pytest.mark.parametrize( "path", [ "/required-bytes-validation-alias", "/required-uploadfile-validation-alias", ], ) def test_required_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": { "title": "P Val Alias", "type": "string", "format": "binary", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-bytes-validation-alias", "/required-uploadfile-validation-alias", ], ) def test_required_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-validation-alias", "/required-uploadfile-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello")]) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-validation-alias", "/required-uploadfile-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_val_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5} # ===================================================================================== # Alias and validation alias @app.post( "/required-bytes-alias-and-validation-alias", operation_id="required_bytes_alias_and_validation_alias", ) def read_required_bytes_alias_and_validation_alias( p: Annotated[bytes, File(alias="p_alias", validation_alias="p_val_alias")], ): return {"file_size": len(p)} @app.post( "/required-uploadfile-alias-and-validation-alias", operation_id="required_uploadfile_alias_and_validation_alias", ) def read_required_uploadfile_alias_and_validation_alias( p: Annotated[UploadFile, File(alias="p_alias", validation_alias="p_val_alias")], ): return {"file_size": p.size} @pytest.mark.parametrize( "path", [ "/required-bytes-alias-and-validation-alias", "/required-uploadfile-alias-and-validation-alias", ], ) def test_required_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": { "title": "P Val Alias", "type": "string", "format": "binary", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/required-bytes-alias-and-validation-alias", "/required-uploadfile-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-alias-and-validation-alias", "/required-uploadfile-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-alias-and-validation-alias", "/required-uploadfile-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello")]) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/required-bytes-alias-and-validation-alias", "/required-uploadfile-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_val_alias", b"hello")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": 5}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/test_list.py
tests/test_request_params/test_file/test_list.py
from typing import Annotated import pytest from fastapi import FastAPI, File, UploadFile from fastapi.testclient import TestClient from .utils import get_body_model_name app = FastAPI() # ===================================================================================== # Without aliases @app.post("/list-bytes", operation_id="list_bytes") async def read_list_bytes(p: Annotated[list[bytes], File()]): return {"file_size": [len(file) for file in p]} @app.post("/list-uploadfile", operation_id="list_uploadfile") async def read_list_uploadfile(p: Annotated[list[UploadFile], File()]): return {"file_size": [file.size for file in p]} @pytest.mark.parametrize( "path", [ "/list-bytes", "/list-uploadfile", ], ) 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", "format": "binary"}, "title": "P", }, }, "required": ["p"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/list-bytes", "/list-uploadfile", ], ) def test_list_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes", "/list-uploadfile", ], ) def test_list(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 200 assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Alias @app.post("/list-bytes-alias", operation_id="list_bytes_alias") async def read_list_bytes_alias(p: Annotated[list[bytes], File(alias="p_alias")]): return {"file_size": [len(file) for file in p]} @app.post("/list-uploadfile-alias", operation_id="list_uploadfile_alias") async def read_list_uploadfile_alias( p: Annotated[list[UploadFile], File(alias="p_alias")], ): return {"file_size": [file.size for file in p]} @pytest.mark.parametrize( "path", [ "/list-bytes-alias", "/list-uploadfile-alias", ], ) 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", "format": "binary"}, "title": "P Alias", }, }, "required": ["p_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/list-bytes-alias", "/list-uploadfile-alias", ], ) def test_list_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-alias", "/list-uploadfile-alias", ], ) def test_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-alias", "/list-uploadfile-alias", ], ) def test_list_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello"), ("p_alias", b"world")]) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Validation alias @app.post("/list-bytes-validation-alias", operation_id="list_bytes_validation_alias") def read_list_bytes_validation_alias( p: Annotated[list[bytes], File(validation_alias="p_val_alias")], ): return {"file_size": [len(file) for file in p]} @app.post( "/list-uploadfile-validation-alias", operation_id="list_uploadfile_validation_alias", ) def read_list_uploadfile_validation_alias( p: Annotated[list[UploadFile], File(validation_alias="p_val_alias")], ): return {"file_size": [file.size for file in p]} @pytest.mark.parametrize( "path", [ "/list-bytes-validation-alias", "/list-uploadfile-validation-alias", ], ) 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", "format": "binary"}, "title": "P Val Alias", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/list-bytes-validation-alias", "/list-uploadfile-validation-alias", ], ) def test_list_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-validation-alias", "/list-uploadfile-validation-alias", ], ) def test_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", b"hello"), ("p", b"world")]) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-validation-alias", "/list-uploadfile-validation-alias", ], ) def test_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post( path, files=[("p_val_alias", b"hello"), ("p_val_alias", b"world")] ) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]} # ===================================================================================== # Alias and validation alias @app.post( "/list-bytes-alias-and-validation-alias", operation_id="list_bytes_alias_and_validation_alias", ) def read_list_bytes_alias_and_validation_alias( p: Annotated[list[bytes], File(alias="p_alias", validation_alias="p_val_alias")], ): return {"file_size": [len(file) for file in p]} @app.post( "/list-uploadfile-alias-and-validation-alias", operation_id="list_uploadfile_alias_and_validation_alias", ) def read_list_uploadfile_alias_and_validation_alias( p: Annotated[ list[UploadFile], File(alias="p_alias", validation_alias="p_val_alias") ], ): return {"file_size": [file.size for file in p]} @pytest.mark.parametrize( "path", [ "/list-bytes-alias-and-validation-alias", "/list-uploadfile-alias-and-validation-alias", ], ) 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", "format": "binary"}, "title": "P Val Alias", }, }, "required": ["p_val_alias"], "title": body_model_name, "type": "object", } @pytest.mark.parametrize( "path", [ "/list-bytes-alias-and-validation-alias", "/list-uploadfile-alias-and-validation-alias", ], ) def test_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-alias-and-validation-alias", "/list-uploadfile-alias-and-validation-alias", ], ) def test_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.post(path, files=[("p", "hello"), ("p", "world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_val_alias", ], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-alias-and-validation-alias", "/list-uploadfile-alias-and-validation-alias", ], ) def test_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.post(path, files=[("p_alias", b"hello"), ("p_alias", b"world")]) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_val_alias"], "msg": "Field required", "input": None, } ] } @pytest.mark.parametrize( "path", [ "/list-bytes-alias-and-validation-alias", "/list-uploadfile-alias-and-validation-alias", ], ) def test_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.post( path, files=[("p_val_alias", b"hello"), ("p_val_alias", b"world")] ) assert response.status_code == 200, response.text assert response.json() == {"file_size": [5, 5]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/utils.py
tests/test_request_params/test_file/utils.py
from typing import Any def get_body_model_name(openapi: dict[str, Any], path: str) -> str: body = openapi["paths"][path]["post"]["requestBody"] body_schema = body["content"]["multipart/form-data"]["schema"] return body_schema.get("$ref", "").split("/")[-1]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_file/__init__.py
tests/test_request_params/test_file/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_path/test_optional_list.py
tests/test_request_params/test_path/test_optional_list.py
# Optional Path parameters are not supported
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_path/test_list.py
tests/test_request_params/test_path/test_list.py
# FastAPI doesn't currently support non-scalar Path parameters
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_path/__init__.py
tests/test_request_params/test_path/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_path/test_required_str.py
tests/test_request_params/test_path/test_required_str.py
from typing import Annotated import pytest from fastapi import FastAPI, Path from fastapi.testclient import TestClient app = FastAPI() @app.get("/required-str/{p}") async def read_required_str(p: Annotated[str, Path()]): return {"p": p} @app.get("/required-alias/{p_alias}") async def read_required_alias(p: Annotated[str, Path(alias="p_alias")]): return {"p": p} @app.get("/required-validation-alias/{p_val_alias}") def read_required_validation_alias( p: Annotated[str, Path(validation_alias="p_val_alias")], ): return {"p": p} @app.get("/required-alias-and-validation-alias/{p_val_alias}") def read_required_alias_and_validation_alias( p: Annotated[str, Path(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} @pytest.mark.parametrize( ("path", "expected_name", "expected_title"), [ pytest.param("/required-str/{p}", "p", "P", id="required-str"), pytest.param( "/required-alias/{p_alias}", "p_alias", "P Alias", id="required-alias" ), pytest.param( "/required-validation-alias/{p_val_alias}", "p_val_alias", "P Val Alias", id="required-validation-alias", ), pytest.param( "/required-alias-and-validation-alias/{p_val_alias}", "p_val_alias", "P Val Alias", id="required-alias-and-validation-alias", ), ], ) def test_schema(path: str, expected_name: str, expected_title: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": expected_title, "type": "string"}, "name": expected_name, "in": "path", } ] @pytest.mark.parametrize( "path", [ pytest.param("/required-str", id="required-str"), pytest.param("/required-alias", id="required-alias"), pytest.param( "/required-validation-alias", id="required-validation-alias", ), pytest.param( "/required-alias-and-validation-alias", id="required-alias-and-validation-alias", ), ], ) def test_success(path: str): client = TestClient(app) response = client.get(f"{path}/hello") assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_path/test_optional_str.py
tests/test_request_params/test_path/test_optional_str.py
# Optional Path parameters are not supported
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_header/test_optional_list.py
tests/test_request_params/test_header/test_optional_list.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Header from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/optional-list-str") async def read_optional_list_str( p: Annotated[Optional[list[str]], Header()] = None, ): return {"p": p} class HeaderModelOptionalListStr(BaseModel): p: Optional[list[str]] = None @app.get("/model-optional-list-str") async def read_model_optional_list_str( p: Annotated[HeaderModelOptionalListStr, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P", }, "name": "p", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-str", "/model-optional-list-str"], ) def test_optional_list_str(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.get("/optional-list-alias") async def read_optional_list_alias( p: Annotated[Optional[list[str]], Header(alias="p_alias")] = None, ): return {"p": p} class HeaderModelOptionalListAlias(BaseModel): p: Optional[list[str]] = Field(None, alias="p_alias") @app.get("/model-optional-list-alias") async def read_model_optional_list_alias( p: Annotated[HeaderModelOptionalListAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Alias", }, "name": "p_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-alias", "/model-optional-list-alias"], ) def test_optional_list_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias", "/model-optional-list-alias", ], ) def test_optional_list_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers=[("p_alias", "hello"), ("p_alias", "world")]) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.get("/optional-list-validation-alias") def read_optional_list_validation_alias( p: Annotated[Optional[list[str]], Header(validation_alias="p_val_alias")] = None, ): return {"p": p} class HeaderModelOptionalListValidationAlias(BaseModel): p: Optional[list[str]] = Field(None, validation_alias="p_val_alias") @app.get("/model-optional-list-validation-alias") def read_model_optional_list_validation_alias( p: Annotated[HeaderModelOptionalListValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-validation-alias", "/model-optional-list-validation-alias", ], ) def test_optional_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-list-validation-alias", "/model-optional-list-validation-alias"], ) def test_optional_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get( path, headers=[("p_val_alias", "hello"), ("p_val_alias", "world")] ) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.get("/optional-list-alias-and-validation-alias") def read_optional_list_alias_and_validation_alias( p: Annotated[ Optional[list[str]], Header(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class HeaderModelOptionalListAliasAndValidationAlias(BaseModel): p: Optional[list[str]] = Field( None, alias="p_alias", validation_alias="p_val_alias" ) @app.get("/model-optional-list-alias-and-validation-alias") def read_model_optional_list_alias_and_validation_alias( p: Annotated[HeaderModelOptionalListAliasAndValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [ {"items": {"type": "string"}, "type": "array"}, {"type": "null"}, ], "title": "P Val Alias", }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers=[("p_alias", "hello"), ("p_alias", "world")]) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-list-alias-and-validation-alias", "/model-optional-list-alias-and-validation-alias", ], ) def test_optional_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get( path, headers=[("p_val_alias", "hello"), ("p_val_alias", "world")] ) assert response.status_code == 200, response.text assert response.json() == { "p": [ "hello", "world", ] }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_header/test_list.py
tests/test_request_params/test_header/test_list.py
from typing import Annotated import pytest from dirty_equals import AnyThing, IsOneOf, IsPartialDict from fastapi import FastAPI, Header from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/required-list-str") async def read_required_list_str(p: Annotated[list[str], Header()]): return {"p": p} class HeaderModelRequiredListStr(BaseModel): p: list[str] @app.get("/model-required-list-str") def read_model_required_list_str(p: Annotated[HeaderModelRequiredListStr, Header()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P", "type": "array", "items": {"type": "string"}, }, "name": "p", "in": "header", } ] @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p"], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", ["/required-list-str", "/model-required-list-str"], ) def test_required_list_str(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 200 assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias @app.get("/required-list-alias") async def read_required_list_alias(p: Annotated[list[str], Header(alias="p_alias")]): return {"p": p} class HeaderModelRequiredListAlias(BaseModel): p: list[str] = Field(alias="p_alias") @app.get("/model-required-list-alias") async def read_model_required_list_alias( p: Annotated[HeaderModelRequiredListAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/required-list-alias", "/model-required-list-alias"], ) def test_required_list_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_alias"], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias", "/model-required-list-alias", ], ) def test_required_list_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers=[("p_alias", "hello"), ("p_alias", "world")]) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Validation alias @app.get("/required-list-validation-alias") def read_required_list_validation_alias( p: Annotated[list[str], Header(validation_alias="p_val_alias")], ): return {"p": p} class HeaderModelRequiredListValidationAlias(BaseModel): p: list[str] = Field(validation_alias="p_val_alias") @app.get("/model-required-list-validation-alias") async def read_model_required_list_validation_alias( p: Annotated[HeaderModelRequiredListValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_list_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Val Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-list-validation-alias", "/model-required-list-validation-alias", ], ) def test_required_list_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": ["hello", "world"]})), } ] } @pytest.mark.parametrize( "path", ["/required-list-validation-alias", "/model-required-list-validation-alias"], ) def test_required_list_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get( path, headers=[("p_val_alias", "hello"), ("p_val_alias", "world")] ) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]} # ===================================================================================== # Alias and validation alias @app.get("/required-list-alias-and-validation-alias") def read_required_list_alias_and_validation_alias( p: Annotated[list[str], Header(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class HeaderModelRequiredListAliasAndValidationAlias(BaseModel): p: list[str] = Field(alias="p_alias", validation_alias="p_val_alias") @app.get("/model-required-list-alias-and-validation-alias") def read_model_required_list_alias_and_validation_alias( p: Annotated[HeaderModelRequiredListAliasAndValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": { "title": "P Val Alias", "type": "array", "items": {"type": "string"}, }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers=[("p", "hello"), ("p", "world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, IsPartialDict({"p": ["hello", "world"]}), ), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers=[("p_alias", "hello"), ("p_alias", "world")]) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_val_alias"], "msg": "Field required", "input": IsOneOf( None, IsPartialDict({"p_alias": ["hello", "world"]}), ), } ] } @pytest.mark.parametrize( "path", [ "/required-list-alias-and-validation-alias", "/model-required-list-alias-and-validation-alias", ], ) def test_required_list_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get( path, headers=[("p_val_alias", "hello"), ("p_val_alias", "world")] ) assert response.status_code == 200, response.text assert response.json() == {"p": ["hello", "world"]}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_header/__init__.py
tests/test_request_params/test_header/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_header/test_required_str.py
tests/test_request_params/test_header/test_required_str.py
from typing import Annotated import pytest from dirty_equals import AnyThing, IsOneOf, IsPartialDict from fastapi import FastAPI, Header from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/required-str") async def read_required_str(p: Annotated[str, Header()]): return {"p": p} class HeaderModelRequiredStr(BaseModel): p: str @app.get("/model-required-str") async def read_model_required_str(p: Annotated[HeaderModelRequiredStr, Header()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P", "type": "string"}, "name": "p", "in": "header", } ] @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p"], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", ["/required-str", "/model-required-str"], ) def test_required_str(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/required-alias") async def read_required_alias(p: Annotated[str, Header(alias="p_alias")]): return {"p": p} class HeaderModelRequiredAlias(BaseModel): p: str = Field(alias="p_alias") @app.get("/model-required-alias") async def read_model_required_alias(p: Annotated[HeaderModelRequiredAlias, Header()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Alias", "type": "string"}, "name": "p_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/required-alias", "/model-required-alias"], ) def test_required_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_alias"], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": "hello"})), } ] } @pytest.mark.parametrize( "path", [ "/required-alias", "/model-required-alias", ], ) def test_required_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/required-validation-alias") def read_required_validation_alias( p: Annotated[str, Header(validation_alias="p_val_alias")], ): return {"p": p} class HeaderModelRequiredValidationAlias(BaseModel): p: str = Field(validation_alias="p_val_alias") @app.get("/model-required-validation-alias") def read_model_required_validation_alias( p: Annotated[HeaderModelRequiredValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/required-validation-alias", "/model-required-validation-alias"], ) def test_required_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_val_alias"], "msg": "Field required", "input": IsOneOf(None, IsPartialDict({"p": "hello"})), } ] } @pytest.mark.parametrize( "path", [ "/required-validation-alias", "/model-required-validation-alias", ], ) def test_required_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/required-alias-and-validation-alias") def read_required_alias_and_validation_alias( p: Annotated[str, Header(alias="p_alias", validation_alias="p_val_alias")], ): return {"p": p} class HeaderModelRequiredAliasAndValidationAlias(BaseModel): p: str = Field(alias="p_alias", validation_alias="p_val_alias") @app.get("/model-required-alias-and-validation-alias") def read_model_required_alias_and_validation_alias( p: Annotated[HeaderModelRequiredAliasAndValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": True, "schema": {"title": "P Val Alias", "type": "string"}, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": AnyThing, } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "header", "p_val_alias", ], "msg": "Field required", "input": IsOneOf( None, IsPartialDict({"p": "hello"}), ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_alias": "hello"}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["header", "p_val_alias"], "msg": "Field required", "input": IsOneOf( None, IsPartialDict({"p_alias": "hello"}), ), } ] } @pytest.mark.parametrize( "path", [ "/required-alias-and-validation-alias", "/model-required-alias-and-validation-alias", ], ) def test_required_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_val_alias": "hello"}) assert response.status_code == 200, response.text assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_request_params/test_header/test_optional_str.py
tests/test_request_params/test_header/test_optional_str.py
from typing import Annotated, Optional import pytest from fastapi import FastAPI, Header from fastapi.testclient import TestClient from pydantic import BaseModel, Field app = FastAPI() # ===================================================================================== # Without aliases @app.get("/optional-str") async def read_optional_str(p: Annotated[Optional[str], Header()] = None): return {"p": p} class HeaderModelOptionalStr(BaseModel): p: Optional[str] = None @app.get("/model-optional-str") async def read_model_optional_str(p: Annotated[HeaderModelOptionalStr, Header()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P", }, "name": "p", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-str", "/model-optional-str"], ) def test_optional_str(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias @app.get("/optional-alias") async def read_optional_alias( p: Annotated[Optional[str], Header(alias="p_alias")] = None, ): return {"p": p} class HeaderModelOptionalAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias") @app.get("/model-optional-alias") async def read_model_optional_alias(p: Annotated[HeaderModelOptionalAlias, Header()]): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_str_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Alias", }, "name": "p_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", ["/optional-alias", "/model-optional-alias"], ) def test_optional_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias", "/model-optional-alias", ], ) def test_optional_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Validation alias @app.get("/optional-validation-alias") def read_optional_validation_alias( p: Annotated[Optional[str], Header(validation_alias="p_val_alias")] = None, ): return {"p": p} class HeaderModelOptionalValidationAlias(BaseModel): p: Optional[str] = Field(None, validation_alias="p_val_alias") @app.get("/model-optional-validation-alias") def read_model_optional_validation_alias( p: Annotated[HeaderModelOptionalValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", ["/optional-validation-alias", "/model-optional-validation-alias"], ) def test_optional_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-validation-alias", "/model-optional-validation-alias", ], ) def test_optional_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"} # ===================================================================================== # Alias and validation alias @app.get("/optional-alias-and-validation-alias") def read_optional_alias_and_validation_alias( p: Annotated[ Optional[str], Header(alias="p_alias", validation_alias="p_val_alias") ] = None, ): return {"p": p} class HeaderModelOptionalAliasAndValidationAlias(BaseModel): p: Optional[str] = Field(None, alias="p_alias", validation_alias="p_val_alias") @app.get("/model-optional-alias-and-validation-alias") def read_model_optional_alias_and_validation_alias( p: Annotated[HeaderModelOptionalAliasAndValidationAlias, Header()], ): return {"p": p.p} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_schema(path: str): assert app.openapi()["paths"][path]["get"]["parameters"] == [ { "required": False, "schema": { "anyOf": [{"type": "string"}, {"type": "null"}], "title": "P Val Alias", }, "name": "p_val_alias", "in": "header", } ] @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_missing(path: str): client = TestClient(app) response = client.get(path) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_name(path: str): client = TestClient(app) response = client.get(path, headers={"p": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": None} @pytest.mark.parametrize( "path", [ "/optional-alias-and-validation-alias", "/model-optional-alias-and-validation-alias", ], ) def test_optional_alias_and_validation_alias_by_validation_alias(path: str): client = TestClient(app) response = client.get(path, headers={"p_val_alias": "hello"}) assert response.status_code == 200 assert response.json() == {"p": "hello"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/test_main.py
tests/test_modules_same_name_body/test_main.py
import pytest from fastapi.testclient import TestClient from .app.main import app client = TestClient(app) @pytest.mark.parametrize( "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] ) def test_post(path): data = {"a": 2, "b": "foo"} response = client.post(path, json=data) assert response.status_code == 200, response.text assert data == response.json() @pytest.mark.parametrize( "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] ) def test_post_invalid(path): data = {"a": "bar", "b": "foo"} response = client.post(path, json=data) assert response.status_code == 422, response.text def test_openapi_schema(): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/a/compute": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Compute", "operationId": "compute_a_compute_post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_compute_a_compute_post" } } }, "required": True, }, } }, "/b/compute/": { "post": { "responses": { "200": { "description": "Successful Response", "content": {"application/json": {"schema": {}}}, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "summary": "Compute", "operationId": "compute_b_compute__post", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_compute_b_compute__post" } } }, "required": True, }, } }, }, "components": { "schemas": { "Body_compute_b_compute__post": { "title": "Body_compute_b_compute__post", "required": ["a", "b"], "type": "object", "properties": { "a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "string"}, }, }, "Body_compute_a_compute_post": { "title": "Body_compute_a_compute_post", "required": ["a", "b"], "type": "object", "properties": { "a": {"title": "A", "type": "integer"}, "b": {"title": "B", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, } }, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/__init__.py
tests/test_modules_same_name_body/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/app/b.py
tests/test_modules_same_name_body/app/b.py
from fastapi import APIRouter, Body router = APIRouter() @router.post("/compute/") def compute(a: int = Body(), b: str = Body()): return {"a": a, "b": b}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/app/a.py
tests/test_modules_same_name_body/app/a.py
from fastapi import APIRouter, Body router = APIRouter() @router.post("/compute") def compute(a: int = Body(), b: str = Body()): return {"a": a, "b": b}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/app/main.py
tests/test_modules_same_name_body/app/main.py
from fastapi import FastAPI from . import a, b app = FastAPI() app.include_router(a.router, prefix="/a") app.include_router(b.router, prefix="/b")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_modules_same_name_body/app/__init__.py
tests/test_modules_same_name_body/app/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validate_response_recursive/test_validate_response_recursive.py
tests/test_validate_response_recursive/test_validate_response_recursive.py
from fastapi.testclient import TestClient from .app import app def test_recursive(): client = TestClient(app) response = client.get("/items/recursive") assert response.status_code == 200, response.text assert response.json() == { "sub_items": [{"name": "subitem", "sub_items": []}], "name": "item", } response = client.get("/items/recursive-submodel") assert response.status_code == 200, response.text assert response.json() == { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validate_response_recursive/__init__.py
tests/test_validate_response_recursive/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/tests/test_validate_response_recursive/app.py
tests/test_validate_response_recursive/app.py
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class RecursiveItem(BaseModel): sub_items: list["RecursiveItem"] = [] name: str class RecursiveSubitemInSubmodel(BaseModel): sub_items2: list["RecursiveItemViaSubmodel"] = [] name: str class RecursiveItemViaSubmodel(BaseModel): sub_items1: list[RecursiveSubitemInSubmodel] = [] name: str RecursiveItem.model_rebuild() RecursiveSubitemInSubmodel.model_rebuild() RecursiveItemViaSubmodel.model_rebuild() @app.get("/items/recursive", response_model=RecursiveItem) def get_recursive(): return {"name": "item", "sub_items": [{"name": "subitem", "sub_items": []}]} @app.get("/items/recursive-submodel", response_model=RecursiveItemViaSubmodel) def get_recursive_submodel(): return { "name": "item", "sub_items1": [ { "name": "subitem", "sub_items2": [ { "name": "subsubitem", "sub_items1": [{"name": "subsubsubitem", "sub_items2": []}], } ], } ], }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/params.py
fastapi/params.py
import warnings from collections.abc import Sequence from dataclasses import dataclass from enum import Enum from typing import Annotated, Any, Callable, Optional, Union from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.openapi.models import Example from pydantic import AliasChoices, AliasPath from pydantic.fields import FieldInfo from typing_extensions import Literal, deprecated from ._compat import ( Undefined, ) _Unset: Any = Undefined class ParamTypes(Enum): query = "query" header = "header" path = "path" cookie = "cookie" class Param(FieldInfo): # type: ignore[misc] in_: ParamTypes def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", category=FastAPIDeprecationWarning, stacklevel=4, ) self.example = example self.include_in_schema = include_in_schema self.openapi_examples = openapi_examples kwargs = dict( default=default, default_factory=default_factory, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, ) if examples is not None: kwargs["examples"] = examples if regex is not None: warnings.warn( "`regex` has been deprecated, please use `pattern` instead", category=FastAPIDeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra kwargs["deprecated"] = deprecated if serialization_alias in (_Unset, None) and isinstance(alias, str): serialization_alias = alias if validation_alias in (_Unset, None): validation_alias = alias kwargs.update( { "annotation": annotation, "alias_priority": alias_priority, "validation_alias": validation_alias, "serialization_alias": serialization_alias, "strict": strict, "json_schema_extra": current_json_schema_extra, } ) kwargs["pattern"] = pattern or regex use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} super().__init__(**use_kwargs) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})" class Path(Param): # type: ignore[misc] in_ = ParamTypes.path def __init__( self, default: Any = ..., *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): assert default is ..., "Path parameters cannot have a default value" self.in_ = self.in_ super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) class Query(Param): # type: ignore[misc] in_ = ParamTypes.query def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) class Header(Param): # type: ignore[misc] in_ = ParamTypes.header def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, convert_underscores: bool = True, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): self.convert_underscores = convert_underscores super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) class Cookie(Param): # type: ignore[misc] in_ = ParamTypes.cookie def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) class Body(FieldInfo): # type: ignore[misc] def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", category=FastAPIDeprecationWarning, stacklevel=4, ) self.example = example self.include_in_schema = include_in_schema self.openapi_examples = openapi_examples kwargs = dict( default=default, default_factory=default_factory, alias=alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, ) if examples is not None: kwargs["examples"] = examples if regex is not None: warnings.warn( "`regex` has been deprecated, please use `pattern` instead", category=FastAPIDeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra kwargs["deprecated"] = deprecated if serialization_alias in (_Unset, None) and isinstance(alias, str): serialization_alias = alias if validation_alias in (_Unset, None): validation_alias = alias kwargs.update( { "annotation": annotation, "alias_priority": alias_priority, "validation_alias": validation_alias, "serialization_alias": serialization_alias, "strict": strict, "json_schema_extra": current_json_schema_extra, } ) kwargs["pattern"] = pattern or regex use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset} super().__init__(**use_kwargs) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.default})" class Form(Body): # type: ignore[misc] def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, media_type: str = "application/x-www-form-urlencoded", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) class File(Form): # type: ignore[misc] def __init__( self, default: Any = Undefined, *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, media_type: str = "multipart/form-data", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, validation_alias: Union[str, AliasPath, AliasChoices, None] = None, serialization_alias: Union[str, None] = None, title: Optional[str] = None, description: Optional[str] = None, gt: Optional[float] = None, ge: Optional[float] = None, lt: Optional[float] = None, le: Optional[float] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, pattern: Optional[str] = None, regex: Annotated[ Optional[str], deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Union[str, None] = None, strict: Union[bool, None] = _Unset, multiple_of: Union[float, None] = _Unset, allow_inf_nan: Union[bool, None] = _Unset, max_digits: Union[int, None] = _Unset, decimal_places: Union[int, None] = _Unset, examples: Optional[list[Any]] = None, example: Annotated[ Optional[Any], deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Optional[dict[str, Example]] = None, deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[dict[str, Any], None] = None, **extra: Any, ): super().__init__( default=default, default_factory=default_factory, annotation=annotation, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, deprecated=deprecated, example=example, examples=examples, openapi_examples=openapi_examples, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) @dataclass(frozen=True) class Depends: dependency: Optional[Callable[..., Any]] = None use_cache: bool = True scope: Union[Literal["function", "request"], None] = None @dataclass(frozen=True) class Security(Depends): scopes: Optional[Sequence[str]] = None
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/staticfiles.py
fastapi/staticfiles.py
from starlette.staticfiles import StaticFiles as StaticFiles # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/cli.py
fastapi/cli.py
try: from fastapi_cli.cli import main as cli_main except ImportError: # pragma: no cover cli_main = None # type: ignore def main() -> None: if not cli_main: # type: ignore[truthy-function] message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' print(message) raise RuntimeError(message) # noqa: B904 cli_main()
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/exception_handlers.py
fastapi/exception_handlers.py
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import is_body_allowed_for_status_code from fastapi.websockets import WebSocket from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.status import WS_1008_POLICY_VIOLATION async def http_exception_handler(request: Request, exc: HTTPException) -> Response: headers = getattr(exc, "headers", None) if not is_body_allowed_for_status_code(exc.status_code): return Response(status_code=exc.status_code, headers=headers) return JSONResponse( {"detail": exc.detail}, status_code=exc.status_code, headers=headers ) async def request_validation_exception_handler( request: Request, exc: RequestValidationError ) -> JSONResponse: return JSONResponse( status_code=422, content={"detail": jsonable_encoder(exc.errors())}, ) async def websocket_request_validation_exception_handler( websocket: WebSocket, exc: WebSocketRequestValidationError ) -> None: await websocket.close( code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors()) )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/requests.py
fastapi/requests.py
from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401 from starlette.requests import Request as Request # noqa: F401
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/datastructures.py
fastapi/datastructures.py
from collections.abc import Mapping from typing import ( Annotated, Any, BinaryIO, Callable, Optional, TypeVar, cast, ) from annotated_doc import Doc from pydantic import GetJsonSchemaHandler from starlette.datastructures import URL as URL # noqa: F401 from starlette.datastructures import Address as Address # noqa: F401 from starlette.datastructures import FormData as FormData # noqa: F401 from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile class UploadFile(StarletteUploadFile): """ A file uploaded in a request. Define it as a *path operation function* (or dependency) parameter. If you are using a regular `def` function, you can use the `upload_file.file` attribute to access the raw standard Python file (blocking, not async), useful and needed for non-async code. Read more about it in the [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). ## Example ```python from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename} ``` """ file: Annotated[ BinaryIO, Doc("The standard Python file object (non-async)."), ] filename: Annotated[Optional[str], Doc("The original file name.")] size: Annotated[Optional[int], Doc("The size of the file in bytes.")] headers: Annotated[Headers, Doc("The headers of the request.")] content_type: Annotated[ Optional[str], Doc("The content type of the request, from the headers.") ] async def write( self, data: Annotated[ bytes, Doc( """ The bytes to write to the file. """ ), ], ) -> None: """ Write some bytes to the file. You normally wouldn't use this from a file you read in a request. To be awaitable, compatible with async, this is run in threadpool. """ return await super().write(data) async def read( self, size: Annotated[ int, Doc( """ The number of bytes to read from the file. """ ), ] = -1, ) -> bytes: """ Read some bytes from the file. To be awaitable, compatible with async, this is run in threadpool. """ return await super().read(size) async def seek( self, offset: Annotated[ int, Doc( """ The position in bytes to seek to in the file. """ ), ], ) -> None: """ Move to a position in the file. Any next read or write will be done from that position. To be awaitable, compatible with async, this is run in threadpool. """ return await super().seek(offset) async def close(self) -> None: """ Close the file. To be awaitable, compatible with async, this is run in threadpool. """ return await super().close() @classmethod def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": if not isinstance(__input_value, StarletteUploadFile): raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") return cast(UploadFile, __input_value) @classmethod def __get_pydantic_json_schema__( cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler ) -> dict[str, Any]: return {"type": "string", "format": "binary"} @classmethod def __get_pydantic_core_schema__( cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] ) -> Mapping[str, Any]: from ._compat.v2 import with_info_plain_validator_function return with_info_plain_validator_function(cls._validate) class DefaultPlaceholder: """ You shouldn't use this class directly. It's used internally to recognize when a default value has been overwritten, even if the overridden default value was truthy. """ def __init__(self, value: Any): self.value = value def __bool__(self) -> bool: return bool(self.value) def __eq__(self, o: object) -> bool: return isinstance(o, DefaultPlaceholder) and o.value == self.value DefaultType = TypeVar("DefaultType") def Default(value: DefaultType) -> DefaultType: """ You shouldn't use this function directly. It's used internally to recognize when a default value has been overwritten, even if the overridden default value was truthy. """ return DefaultPlaceholder(value) # type: ignore
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/exceptions.py
fastapi/exceptions.py
from collections.abc import Sequence from typing import Annotated, Any, Optional, TypedDict, Union from annotated_doc import Doc from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException class EndpointContext(TypedDict, total=False): function: str path: str file: str line: int class HTTPException(StarletteHTTPException): """ An HTTP exception you can raise in your own code to show errors to the client. This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). ## Example ```python from fastapi import FastAPI, HTTPException app = FastAPI() items = {"foo": "The Foo Wrestlers"} @app.get("/items/{item_id}") async def read_item(item_id: str): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return {"item": items[item_id]} ``` """ def __init__( self, status_code: Annotated[ int, Doc( """ HTTP status code to send to the client. """ ), ], detail: Annotated[ Any, Doc( """ Any data to be sent to the client in the `detail` key of the JSON response. """ ), ] = None, headers: Annotated[ Optional[dict[str, str]], Doc( """ Any headers to send to the client in the response. """ ), ] = None, ) -> None: super().__init__(status_code=status_code, detail=detail, headers=headers) class WebSocketException(StarletteWebSocketException): """ A WebSocket exception you can raise in your own code to show errors to the client. This is for client errors, invalid authentication, invalid data, etc. Not for server errors in your code. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). ## Example ```python from typing import Annotated from fastapi import ( Cookie, FastAPI, WebSocket, WebSocketException, status, ) app = FastAPI() @app.websocket("/items/{item_id}/ws") async def websocket_endpoint( *, websocket: WebSocket, session: Annotated[str | None, Cookie()] = None, item_id: str, ): if session is None: raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Session cookie is: {session}") await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") ``` """ def __init__( self, code: Annotated[ int, Doc( """ A closing code from the [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). """ ), ], reason: Annotated[ Union[str, None], Doc( """ The reason to close the WebSocket connection. It is UTF-8-encoded data. The interpretation of the reason is up to the application, it is not specified by the WebSocket specification. It could contain text that could be human-readable or interpretable by the client code, etc. """ ), ] = None, ) -> None: super().__init__(code=code, reason=reason) RequestErrorModel: type[BaseModel] = create_model("Request") WebSocketErrorModel: type[BaseModel] = create_model("WebSocket") class FastAPIError(RuntimeError): """ A generic, FastAPI-specific error. """ class DependencyScopeError(FastAPIError): """ A dependency declared that it depends on another dependency with an invalid (narrower) scope. """ class ValidationException(Exception): def __init__( self, errors: Sequence[Any], *, endpoint_ctx: Optional[EndpointContext] = None, ) -> None: self._errors = errors self.endpoint_ctx = endpoint_ctx ctx = endpoint_ctx or {} self.endpoint_function = ctx.get("function") self.endpoint_path = ctx.get("path") self.endpoint_file = ctx.get("file") self.endpoint_line = ctx.get("line") def errors(self) -> Sequence[Any]: return self._errors def _format_endpoint_context(self) -> str: if not (self.endpoint_file and self.endpoint_line and self.endpoint_function): if self.endpoint_path: return f"\n Endpoint: {self.endpoint_path}" return "" context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}' if self.endpoint_path: context += f"\n {self.endpoint_path}" return context def __str__(self) -> str: message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n" for err in self._errors: message += f" {err}\n" message += self._format_endpoint_context() return message.rstrip() class RequestValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, body: Any = None, endpoint_ctx: Optional[EndpointContext] = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) self.body = body class WebSocketRequestValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, endpoint_ctx: Optional[EndpointContext] = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) class ResponseValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, body: Any = None, endpoint_ctx: Optional[EndpointContext] = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) self.body = body class PydanticV1NotSupportedError(FastAPIError): """ A pydantic.v1 model is used, which is no longer supported. """ class FastAPIDeprecationWarning(UserWarning): """ A custom deprecation warning as DeprecationWarning is ignored Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries """
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/logger.py
fastapi/logger.py
import logging logger = logging.getLogger("fastapi")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false