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

Time:04-26

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?

CodePudding user response:

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}
  • Related