如何将JSON加载的参数传入FastAPI端点函数?
Solution
First, fix the immediate issues in your code:
- Remove the redundant
app.mount("/", app)line—it’s unnecessary and can cause routing conflicts. - Unpack your parameter dictionary using
**to pass each key-value pair as individual keyword arguments tomy_endpoint. - Since
my_endpointis a synchronous function, you don’t needasyncio.run—call it directly from your async endpoint (FastAPI automatically handles sync functions in async contexts via a thread pool).
Here’s the corrected code:
from fastapi import FastAPI app = FastAPI() @app.get('/my-endpoint') def my_endpoint( arg1: int, arg2: str, # ... include all other 68 parameters here arg70: str ): print("Doing some action with those 70 arguments...") # ... your business logic here return "Some fake response" # Example parameters stored as a dictionary (equivalent to your JSON) arguments_dict = { "arg1": 12, "arg2": "extract", # ... match all parameters required by my_endpoint } @app.get('/another-endpoint') async def another_endpoint(): # Unpack the dictionary into individual keyword arguments response = my_endpoint(**arguments_dict) return response
Better Approach for Maintainability (With Frequent Parameter Changes)
Having 70 individual parameters in your function signature is hard to maintain, especially when parameters are added or removed regularly. Instead, use a Pydantic BaseModel to encapsulate all parameters:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # Define a model that includes all your parameters class MyEndpointParams(BaseModel): arg1: int arg2: str # ... add all 70 parameters here with their types @app.get('/my-endpoint') def my_endpoint(params: MyEndpointParams): # Access parameters via params.arg1, params.arg2, etc. print("Doing some action with parameters...") # ... your logic return "Some fake response" # Example parameter dict (loaded from JSON or stored) arguments_dict = { "arg1": 12, "arg2": "extract", # ... all parameters matching the model } @app.get('/another-endpoint') async def another_endpoint(): # Convert the dict to the Pydantic model instance params = MyEndpointParams(**arguments_dict) response = my_endpoint(params) return response
This way, when you need to add or remove parameters, you only update the MyEndpointParams model instead of modifying the function signature—much cleaner and less error-prone.
内容的提问来源于stack exchange,提问作者FN_
相关产品推荐
相关产品推荐

