oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Custom error json output when query parameter is required

Open manuelarte opened this issue 7 months ago • 3 comments

Hi,

I have the following openapi.yml:

...
  /users:
    get:
      summary: Get a user by surname
      parameters:
        - in: query
          name: surname
          schema:
            type: string
          required: true
          description: The user's surname
...

So if I call the endpoint without the surname query parameter, I am getting something like:

{ 
  "msg": "Query argument surname is required, but not found" 
}

But I would like to return my own response, as an example, something like:

{
  "type": "validation",
  "message": "surname is required"
}

How can I achieve that?

manuelarte avatar Jul 16 '25 14:07 manuelarte

Were you able to find any solutions?

reza-cb avatar Nov 17 '25 06:11 reza-cb

Were you able to find any solutions?

There is an option to set "global" errors. You can see an example here (this is my own repo): https://github.com/manuelarte/go-web-layout/blob/34e781b67d6ac956069d407ecb2a15699f4639d3/internal/api/rest/api.go#L32

manuelarte avatar Nov 17 '25 08:11 manuelarte

Were you able to find any solutions?

There is an option to set "global" errors. You can see an example here (this is my own repo): https://github.com/manuelarte/go-web-layout/blob/34e781b67d6ac956069d407ecb2a15699f4639d3/internal/api/rest/api.go#L32

Thanks @manuelarte . This works perfectly. Just for others who might have the same requirement and are using Gin: this is not supported in Gin. However, what Manuel suggested works perfectly in Chi.

reza-cb avatar Nov 18 '25 04:11 reza-cb