SSK
SSK

Reputation: 3766

Object as query string param in API on Open API Specification Swagger

I have an API which is accepting query param as Object. I am using this to add multiple filters to filter the result.

When I hit the request from swagger, I am getting null for my filter object in the controller.

userFilter is the POJO class. It is used as a query param and in the controller, it is coming as null.

On swagger, it is showing as below

swagger screenshot

userFilter object is not getting constructed and getting NullPointerException in controller class when trying to access any field from userFilter.

Upvotes: 3

Views: 4323

Answers (1)

SSK
SSK

Reputation: 3766

I got the solution from swagger.io.

As per the explanation, content is used in complex serialization scenarios that are not covered by style and explode. For example, if we need to send a JSON string in the query string like so:

filter={"type":"t-shirt","color":"blue"}

In this case, we need to wrap the parameter schema into content/<media-type> as shown below.

We need to add content = {@Content(schema = @Schema(type = "object"))} to the @Parameter.

@Parameter(description = "Filters", required = true, content = {@Content(schema = @Schema(type = "object"))})

In JSON format it will look like below.

parameters:
  - in: query
    name: filter
    
    # Wrap 'schema' into 'content.<media-type>'
    content:
      application/json:  # <---- media type indicates how to serialize / deserialize the parameter content
        schema:
          type: object
          properties:
            type:
              type: string
            color:
              type: string

Upvotes: 6

Related Questions