如何用Swagger创建带JSON请求体的POST API?参数配置咨询
Fixing Your Swagger POST API Configuration for Label Creation
Let's walk through the issues in your current Swagger definition and fix them step by step:
Key Issues in Your Current Setup
- Incorrect
labelRequestDefinition: You've setlabelRequestas anobjectbut used theitemsfield (which is only meant for array types). This causes Swagger to misinterpret your request body structure. - Missing
consumesField: For POST requests accepting JSON bodies, you need to explicitly specify the media type your API consumes (not just what it produces). - Ambiguous 201 Response: While referencing the request schema works, it's better to ensure the response schema clearly matches the actual returned resource (which mirrors your request structure here).
Corrected Full Swagger Definition
swagger: '2.0' info: title: Device Labels API version: '1.0' paths: '/api/v1/labels': post: tags: - devices summary: Create new label description: Create a new label for specified devices operationId: createNewLabel consumes: # Added to specify accepted request body format - application/json produces: - application/json parameters: - name: x-access-token description: Cognito authentication token in: header type: string required: true - in: body name: body description: Details of the label to create required: true schema: $ref: '#/definitions/LabelRequest' responses: '201': description: Label created successfully schema: $ref: '#/definitions/LabelRequest' definitions: LabelRequest: # Simplified structure without invalid `items` field type: object required: # Explicitly mark mandatory fields (best practice) - device_ids - name properties: device_ids: type: array items: type: string format: uuid example: "9bc11e25-4db2-4780-b761-390e3806082a" example: ["ea4b9daa-07cd-4cd6-981f-c86e1e81f04c"] name: type: string example: "labelName"
Breakdown of Changes
- Fixed Request Body Definition: Removed the invalid
itemsfield fromlabelRequestand merged thelabelRequestBodystructure directly into it (since your request is a single object, not an array of objects). - Added
consumes: Tells Swagger your API acceptsapplication/jsonrequest bodies, which aligns with your Postman test request. - Explicit Required Fields: Added a
requiredarray toLabelRequestto enforce thatdevice_idsandnameare always provided, matching your expected request structure. - Improved Readability: Renamed definitions to use PascalCase (standard for Swagger) and updated examples to match your actual API usage, making the documentation more actionable.
With this configuration, Swagger will correctly render the request body form, validate required fields, and display the expected 201 response structure that matches your API's behavior.
内容的提问来源于stack exchange,提问作者tupac shakur
相关产品推荐
相关产品推荐

