SwaggerHub Mock接口POST请求字段缺失仍返回201问题求助
I see the issue here—SwaggerHub's default mock server doesn't automatically enforce request body validation unless you explicitly configure two key things in your OpenAPI definition AND enable validation in the mock settings. Let's break down the fixes step by step:
1. Mark Required Fields in Your Order Schema
Right now, your Order definition doesn't specify which fields are mandatory. Without this, the mock server treats all fields as optional, so missing fields won't trigger a 400 error. Add a required array to the Order object listing all fields that must be present in a valid request:
definitions: Order: type: object required: # Add this section to define mandatory fields - marketPair - amount - operationType - orderType # Include any other fields that are non-negotiable for your use case properties: id: type: string format: uuid example: d290f1ee-6c54-4b01-90e6-d701748f0851 marketPair: type: integer format: "int64" example: "BTC_TRY" amount: type: number format: "int64" example: "1.3" price: type: integer format: "int32" example: "467" operationType: type: string description: "Type of operation" enum: - "buy" - "sell" example: "buy" orderType: type: string description: "Order Type" enum: - "limit" - "market" - "stop" default: "limit" example: "limit" xml: name: "Order"
2. Mark the Body Parameter as Required
Your POST request's order body parameter isn't marked as required. This means the mock server accepts requests without a body and still returns 201. Add required: true to the parameter definition:
post: summary: "Creates order" description: "" consumes: - application/json parameters: - name: "order" in: body description: "New order" required: true # Add this line to enforce a request body schema: $ref: "#/definitions/Order" responses: 201: description: "Order succesfully created." 400: description: "Order can't be created"
3. Enable Request Validation in SwaggerHub Mock Settings
Even with the definition fixes, you need to turn on validation in the SwaggerHub mock configuration:
- Navigate to your API in SwaggerHub
- Click the Mock button in the top-right corner
- In the mock settings panel, find the Validate Requests toggle and switch it to On
- Save your settings
Once you've completed these steps, the mock server will behave as expected:
- Return 400 if there's no request body (thanks to
required: trueon the body parameter) - Return 400 if any required fields are missing, or if fields have invalid data types/enum values (thanks to the
requiredarray and schema constraints)
内容的提问来源于stack exchange,提问作者Stan Reduta

