如何解决当我的 JSON 是这样的时,如何为我的 FastAPI 端点创建 Pydantic 模型?
{
'events': [
{
'type': 'message','replyToken': '0bc647fc5282423cde13fffbc947a8','source': {
'userId': 'U996ed69353d3c962ee17b33d9af3e2','type': 'user'
},'timestamp': 161185209914,'mode': 'active','message': {
'type': 'text','id': '1346188304367','text': ' hello'
}
}
],'destination': 'Uf44eb3ba6c4b87adbfaa4a517e'
}
这是我正在使用的 webhook 中的 json 它是这样包含的,我该如何为它编写 Pytantic 模型?
解决方法
这应该适用于您上面给出的请求正文。
from pydantic import BaseModel
from typing import List
class Source(BaseModel):
userId: str
type: str
class Message(BaseModel):
type: str
id: str
text: str
class Event(BaseModel):
type: str
replyToken: str
source: Source
timestamp: int
mode: str
message: Message
class Webhook(BaseModel):
events: List[Event]
destination: str
这是 Webhook
模型的 OpenAPI 架构。
{
"title": "Webhook","type": "object","properties": {
"events": {
"title": "Events","type": "array","items": {
"$ref": "#/definitions/Event"
}
},"destination": {
"title": "Destination","type": "string"
}
},"required": [
"events","destination"
],"definitions": {
"Source": {
"title": "Source","properties": {
"userId": {
"title": "Userid","type": "string"
},"type": {
"title": "Type","type": "string"
}
},"required": [
"userId","type"
]
},"Message": {
"title": "Message","properties": {
"type": {
"title": "Type","id": {
"title": "Id","text": {
"title": "Text","required": [
"type","id","text"
]
},"Event": {
"title": "Event","replyToken": {
"title": "Replytoken","source": {
"$ref": "#/definitions/Source"
},"timestamp": {
"title": "Timestamp","type": "integer"
},"mode": {
"title": "Mode","message": {
"$ref": "#/definitions/Message"
}
},"replyToken","source","timestamp","mode","message"
]
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。