Keeping endpoint function declarations in separate modules with FastAPI

  fastapi, python, python-3.x

I have an API that uses FastAPI. In a single file (main.py), I have the call to the function that creates the API

from fastapi import FastAPI
# ...
app = FastAPI()

As well as all the endpoints:

@app.post("/sum")
async def sum_two_numbers(number1: int, number2: int):
    return {'result': number1 + number2}

But as the application gets larger, the file is becoming messy and hard to maintain. The obvious solution would be to keep function definitions in separate modules and just import them and use them in main.py, like this:

from mymodules.operations import sum_two_numbers
# ...
@app.post("/sum")
sum_two_numbers(number1: int, number2: int)

Only that doesn’t work. I don’t know if I’m doing it wrong or it can’t be done, but I get this error from VSCode:

Expected function or class declaration after decorator | Pylance

(My program has so many errors that I haven’t seen the actual interpreter complaint, but if that’s important, I can try debug it and post it here)

So is this impossible to do and I have to stick to the one-file API, or it is possible to do, but I’m doing it wrong? If the second, what is the right way?

Source: Python Questions

LEAVE A COMMENT