Skip to content

Defining the request body type in a dynamically created endpoint - typing issues #2901

Closed
@provinzkraut

Description

@provinzkraut

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here's a self-contained, minimal, reproducible, example with my use case:

from typing import Type
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()


def create_endpoint(model: Type[BaseModel]):
    @app.post("/")
    def post(data: model):
        pass

Description

  • Run mypy against this snippet
  • Receive the error Variable "model" is not valid as a type

The provided example works as intended, but mypy - rightfully - complains about this since type variables cannot be used as types. The problem however is that using Type[...] to annotate create_endpoint is correct but there's no way (that I am aware of) in FastAPI to define the type of the request body other than with an annotation.

It would be really great to have a different way to achieve this, because as of now, dynamically creating endpoints like this is a bit inconvenient.

Environment

  • OS: Debian 10.8
  • FastAPI Version: 0.63.0
  • Python version: 3.8.6

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions