You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 to my_endpoint.
  • Since my_endpoint is a synchronous function, you don’t need asyncio.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_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:30:50