Fastapi: How to define a generic route?

Created on 27 Dec 2019  路  3Comments  路  Source: tiangolo/fastapi

Description

How to define a generic route that can accept any method(and of course get the request data)?

The desired route should accept any method (GET, PUT, POST, etc.)

With starlette, we can do this:

@app.route('/echo')
async def echo(request):
    return f'Client used {request.method} method'

You can see that clients can use any method(GET, PUT, POST, etc.) for /echo endpoint and server can check the used method with request.method here.

Bu in FastAPI, @app.route decorator doesn't work like that.

question

Most helpful comment

@ramazanpolat
I've found api_route decorator and looks like it's something you're looking for.

@app.api_route("/test", methods=["GET", "POST", "DELETE"])
async def test(request: Request):
    return {"method": request.method}

All 3 comments

@ramazanpolat
I've found api_route decorator and looks like it's something you're looking for.

@app.api_route("/test", methods=["GET", "POST", "DELETE"])
async def test(request: Request):
    return {"method": request.method}

Thanks for the help here @shifr ! :clap: :bow:

Thanks for reporting back and closing the issue @ramazanpolat :+1:

Have in mind that it's probably best not to do that, as you will end up with complex mixed logic.

If the code for different HTTP operations is similar, then it's probably best to put the common parts in functions, or in dependencies than putting it all together in the same big function. Also, some more context: https://github.com/tiangolo/fastapi/issues/913#issuecomment-585968618

I have encountered an issue on some point, where the GET request would fail, because it was getting too long. Using POST did the trick, but I didn't want to give up on the GET option either, as it was a nice convince method for 90% of the requests. Both of them have the exact same logic, but as mentioned GET seemed to have limits.

@router.post('/domagic')
def post_my_request(query: MyModel):
    return get_my_request(query.name, query.type)

@router.get('/domagic')
def get_my_request(name=None, type=None):
    //do some magic
   return result

or

@router.post('/domagic')
def post_my_request(query: MyModel):
    return _do_magic(query.name, query.type)

@router.get('/domagic')
def get_my_request(name=None, type=None):
    return _do_magic(name, type)

def _do_magic(name, type):
    //do some magic
   return result  
Was this page helpful?
0 / 5 - 0 ratings