OpenAPI文档中WebSocket请求、响应及请求来源表示问询
OpenAPI 中 WebSocket 相关问题解答
1. WebSocket 不存在 HTTP 方法,是否要全部视为 POST?
不用硬套 HTTP 的 GET/POST 方法。OpenAPI 原生并未完全适配 WebSocket 协议(因为 WebSocket 是双向、无特定请求方法的长连接),所以不要将 WebSocket 消息映射为 HTTP 请求方法。
你可以通过自定义扩展字段(比如x-websocket-operation)来标记这是一个 WebSocket 操作,明确它和 HTTP 接口的区别。比如:
paths: /chat: x-websocket: true post: operationId: sendChatMessage x-websocket-direction: client-to-server requestBody: content: application/json: schema: type: object properties: message: type: string responses: '200': description: 服务器确认消息接收
这里的post只是为了符合 OpenAPI 的语法结构,实际代表的是客户端向服务器发送的 WebSocket 消息,而非 HTTP POST 请求。
2. 如何标识请求发起方(服务器/客户端)?
通过自定义扩展字段明确消息方向,常用两种方式:
- 在操作级别添加扩展,比如
x-websocket-direction,值设为client-to-server或server-to-client,分别对应客户端发起和服务器推送的消息。 - 拆分操作块:单独定义客户端发送消息的操作,以及服务器推送消息的操作,用
summary或description明确方向。
示例:
paths: /chat: x-websocket: true # 客户端向服务器发消息 post: summary: 客户端发送聊天消息 x-websocket-direction: client-to-server requestBody: ... # 服务器向客户端推消息 get: summary: 服务器推送聊天消息 x-websocket-direction: server-to-client responses: '200': content: application/json: schema: type: object properties: sender: type: string message: type: string
这里的get也只是语法占位,实际代表服务器主动推送的消息。
3. OpenAPI 格式的 WebSocket 示例
下面是一个完整的极简示例,用扩展字段适配 WebSocket 双向通信:
openapi: 3.0.3 info: title: WebSocket Chat API version: 1.0.0 servers: - url: wss://api.example.com/chat paths: /chat: x-websocket: true # 客户端发送消息 post: operationId: clientSendMessage x-websocket-direction: client-to-server requestBody: required: true content: application/json: schema: type: object properties: userId: type: string message: type: string required: [userId, message] responses: '200': description: 服务器已接收消息 content: application/json: schema: type: object properties: status: type: string enum: [success] # 服务器推送消息 get: operationId: serverPushMessage x-websocket-direction: server-to-client responses: '200': description: 服务器推送的聊天消息 content: application/json: schema: type: object properties: senderId: type: string message: type: string timestamp: type: string format: date-time
这个示例通过x-websocket标记路径为 WebSocket 端点,用x-websocket-direction区分消息方向,同时用requestBody和responses分别定义客户端发送的消息结构和服务器推送的消息结构。
内容的提问来源于stack exchange,提问作者Nithin B
相关产品推荐
相关产品推荐

