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

Question:

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?

Asked By: alercelik

||

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}
Answered By: 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.

Answered By: miksus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.