Before I start: I reviewed the following links and none of them matched my question:
- Swagger - Specify Optional Object Property or Multiple Responses
- Swagger; specify two responses with same code based on optional parameter
- Swagger - Specify Optional Object Property or Multiple Responses
So, I have OpenAPI 3 definition for an endpoint that returns a given payload for a successful call (e.g. 200 OK
). However, for unsuccessful calls (e.g. 408 CONFLICT
), I want to return a completely different error payload.
You can see the definition below:
openapi: 3.0.1
info:
title: Dogs
description: API to add dogs into a database
version: 0.0.1
paths:
/dog:
post:
description: Saves a dog into the database
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/Dog"
responses:
201:
description: A dog was added to the system
content:
application/json:
schema:
$ref: "#/components/schemas/Dog"
400:
description: This dog already exist in the system
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Dog:
type: object
properties:
name:
type: string
description: Name of the dog
example: "barky"
Error:
type: object
properties:
code:
type: string
description: Machine-readable code of the error.
example: "Already Exists"
message:
type: string
description: A Human-readable error message.
example: "Empty string is not a valid name for a dog"
From that, I'm generating a Spring
code (currently using the Swagger editor
). The method signature that is associated with the definition looks like that:
ResponseEntity<Dog> dogPost(@ApiParam(value = "" ) @Valid @RequestBody Dog body);
As a result - I cannot return the Error object in this function unless throwing an exception and catching in later on - which I consider a bad practice since the action of invalid input is not an exception.
Is there a way to solve this nicely without throwing an exception and catching it outside of the function scope?