简体   繁体   中英

How to assign a function to a route functionally, without a route decorator in 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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM