How to pass on request from one server to another in FastAPI?

239 views Asked by At

I have two different machines, each running same FastAPI() application, started with unicorn on port 3000. I am not sure what is the right approach to duplicate each route from the first server to the second one..

For example when the first server get

@router.post("/register_book")
async def register_book(
    request: RegisterBookRequest, db)
) -> Response:
....

What I look for is a way, that not only first server will proceed this request, but also same request will be sent from server A to server B.. something like

@router.post("/register_book")
async def register_book(
    request: RegisterBookRequest, db)
) -> Response:
....
// initiate the same synchronous request to <second server IP>:3000, wait for response

Any ideas? The best I guess something like

@router.post("/register_book")
@something.dupliate.request("<second_server_ip>:3000")
async def register_book(
    request: RegisterBookRequest, db)
) -> Response:
....

but I doubt it possible..thanks

1

There are 1 answers

2
Yurii Motov On

You can create middleware.

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def duplicate_request(request: Request, call_next):
    # Send request to server 2
    # You can send it in separate asyncio 
    # task and wait for results in the end of this
    # function (before return) 
    response = await call_next(request)
    # Wait for response from server 2
    return response