@Operation vs @ApiResponse in Swagger
Last updated: July 26, 2023
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .
You can explore the course here:
>> Learn Spring Security
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .
The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
>> Take a look at DBSchema
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:
>> Try out the Profiler
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .
Get started with Spring Data JPA through the guided reference course:
>> CHECK OUT THE COURSE
Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.
Simply put, Digma provides immediate code feedback . As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.
The feedback is available from the minute you are writing it.
Imagine being alerted to any regression or code smell as you're running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.
>> Enable code feedback in your IDE.
Of course, Digma is free for developers.
30% less RAM and a 30% smaller base image for running a Spring Boot application? Yes, please.
Alpaquita Linux was designed to efficiently run containerized Java applications.
It's meant to handle heavy workloads and do it well.
And the Alpaquita Containers incorporates Liberica JDK Lite, a Java runtime tailored to cloud-based services:
>> Try Alpaquita Containers now.

We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial :
>> The Essential List of Spring Boot Annotations and Their Use Cases

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:
1. overview.
In this tutorial, we’ll discuss the main differences between Swagger’s @Operation and @ApiResponse annotations.
2. Descriptive Documentation With Swagger
When we create a REST API, it’s also important to create its proper specification. Additionally, such a specification should be readable, understandable, and provide all essential information.
Moreover, the documentation should describe every change made to the API. It’d be exhausting and, more importantly, time-consuming to create REST API documentation manually. Fortunately, tools like Swagger can help us with this process.
Swagger represents a set of open-source tools built around OpenAPI Specifications . It can help us design, build, document, and consume REST APIs.
The Swagger Specification is a standard for documenting REST APIs. Using Swagger Specification, we can describe our entire API, such as exposed endpoints, operations, parameters, authentication methods, etc.
Swagger provides various annotations that can help us document REST API. Moreover, it provides the @Operation and @ApiResponse annotations to document responses for our REST API . In the remainder of this tutorial, we’ll use the below controller class and see how to use these annotations:
3. @Operation
The @Operation annotation is used to describe a single operation. An operation is a unique combination of a path and an HTTP method.
Additionally, using @Operation , we can describe the result of a successful REST API call. In other words, we can use this annotation to specify the general return type.
Let’s add the annotation to our method:
Next, we’ll go through some of the most used properties within @Operation .
3.1. The summary Property
The required summary property contains the operation’s summary field. Simply put, it provides a short description of the operation. However, we should keep this parameter shorter than 120 characters.
Here’s how we define the summary property inside the @Operation annotation:
3.2. The description Property
Using description , we can provide more details about the operation. For instance, we can place a text describing the endpoint’s restrictions:
3.3. The hidden Property
The hidden property represents whether or not this operation is hidden.
4. @ApiResponse
It’s a common practice to return errors using HTTP status codes. We can use the @ApiResponse annotation to describe the concrete possible response of an operation.
While the @Operation annotation describes an operation and a general return type, the @ApiResponse annotation describes the rest of the possible return codes.
Furthermore, the annotation can be applied at the method level as well as at the class level. Moreover, annotation on the class level will be parsed only if an @ApiResponse annotation with the same code is not already defined on the method level. In other words, the method annotations have precedence over class annotations.
We should use the @ApiResponse annotations within the @ApiResponses annotation whether we have one or multiple responses. If we use this annotation directly, it will not be parsed by Swagger.
Let’s define the @ApiResponses and @ApiResponse annotations on our method:
We can use the annotation to specify the success response as well:
Now, let’s go through some of the properties used within @ApiResponse .
4.1. The responseCode and description Properties
Both responseCode and description properties are required parameters in the @ApiResponse annotation. It’s important to mention we cannot define more than one @ApiResponse with the same code property.
The message property usually contains a human-readable message that goes along with the response:
4.2. The content Property
Sometimes, an endpoint uses different response types. For example, we can have one type for success response and another for error response. We can describe them using the optional content property by associating a response class as a schema.
Firstly, let’s define a class that will be returned in case of an internal server error:
Secondly, let’s add a new @ApiResponse for internal server errors:
5. Differences Between @Operation and @ApiResponse
To sum up, the following table shows the main differences between the @Operation and @ApiResponse annotations:
6. Conclusion
In this article, we learnt the differences between the @Operation and @ApiResponse annotations.
As always, the source code for the examples is available on GitHub .
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
Get started with spring 5 and spring boot 2, through the learn spring course :.

Follow the Spring Category

Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
Annotations 1.5.X
Swagger 2.x.
- What is it about?
- Where to start
- Quick start
- Your own configuration
- Full control of your API definition
- Visualize and interact
- Dependencies
- Exposing OpenAPI definition
- Configuration
- Configuration properties
- Resolve the OpenAPI Definition
- Resource scanning
- Scenarios examples
Quick Annotation Overview
- Reader listeners
- Configure a custom scanner
- Extending Reader
- Extending core Resolver
- OpenAPI 3.1 Support
- Not using Maven
- Migration from 1.5
Integration 1.5.X
- Annotations

Migration Guides
- swagger-core 1.3 to 1.5
Tutorials 1.5.X
- Overriding Models
- CORS Support
- Coding Standards
Legacy Docs
Clone this wiki locally, swagger-core annotations.
In order to generate the Swagger documentation, swagger-core offers a set of annotations to declare and manipulate the output. The swagger-core output is compliant with Swagger Specification . A user is not required to be familiar with the full aspects of the Swagger Specification in order to use it, but as a reference it may answer a few questions regarding the generated output.
This page introduces the annotations provided by swagger-core. They are grouped into three - the annotation to declare the resource, the set of annotations to declare an operation, and the set of annotations that declare API models.
The documentation for each annotation is meant as an overview of its usage. Each annotation also has links to its javadocs (both on the header and at the end of the overview). The javadocs provide you with additional information about each annotation, especially dealing with some edge cases.
At the very least:
@Api is required to declare an API resource.
@javax.ws.rs.Path is required at class level (since v1.5.8) to have Swagger scan root resoure, in compliance with JAX-RS spec.
Without having those two combined, no output will be generated, unless scanAllResources config option is not set, in which case also @Path annotatied classes with no @Api annotation will be scanned.
Servlets require @ApiImplicitParam to define the method parameters whereas JAX-RS based application can utilize the basic @XxxxParam annotations ( @QueryParam , @PathParam ...).
The following table summarizes parsing behaviour depending on annotations and ReaderConfig.scanAllResources value
NOTE : in version 1.5.8 only, @Api annotation is not needed to have class scanned, @Path is sufficient, according to the following table:
Table of contents:
Resource API Declaration
Operation declaration, model declaration, swagger definition, customising the swagger definition.
For your convenience, the javadocs are available as well.
The latest release also adds a number of annotations for adding extensions and metadata at the Swagger Definition level:
In Swagger 2.0, resources were replaced by tags, and this impacts the @Api annotation. It is no longer used to declare a resource, and it is now used to apply definitions for all the operations defined under it.
A JAX-RS usage would be:
In this example, we're saying that the tag for the operations under this class is pet (so they would all be grouped together). Swagger will pick up on the @Produces annotation but you can override this value if you wish.
@Api can also be used to declare authorization at the resource-level. These definitions apply to all operations under this resource, but can be overridden at the operation level if needed. In the example above, we're adding a previously-declared OAuth2 authorization scheme without any scopes. For further details, check the @Authorization annotation.
Instead of using the value() , you can use the tags() property which allows you to set multiple tags for the operations. For example:
Note that in this case, value() would be ignored even if it exists.
The boolean hidden property can be used to entirely hide an @Api even if it declared. This is especially useful when using sub-resources to remove unwanted artifacts.
In swagger-core 1.5.X, description() , basePath() , and position() are no longer used.
For further details about this annotation, usage and edge cases, check out the javadocs .
@ApiOperation
The @ApiOperation is used to declare a single operation. An operation is considered a unique combination of a path and a HTTP method.
The value of the annotation is a short description on the API. Since this is displayed in the list of operations in Swagger-UI and the location is limited in size, this should be kept short (preferably shorter than 120 characters). The notes allows you to give significantly more details about the operations. response is the return type of the method. Notice that the actual method declaration returns a Response but that is a general-purpose JAX-RS class and not the actual response sent to the user. If the returned object is the actual result, it can be used directly instead of declaring it in the annotation. Since we want to return a list of pets, we declare that using the responseContainer . Keep in mind that Java has type erasure, so using generics in the return type may not be parsed properly, and the response should be used directly. The @GET JAX-RS annotation will be used as the (HTTP) method field of the operation, and the @Path would tell us the path of the operation (operations are grouped under the same path, one for each HTTP method used).
The output would be:
@ApiResponses , @ApiResponse
It's a common practice to return errors (or other success messages) using HTTP status codes. While the general return type of an operation is defined in the @ApiOperation , the rest of the return codes should be described using these annotations.
The @ApiResponse describes a concrete possible response. It cannot be used directly on the method or class/interface and needs to be included in the array value of @ApiResponses (whether there's one response or more).
If the response is accompanied with a body, the body model can be described as well (one model per response).
In swagger-core 1.5.X, you can also add description of response headers as seen in the example above.
For further details about this annotation, usage and edge cases, check out the javadocs ( @ApiResponses , @ApiResponse ) .
@Authorization , @AuthorizationScope
These annotations are used as input to @Api and @ApiOperation only, and not directly on the resources and operations. Once you've declared and configured which authorization schemes you support in your API, you can use these annotation to note which authorization scheme is required on a resource or a specific operation. The @AuthorizationScope is specific to the case of an OAuth2 authorization scheme where you may want to specify specific supported scopes.
The @Authorization and @AuthorizationScope translate to the Security Requirement Object .
The behavior between the implementations (JAX-RS, Servlets or otherwise) is the same:
In this case we declare that the addPet operation uses the petoauth authorization scheme (we'll assume it is an OAuth2 authorization scheme). Then using the @AuthorizationScope we fine-tune the definition by saying it requires the add:pet scope. As mentioned above, you can see that @AuthorizationScope is used as an input to @Authorization , and that in turn is used as input to @ApiOperation . Remember, these annotations can only be used as input to @Api and @ApiOperation . Using any of them directly on a class or a method will be ignored.
For further details about this annotation, usage and edge cases, check out the javadocs ( @Authorization , @AuthorizationScope ) .
The @ApiParam is used solely with the JAX-RS parameter annotations ( @PathParam , @QueryParam , @HeaderParam , @FormParam and in JAX-RS 2, @BeanParam ). While swagger-core scans these annotations by default, the @ApiParam can be used to add more details on the parameters or change the values as they are read from the code.
In the Swagger Specification, this translates to the Parameter Object .
Swagger will pick up the value() of these annotations and use them as the parameter name, and based on the the annotation it will also set the parameter type.
Swagger will also use the value of @DefaultValue as the default value property if one exists.
Here we have two parameters. The first, username which is a part of the path. The second is the body, in this case a User object. Note that both parameters have the required property set to true . For the @PathParam, this is redundant as it is mandatory by default and cannot be overridden.
@ApiImplicitParam , @ApiImplicitParams
You may wish you describe operation parameters manually. This can be for various reasons, for example:
- Using Servlets which don't use JAX-RS annotations.
- Wanting to hide a parameter as it is defined and override it with a completely different definition.
- Describe a parameter that is used by a filter or another resource prior to reaching the JAX-RS implementation.
Since there can be several parameters to be included, the @ApiImplicitParams allows for multiple @ApiImplicitParam definitions.
In the Swagger Specification, these translate to the Parameter Object .
When defining parameters implicitly, it's important to set name , dataType and paramType for Swagger's definitions to be proper.
In the above sample we can see a Servlet definition with several parameters. The dataType can be either a primitive or a class name. The paramType can be any of the parameter types that are supported by Swagger (refer to the javadocs or the spec for further details).
For further details about this annotation, usage and edge cases, check out the javadocs ( @ApiImplicitParam , @ApiImplicitParams ) .
@ResponseHeader
If you want to describe a response header, you can simply add it to your @ApiOperation or @ApiResponse , while supplying the name of the header, a description and a type.
For example, in a given response, it would look as follows:
Swagger-core builds the model definitions based on the references to them throughout the API introspection. The @ApiModel allows you to manipulate the meta data of a model from a simple description or name change to a definition of polymorphism.
This translates to the Schema Object in the Swagger Specification.
At its basic functionality, you an use @ApiModel to change the name of the model and add a description to it:
Here we change the name of the model from OriginalModel to DifferentModel.
You can also use @ApiModel to implement model composition, by specifying subtypes like:
An example of this scenario is available in swagger-samples:
https://github.com/swagger-api/swagger-samples/blob/master/java/java-jaxrs/src/main/java/io/swagger/sample/model/Pet.java
https://github.com/swagger-api/swagger-samples/blob/master/java/java-jaxrs/src/main/java/io/swagger/sample/model/Vehicle.java
@ApiModelProperty
While swagger-core will introspect fields and setters/getters, it will also read and process JAXB annotations. The @ApiModelProperty allows controlling Swagger-specific definitions such as allowed values, and additional notes. It also offers additional filtering properties in case you want to hide the property in certain scenarios.
This is a simple example of adding a short description to the model property. It can also be observed that while status is a String, we document it as having only three possible values.
The output of it would be:
@SwaggerDefinition
The SwaggerDefinition annotation provides properties corresponding to many (but not all) top-level properties of the Swagger object, allowing you to set these for your auto-generated definition. The annotation can be on any class scanned during the Swagger auto-configuration process, i.e. it does not have to be on a JAX-RS API class but could just be on a marker/config interface, for example:
The properties shown above will result in the corresponding metadata to be added to the generates swagger.json / swagger.yaml file
If you have multiple @SwaggerDefinition annotations they will be aggregated in the order they are found - any duplicate annotation properties will overwrite previous ones.
The @Info annotation adds general metadata properties for a Swagger definition - corresponding to the Info object in the specification. As in the example above:
See the javadoc for a complete list of supported properties.
The @Contact annotation adds contact properties to the @Info section of a Swagger definition - corresponding to the Contact object in the specification. As in the example above:
See the javadoc for a list of supported properties.
The @License annotation adds license properties to the @Info section of a Swagger definition - corresponding to the License object in the specification. As in the example above:
The extension annotation allows for adding of extension properties to a Swagger definition. It is currently supported within the @ApiOperation, @Info and @Tag annotations. There are two ways to use it:
which will result in the following json:
The property name will automatically be prefixed with "x-" if it isn't done so explicitly in the annotation.
Alternatively you can name the extension:
which wraps the contained extension properties in a JSON object.
@ExtensionProperty
An individual property within an extension - see previous @Extension section for examples.
If you for any reason want to customise the generated Swagger definition beyond what is possible with the annotations, you can provide the Swagger engine with a ReaderListener that provides the corresponding callbacks:
Any class found during resource scanning with this annotation will be instantiated and invoked correspondingly. For example the following class:
Would allow you to override the generated basePath from a system-property.

Java Guides
Search this blog.
Check out my 10+ Udemy bestseller courses and discount coupons: Udemy Courses - Ramesh Fadatare
Swagger Annotations for Rest API Documentation
Quick annotation overview, @apioperation, @apiresponses, @apiresponse, @authorization, @authorizationscope, @apiimplicitparam, @apiimplicitparams.
- Using Servlets which don't use JAX-RS annotations.
- Wanting to hide a parameter as it is defined and override it with a completely different definition.
- Describe a parameter that is used by a filter or another resource prior to reaching the JAX-RS implementation.
@ApiModelProperty
Check out usage of these annotations in this article - Spring Boot 2 RESTful API Documentation with Swagger 2 Tutorial
Post a Comment
Leave Comment
Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub
Frame Alert
This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version .

IMAGES
VIDEO
COMMENTS
1. Overview In this tutorial, we'll learn how to modify the Swagger API Response. First, we'll start with some explanations of the OpenAPI Specification and Swagger API Response. Then, we'll implement a simple example using Spring Boot to document a spring REST API using OpenApi 3.0.
Now it's working with this annotation: @ApiResponse (responseCode = "200", content = @Content (array = @ArraySchema (schema = @Schema (implementation = LocationResponse.class))), description = "Get location information"),. Thanks! - Fel Jan 31, 2020 at 11:31
summary: Get all users responses: '200': description: A list of users content: application/json: schema: $ref: '#/components/schemas/ArrayOfUsers' application/xml: schema: $ref: '#/components/schemas/ArrayOfUsers' text/plain: schema: type: string # This operation returns image
Annotation Type ApiResponse @Target ( value = METHOD ) @Retention ( value = RUNTIME ) public @interface ApiResponse Describes a possible response of an operation. This can be used to describe possible success and error codes from your REST API call.
1. Overview In this tutorial, we'll demonstrate how to use Swagger annotations to make our documentation more descriptive. First, we'll learn how to add a description to different parts of the APIs, like methods, parameters, and error codes. Then we'll see how to add request/response examples. 2. Project Setup
Annotation Type ApiResponses. @Target ( value = { METHOD, TYPE }) @Retention ( value = RUNTIME ) public @interface ApiResponses. A wrapper to allow a list of multiple ApiResponse objects. If you need to describe a single ApiResponse, you still must use this annotation and wrap the @ApiResponse in an array. See Also:
7 Answers Sorted by: 19 I am using swagger 2 and following resolved this problem for me. Remove ' response ' property from both @ApiResponse and @ApiOperation.
1 Answer Sorted by: 5 You need to annotate your Rest method with @ApiResponses and @ApiResponse. For example
This page introduces the annotations provided by swagger-core. They are grouped into: Quick Annotation Overview OpenAPI Operation Media Security Extensions Other The documentation for each annotation is meant as an overview of its usage. Each annotation also has links to its javadocs (both on the header and at the end of the overview).
In order to generate the Swagger documentation, swagger-core offers a set of annotations to declare and manipulate the output. The swagger-core output is compliant with Swagger Specification.
200: description: OK Response Media Types An API can respond with various media types. JSON is the most common format for data exchange, but not the only one possible. To specify the response media types, use the produces keyword on the root level or operation level. The global list can be overridden on the operation level. produces:
The annotation may be used at method level or as field of Operation to define one or more responses of the Operation.. swagger-jaxrs2 reader engine considers this annotation along with method return type and context as input to resolve the OpenAPI Operation responses.
The annotation that may be used to populate OpenAPI Object fields info, tags, servers, security and externalDocs If more than one class is annotated with OpenAPIDefinition, with the same fields defined, behaviour is inconsistent. Operation - Annotation Type in io.swagger.v3.oas.annotations.
Swagger provides various annotations that can help us document REST API. Moreover, it provides the @Operation and @ApiResponse annotations to document responses for our REST API . In the remainder of this tutorial, we'll use the below controller class and see how to use these annotations:
The boolean hidden property can be used to entirely hide an @Api even if it declared. This is especially useful when using sub-resources to remove unwanted artifacts. In swagger-core 1.5.X, description (), basePath (), and position () are no longer used. For further details about this annotation, usage and edge cases, check out the javadocs.
Ryan Pinkham November 05, 2018 We recently held a free Swagger training, Adding Swagger to Your Existing APIs: How to Automate a 'Code First' to OAS at Scale, in which we looked at different tools and strategies for generating and hosting an OpenAPI Specification (OAS) for existing APIs.
209 1 2 12 What do you mean by the right parameter for the "responseContainer"? Did you refer the comment here? - Debargha Roy Jun 18, 2021 at 13:13 I want the "Building.class" inside a "Pageable.class" So that in Swagger the example looks like that above: ``` { "content": [ { "Building": ""} ] } ``` - Petziferum Jun 18, 2021 at 16:11
Let's list all Swagger core annotations that are RESTFul API Documentation in Java. Quick Annotation Overview @Api The @Api is used to declare a Swagger resource API. It serves a double purpose - it affects the Resource Listing and the API Declaration. Only classes that are annotated with @Api will be scanned by Swagger.
a list of response headers. Default: @io.swagger.annotations.ResponseHeader(name="", response=java.lang.Void.class) responseContainer public abstract String responseContainer. Declares a container wrapping the response. Valid values are "List", "Set" or "Map". Any other value will be ignored.