当我的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它是这样被包含的,我怎么能为它写一个柏拉图式的模型呢?

这应该与您上面给出的请求正文一起工作。

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",
"type": "object",
"properties": {
"userId": {
"title": "Userid",
"type": "string"
},
"type": {
"title": "Type",
"type": "string"
}
},
"required": [
"userId",
"type"
]
},
"Message": {
"title": "Message",
"type": "object",
"properties": {
"type": {
"title": "Type",
"type": "string"
},
"id": {
"title": "Id",
"type": "string"
},
"text": {
"title": "Text",
"type": "string"
}
},
"required": [
"type",
"id",
"text"
]
},
"Event": {
"title": "Event",
"type": "object",
"properties": {
"type": {
"title": "Type",
"type": "string"
},
"replyToken": {
"title": "Replytoken",
"type": "string"
},
"source": {
"$ref": "#/definitions/Source"
},
"timestamp": {
"title": "Timestamp",
"type": "integer"
},
"mode": {
"title": "Mode",
"type": "string"
},
"message": {
"$ref": "#/definitions/Message"
}
},
"required": [
"type",
"replyToken",
"source",
"timestamp",
"mode",
"message"
]
}
}
}