Search code examples
openapijson-api

How do I express JSON-API sparse fieldsets with OpenAPI-3.0


I'm implementing an OpenAPI-3.0 spec for my API, and I plan on using sparse fieldsets as a parameter for GETs. The examples for parameters using style=deepObject are a little sparse, so I'm not sure if I've got this exactly right.

- in: query
  name: fields
  style: deepObject
  schema:
    type: object
    additionalProperties:
      type: string

Can I combine both the deepObject and additionalProperties options?

I want to support flexible query parameter inputs like this: GET /articles?include=author&fields[articles]=title,body&fields[people]=name but I don't want to have to spell out every single option for each resource and field.


Solution

  • Your definition is correct. You might also need to add allowReserved: true so that the comma in =title,body is not percent-encoded, and you can add a parameter example value for documentation purposes:

    - in: query
      name: fields
      style: deepObject
      allowReserved: true
      schema:
        type: object
        additionalProperties:
          type: string
        example:
          articles: title,body
          people: name
    

    When using "try it out" in Swagger UI, enter the parameter value in the JSON format like so:

    {
      "articles": "title,body",
      "people": "name"
    }
    

    Swagger UI will serialize the parameter as

    ?fields[articles]=title,body&fields[people]=name