fastify-swagger icon indicating copy to clipboard operation
fastify-swagger copied to clipboard

fix(openapi): always set requestBody.required to true when schema.body exists

Open bas0N opened this issue 1 month ago • 4 comments

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: true when creating requestBody object in prepareOpenapiMethod
  • Added test case for body with only optional properties
  • Updated existing tests to expect required: true when schema.body is defined

Fixes the issue where the OpenAPI spec incorrectly showed requestBody as optional when Fastify actually requires it at runtime.

Checklist

bas0N avatar Nov 22 '25 13:11 bas0N

@Fdawgs when you get a moment, could you please take a look at this PR? Thanks!

bas0N avatar Nov 25 '25 22:11 bas0N

@gurgunday @Fdawgs can we merge it ?

bas0N avatar Dec 01 '25 22:12 bas0N

Not sure if we should count this as a bug fix or semver major

I lean towards the latter

Cc @mcollina

gurgunday avatar Dec 01 '25 22:12 gurgunday

@Fdawgs @gurgunday just a quick bump — anything else needed before we merge?

bas0N avatar Dec 11 '25 23:12 bas0N