I have a FastAPI endpoint which takes up to 70 parameters and they are often added or removed.
I have also list of arguments sent to this API stored in JSON
format (extracted using json.dumps(locals())
), so I can easily reproduce the API call in the future.
I would like to call EP /another-endpoint
which is gonna load arguments from JSON
and call another EP /my-endpoint
, how should I do it?
My code so far
from fastapi import FastAPI
import asyncio
app = FastAPI()
app.mount("/", app)
@app.get('/my-endpoint')
def my_endpoint(
arg1: int,
arg2: str,
...
arg70: str
):
print("Doing some action with those 70 arguments...")
...
return "Some fake response"
# Example arguments in JSON format
arguments_json = {
"arg1": 12,
"arg2": "extract",
....
}
@app.get('/another-endpoint')
async def another_endpoint():
# I have tried using asyncio since I am calling another async function
# but this does not work obviously
response = asyncio.run(my_endpoint(arguments_json))
It does not work, obviously.
CodePudding user response:
you can convert the JSON format arguments into a dictionary, then pass the dictionary as kwargs to the my_endpoint function. Here's an example implementation:
from fastapi import FastAPI
import asyncio
app = FastAPI()
app.mount("/", app)
@app.get('/my-endpoint')
def my_endpoint(
arg1: int,
arg2: str,
...
arg70: str
):
print("Doing some action with those 70 arguments...")
...
return "Some fake response"
# Example arguments in JSON format
arguments_json = {
"arg1": 12,
"arg2": "extract",
....
}
@app.get('/another-endpoint')
async def another_endpoint():
# Convert the JSON format arguments into a dictionary
arguments_dict = json.loads(arguments_json)
# Pass the dictionary as **kwargs to the my_endpoint function
response = await my_endpoint(**arguments_dict)
return response