fix(openapi): always set requestBody.required to true when schema.body exists
Fastify requires a body when schema.body is defined, even if all properties are optional. This ensures the OpenAPI spec correctly reflects Fastify's runtime behavior. This solves the issue #894
Problem
When a route has schema.body defined, Fastify requires that the request includes a body (at least {}), even if all properties inside that body are optional. However, the OpenAPI schema generated by @fastify/swagger was only setting requestBody.required to true when there were required properties inside the object. If the object had only optional properties, then requestBody.required was omitted, incorrectly marking the request body as optional.
This mismatch between the OpenAPI spec and Fastify's actual runtime behavior can mislead client code generators and API consumers.
Solution
This fix ensures that requestBody.required is always set to true when schema.body is defined, regardless of whether any properties inside the body are required. The fix sets required: true when creating the requestBody object in prepareOpenapiMethod, making it explicit that the body is required whenever a body schema is defined.
Example
Before (incorrect):
{
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"hello": { "type": "string" }
}
}
}
}
}
}
After (correct):
{
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"hello": { "type": "string" }
}
}
}
}
}
}
Changes
- Set
required: truewhen creatingrequestBodyobject inprepareOpenapiMethod - Added test case for body with only optional properties
- Updated existing tests to expect
required: truewhenschema.bodyis defined
Fixes the issue where the OpenAPI spec incorrectly showed requestBody as optional when Fastify actually requires it at runtime.
Checklist
- [x] run
npm run test && npm run benchmark --if-present - [x] tests and/or benchmarks are included
- [ ] documentation is changed or added
- [x] commit message and code follows the Developer's Certification of Origin and the Code of conduct
@Fdawgs when you get a moment, could you please take a look at this PR? Thanks!
@gurgunday @Fdawgs can we merge it ?
Not sure if we should count this as a bug fix or semver major
I lean towards the latter
Cc @mcollina
@Fdawgs @gurgunday just a quick bump — anything else needed before we merge?