艾克斯记事-XDIANNAO

FastAPI接收复杂JSON数据

一边学FastAPI一边做项目,之前一直在用flask,改用FastAPI的时候发现,在接收复杂JSON好像有点麻烦,尤其是那种嵌套多层的数据,研究了一阵子,我通过下面的方式实现了;

from typing import Dict,List,Any
from fastapi import FastAPI
from pydantic import BaseModel

app =FastAPI()

class XDPost(BaseModel):
  accesskey: str
  data: Dict[str,Any]

@app.post("/API/TEST")
def xd_test(xdpost: XDPost):
  return xdpost

测试:

{
    "accesskey":"ABCDEFGHIJK",
    "data":{
        "a":[[1,2],[3,4]],
        "b":{"b.1":[[1,2],[3,4]],
            "b.2":{"b.2":"b.2"}
        }

    }
}

返回值:

{"accesskey":"ABCDEFGHIJK","data":{"a":[[1,2],[3,4]],"b":{"b.1":[[1,2],[3,4]],"b.2":{"b.2":"b.2"}}}}

成功实现;

版权所有©艾克斯记事-转载文章请注明出处(带链接)