Python Backend & APIs
20 lessons from merged PRs in FastAPI, Pydantic and Flask, summarized in our own words. The classic Python typing, serialization and ASGI traps.
brain_seed_starter(instance_id="<your-brain-id>", stack="python")20 fixes from merged PRs
Every lesson below is a short summary in our own words and links to its upstream GitHub pull request in a permissive-licensed repository. Seed them into your Brain so your coding agent can find them when a similar problem comes up.
- Symptom
Type checkers complain about the endpoint argument of FastAPI.add_api_route because its annotation differs from the one used by related routing calls.
Cause and fixCause: The endpoint parameter in FastAPI.add_api_route had a narrower type than the downstream APIRouter.add_api_route, get_typed_return_annotation and Starlette's Route, which accept Callable[..., Any]. Fix: The endpoint parameter annotation in applications.py was changed to Callable[..., Any] to match those downstream calls.
- Symptom
Including an APIRouter that uses a custom route_class into another router loses that class, so the parent router's class is applied to the included routes.
Cause and fixCause: include_router rebuilt every included route with the parent router's route_class instead of retaining each route's own class. Fix: include_router in routing.py now keeps the existing class of routes that are APIRoute subclasses when copying them into the parent router; a custom route class test covers it.
- Symptom
FastAPI's generated OpenAPI 422 response ignores a custom response_class media type and overwrites a customized validation-error format with the default one.
Cause and fixCause: The OpenAPI generator always inserted a hard-coded default 422 definition and did not take the media type from the route's response class for additional responses. Fix: openapi/utils.py now uses a user-supplied 422 response definition when one exists and falls back to the default only otherwise, and it takes the media type of response_class for additional responses.
- Symptom
Calling model_copy(deep=True, update={...}) in Pydantic wastes time and can crash on fields that cannot be deep-copied, even though update replaces those fields anyway.
Cause and fixCause: The implementation deep-copied the whole model first and applied the update dict afterwards, so fields about to be overwritten were copied and then thrown away. Fix: Fields present in update are no longer deep-copied; the remaining fields are copied with one shared memo dict to keep shared references, and extra and private state are handled as before.
- Symptom
Using a RootModel[Literal[...]] as a discriminator field in a Pydantic discriminated union raises PydanticUserError saying the field must be of type Literal.
Cause and fixCause: Discriminator value inference did not look inside a root model, so a model schema flagged as root_model was not recognized as a Literal. Fix: _infer_discriminator_values_for_inner_schema now handles a 'model' schema with the root_model flag by unwrapping it to the inner Literal schema, with tests for single and multiple values.
- Symptom
mypy reports errors when a class built with pydantic's create_model() is used in a type annotation, isinstance check or function parameter, forcing type: ignore comments.
Cause and fixCause: The pydantic mypy plugin had no handling for dynamically created classes, so variables assigned from create_model() were not treated as class types. Fix: A get_dynamic_class_hook was added to the mypy plugin so create_model() results become proper class types, including inheriting from the class given in the __base__ keyword.
- Symptom
Pydantic JSON schema generation emits duplicate definitions such as Schema-Input and Schema-Output for deeply nested models whose input and output schemas are identical.
Cause and fixCause: In _DefinitionsRemapping.from_prioritized_choices the json_remapping dict mapped only the original key to the final key, not the intermediate simplified names, so identical schemas were not merged. Fix: The remapping now also records the intermediate simplified names, letting identical input and output schemas collapse into one definition.
- Symptom
A Pydantic dataclass decorated with kw_only=True shows a wrong constructor signature when a field uses Field(kw_only=False), although positional passing still works.
Cause and fixCause: The dataclass conversion did not let a per-field Field(kw_only=False) override the class-level kw_only setting when building the signature. Fix: The dataclass handling was updated so Field(kw_only=...) on a single field overrides the decorator's kw_only parameter, with unit tests confirming the resulting signature.
- Symptom
Pydantic generates a JSON schema whose default list changes order between runs when a field default is a set or frozenset, breaking reproducible builds.
Cause and fixCause: Python hash randomization makes set iteration order vary between processes, and the values were encoded into the schema in that order. Fix: GenerateJsonSchema.default_schema now sorts set and frozenset values before encoding them, so the default list is stable across runs.
- Symptom
Pyright reports no matching overload when passing Pydantic's own Annotated aliases like NewPath or FilePath to validate_as in the experimental pipeline, although it works at runtime.
Cause and fixCause: The validate_as overloads only accepted type[T] or an ellipsis, while these aliases are _AnnotatedAlias objects that do not match type[T]. Fix: An overload taking Any was added as a last fallback, after type[_NewOutT] and EllipsisType, returning _Pipeline[_InT, Any] for Annotated aliases and similar type expressions.
- Symptom
In Pydantic's experimental pipeline, an annotated_types.Interval with a bound of 0 is silently ignored, so Interval(ge=0, le=10) accepts -5.
Cause and fixCause: _apply_constraint in pipeline.py tested each Interval bound for truthiness, and 0 is falsy, so zero bounds were skipped. Fix: The four checks for ge, gt, le and lt now use 'is not None', and test_interval_constraints gained cases with a zero bound for each.
- Symptom
Calling model_rebuild on a Pydantic subclass whose parent has an unresolved forward reference to it does nothing, because the subclass is wrongly treated as already complete.
Cause and fixCause: ModelMetaclass.__new__ marked a subclass as complete without verifying that its fields were resolved, unlike model_rebuild, so subclasses of incomplete parents got flagged complete. Fix: The metaclass now performs the same field-completeness check, rebuilding fields to look for unresolved annotations, before marking a new model class as complete.
- Symptom
click.get_current_context() returns None inside a Flask app factory when running the flask command with the reloader.
Cause and fixCause: With lazy loading, the default under the reloader, the app factory runs in a separate thread, and Click's context is thread-local. Fix: In cli.py the lazily loaded app is now created so the Click context stays available consistently inside the flask command.
- Symptom
Using stream_with_context in an async Flask view fails, while the same route written as a sync function works.
Cause and fixCause: The request context created and pushed its own app context, then popped it automatically, and the internal ContextVar became tied to the temporary event loop used by async views. Fix: In helpers.py the generator now stores the app context along with the request context, and both are pushed (app context first) only when iteration begins rather than during setup.
- Symptom
A FlaskGroup nested inside a larger click group ignores the create_app factory passed to it and loses other Flask CLI behavior.
Cause and fixCause: FlaskGroup put its custom setup in main(), which Click does not call when a nested group's subcommands are invoked. Fix: The custom behavior was moved from FlaskGroup.main into __init__ and make_context, so both flask.cli.cli and custom FlaskGroup instances work when nested under another CLI.
- Symptom
Flask fails to serve static files when static_url_path ends with a slash, for example /foo/ or /.
Cause and fixCause: The static route appends a rule that already starts with a slash, so a prefix ending in a slash produced a doubled slash. Fix: The static URL path handling in app.py and blueprints.py was changed so a trailing slash on static_url_path no longer breaks the route, with a new test in test_basic.py.
- Symptom
With the reloader active, flask run hides startup syntax errors until the first request because the app is imported lazily.
Cause and fixCause: Lazy loading was the default whenever the reloader was enabled, including on the very first load. Fix: When neither --eager-loading nor --lazy-loader is given, flask run now loads eagerly on first start so errors show immediately, then loads lazily on reloads so the server stays up.
- Symptom
Flask send_file with an io.StringIO object returns 200 OK with an empty body and prints a traceback in the terminal.
Cause and fixCause: send_file only works with binary data, and a text-mode file object cannot be streamed correctly. Fix: send_file in helpers.py now raises ValueError when given an io.TextIOBase instance, so the mistake is reported instead of yielding a blank file.
- Symptom
Flask cannot nest the same blueprint in different places, and url_for fails when one blueprint is registered under several prefixes, because registration uses only the blueprint's own name.
Cause and fixCause: Blueprints were registered under the name they were created with, not the full dotted name that includes their parent. Fix: Blueprints are now registered under their full nested name, and register_blueprint accepts a name option that changes the registered name.
- Symptom
mypy reports a type error for an after_request function annotated with Flask's own Response, which type-checked fine in Flask 2.0.
Cause and fixCause: AfterRequestCallable was typed to take Werkzeug's base Response, but Flask passes its Response subclass to callbacks. Fix: typing.py introduces a ResponseType type variable bound to Werkzeug's Response and uses it in AfterRequestCallable, with the decorators in app, blueprints, scaffold, ctx and views updated to match.