Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a function to a route functionally, without a route decorator in FastAPI?

Tags:

python

fastapi

In Flask, it is possible to assign an arbitrary function to a route functionally like:

from flask import Flask
app = Flask()

def say_hello():
    return "Hello"

app.add_url_rule('/hello', 'say_hello', say_hello)

which is equal to (with decorators):

@app.route("/hello")
def say_hello():
    return "Hello"

Is there such a simple and functional way (add_url_rule) in FastAPI?

like image 344
alercelik Avatar asked Oct 25 '25 20:10

alercelik


2 Answers

You can use the add_api_route method to add a route to a router or an app programmtically:

from fastapi import FastAPI, APIRouter


def foo_it():
    return {'Fooed': True}


app = FastAPI()
router = APIRouter()
router.add_api_route('/foo', endpoint=foo_it)
app.include_router(router)
app.add_api_route('/foo-app', endpoint=foo_it)

Both expose the same endpoint in two different locations:

λ curl http://localhost:8000/foo
{"Fooed":true}
λ curl http://localhost:8000/foo-app
{"Fooed":true}
like image 176
MatsLindh Avatar answered Oct 27 '25 10:10

MatsLindh


Decorators are just syntactic sugar. They are simply functions that take another function as the first positional argument.

For example this:

from fastapi import FastAPI
app = FastAPI()

@app.get("/hello")
def say_hello():
    return "Hello"

Is equal to this:

from fastapi import FastAPI
app = FastAPI()

def say_hello():
    return "Hello"


say_hello = app.get("/hello")(say_hello)

You don't need the assignment (setting the variable say_hello) as FastAPI always returns the function itself. That was to illustrate what decorators do.

I agree that the above is ugly and you might want to use the app.add_api_route as MatsLindh's answer suggests. However, I did not find that in the FastAPI documentation so not sure how official it is. Overall, it seems FastAPI's documentation lacks in this regard.

like image 45
miksus Avatar answered Oct 27 '25 11:10

miksus