{title:'@Response Beans', updated:'8.1.0,9.0.0'}

The {@link oaj.http.annotation.Response} annotation can be used to define beans that return HTTP response parts via annotations and methods. They are used in combination with the following annotations:

- {@link oaj.http.annotation.StatusCode}
- {@link oaj.http.annotation.Header}
- {@link oaj.http.annotation.Content}
- {@link oaj.http.annotation.Schema}

Response beans can either be returned or thrown from {@link oajr.annotation.RestOp @RestOp}-annotated methods.

- As a general convention, response beans with return codes <400 should be defined as regular classes and >=400 should be defined as exceptions.

The following example shows the @Response annotation used to define an exception for an invalid login attempt:

| // Our annotated normal response. | @Response | @StatusCode(200) | @Schema( | description="User was good." // Description show in Swagger | ) | public class ValidLogin { | public ValidLogin() { | ... | } | | // Response bean converted to output based on Accept header. | @Content | public WelcomeMessageBean getContent() { | return new WelcomeMessageBean(); | } | }

| // Our annotated exception. | @Response | @StatusCode(401) | @Schema( | description="Invalid username or password provided" // Description show in Swagger | ) | public class InvalidLogin extends Exception { | public InvalidLogin() { | super("Invalid username or password."); // Message sent in response | } | | @Header("My-Message") | public String getMyMessage() { | return "Nope!"; | } | }

| // Our REST method that throws an annotated exception. | @RestGet("/user/login") | public ValidLogin login( | @FormData("username") String username, | @FormData("password") String password | ) throws InvalidLogin | { | if (isValid(username, password)) { | return new ValidLogin(); | } | throw new InvalidLogin(); | }

Custom exceptions can also extend from one of the predefined HTTP exceptions such as the {@link oaj.http.response.Unauthorized} exception:

| // Our annotated exception. | @Response | @Schema( | description="Invalid username or password provided" // Overridden from parent class | ) | public class InvalidLogin extends Unauthorized { | public InvalidLogin() { | super("Invalid username or password."); | } | } | | // Parent predefined exception class. | @Response | @StatusCode(401) | @Schema( | description="Unauthorized" | ) | public class Unauthorized extends RestException {...}