Swagger UI not rendering the correct response(Should return a JSON response)[This is for the GET request Code 200] - spring-boot

Swagger UI is not returning the expected JSON response in the example value. It is returning a empty list.Below are the code snippets I am using,
Gradle Dependency
compile('io.springfox:springfox-swagger-ui:2.9.2')
compile('io.springfox:springfox-swagger2:2.9.2')
Swagger Config
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(HttpServletResponse.class)
.select() .apis(RequestHandlerSelectors.basePackage("com.core.controller.v2"))
.paths(PathSelectors.any())
.build()
.enable(true)
.apiInfo(apiInfo())
.securityContexts(Lists.newArrayList(securityContext()))
.securitySchemes(Lists.newArrayList(apiKey()));
Controller
#ApiOperation(value="A GET request to get a list of all contents for a given user.",
notes = "This API is used to get the contents for a given user with an NPI and Partner ID",
response = CoreContentItem.class)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Success response", response = CoreContentItem.class,responseContainer = "List"),
#ApiResponse(code = 401, message = "Unauthorized"),
#ApiResponse(code = 400, message = "Bad Request",responseContainer = "String"),
#ApiResponse(code = 403, message = "Forbidden"),
#ApiResponse(code = 500, message = "Internal Server Error, please contact system administrator")})
Swagger Output
Swagger UI for success Response
Expected JSON response
This is a sample expected JSON response
[
{
"item": {
"id": "3f94ea1a687dda4af3e2",
"category": null,
"type": "EXTERNAL",
"headline": "DO NOT DELETE - REST ASSURED All - HIGH - JV",
"summary": "DO NOT DELETE - All - HIGH - JV",
"details": null,
"mediaURL": "",
"createdOn": 1493658088000,
"modifiedOn": 1495553312000,
"priority": "HIGH",
"startDate": 1493618400000,
"endDate": 1588312800000,
"feedbackEmail": null,
"totalLikes": 0,
"totalViews": 2,
"customData": null,
"userInteraction": {
"userLiked": false,
"userDisliked": false,
"userViewed": false
},
"availableActions": [
"View",
"Done",
"Submit"
],
"externalURL": "https://www.1234.com/vegetables/armando%25e2%2580%2599s-chiles-rellenos/r/5014"
}
}
]

I found the issue. Apparently it was a model mapping exception that made the Swagger UI to return an empty list. Now I am able to see the model in example value.
enter image description here

Related

Fluent Validation and ASP.NET Core 6 Web API

I am new to fluent validation and also a beginner in Web API. I have been working on a dummy project to learn and your advice will be much appreciated. After following the FluentValidation website, I was able to successfully implement fluent validation.
However, my response body looks very different and contains a lot of information. Is it possible to have a regular response body with validation errors?
I will put down the steps I took to implement fluent validation. your advice and help are much appreciated. I am using manual validation because based on the fluent validation website they are not supporting the auto validation anymore.
In the program file, I added
builder.Services.AddValidatorsFromAssemblyContaining<CityValidator>();
Then I added a class that validated my City class which has two properties Name and Description:
public class CityValidator : AbstractValidator<City>
{
public CityValidator()
{
RuleFor(x => x.Name)
.NotNull()
.NotEmpty()
.WithMessage("Please specify a name");
RuleFor(x => x.Description)
.NotNull()
.NotEmpty()
.WithMessage("Please specify a Description");
}
}
In my CitiesController constructor I injected Validator<City> validator; and in my action, I am using this code:
ValidationResult result = await _validator.ValidateAsync(city);
if (!result.IsValid)
{
result.AddToModelState(this.ModelState);
return BadRequest(result);
}
The AddToModelState is an extension method
public static void AddToModelState(this ValidationResult result, ModelStateDictionary modelState)
{
if (!result.IsValid)
{
foreach (var error in result.Errors)
{
modelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
}
}
On post, I am getting the response as
{
"isValid": false,
"errors": [
{
"propertyName": "Name",
"errorMessage": "Please specify a name",
"attemptedValue": "",
"customState": null,
"severity": 0,
"errorCode": "NotEmptyValidator",
"formattedMessagePlaceholderValues": {
"PropertyName": "Name",
"PropertyValue": ""
}
},
{
"propertyName": "Description",
"errorMessage": "Please specify a name",
"attemptedValue": "",
"customState": null,
"severity": 0,
"errorCode": "NotEmptyValidator",
"formattedMessagePlaceholderValues": {
"PropertyName": "Description",
"PropertyValue": ""
}
}
],
"ruleSetsExecuted": [
"default"
]
}
While the regular response without Fluent Validation looks like this:
{
"errors": {
"": [
"A non-empty request body is required."
],
"pointofInterest": [
"The pointofInterest field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-1a68c87bda2ffb8de50b7d2888b32d02-94d30c7679aec10b-00"
}
The question: is there a way from the use the fluent validation and get the response format like
{
"errors": {
"": [
"A non-empty request body is required."
],
"pointofInterest": [
"The pointofInterest field is required."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-1a68c87bda2ffb8de50b7d2888b32d02-94d30c7679aec10b-00"
}
Thank you for your time.
Updated ans:
with your code, you can simply replace.
return BadRequest(result); // replace this line with below line.
return ValidationProblem(ModelState);
then you get same format as required.
------------------------*----------------------------------------
Please ignore this for manual validation.
You don't need explicit validation call.
this code is not required:
ValidationResult result = await _validator.ValidateAsync(city);
if (!result.IsValid)
{
result.AddToModelState(this.ModelState);
return BadRequest(result);
}
it will auto validate the model using your custom validator.
you simply need this
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
and it will give you errors in the require format.
if(!result.IsValid)
{
result.AddToModelState(this.ModelState);
return ValidationProblem(ModelState);
}

validate response using jsr223 assertion

I have passed chgId as parameter in the get HTTP request.
https://*****?chgId=405
My api response is coming as -
{
"response": {
"data": [
{
"tid": 3697,
"chgId": 405,
"amount": 8.5,
"Currency": "USD",
},
{
"tid": 3698,
"chgId": 405,
"amount": 3.33,
"Currency": "USD",
}
]
}
}
Now from the response I want to validate in JSR223 assertion that the response is correct based on the chgId field. That means in both 'data' array "chgId": 405 text should come.
Can anyone suggest?
You could do something like:
def params = org.apache.http.client.utils.URLEncodedUtils.parse(prev.getURL().toURI(), 'UTF-8')
def expected = params.find { 'chgId' }.value as int
def actual1 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[0].chgId
def actual2 = new groovy.json.JsonSlurper().parse(prev.getResponseData()).response.data[1].chgId
def success = (expected == actual1 && expected == actual2)
if (!success) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('chgId mismatch')
}
where prev stands for previous SampleResult
More information:
URLEncodedUtils JavaDoc
JsonSlurper
Apache Groovy - Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

How I can return my custom json file instead of default json file that generates spring boot?

I have a rest controller for authorization:
#RestController
class AuthController {
#PostMapping("/sign-up")
fun signUp(#RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> {
some code here..
}
}
The signUp method gets SignUpRequest model as a request body. SignUpRequest model is:
enum class Role {
#JsonProperty("Student")
STUDENT,
#JsonProperty("Tutor")
TUTOR
}
data class SignUpRequest(
val role: Role,
val email: String,
val password: String
)
When I make /sign-up post request with JSON:
{
"role": "asdf",
"email": "",
"password": ""
}
It returns me an answer that were generated by spring boot:
{
"timestamp": "2020-02-12T05:45:42.387+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]\n at [Source: (PushbackInputStream); line: 3, column: 10] (through reference chain: foo.bar.xyz.model.SignUpRequest[\"role\"])",
"path": "/sign-up"
}
Question is: How I can return my custom JSON instead of that default generated JSON?
I want to return my custom JSON, like:
{
"result": "Invalid user data are given",
"errors": [
{
"fieldName": "ROLE",
"text": "Given role does not exist"
},
{
"fieldName": "EMAIL",
"text": "EMAIL is empty"
}
]
}
I suggest you to create ErrorContrller that generates custom json map as response. Then when you will catch an error in sign-up method, call ErrorContrllers method.
You can find info from this link
Finally I found out a solution. You should create a class that annotates #ControllerAdvice, and make a method that annotates #ExceptionHandler.
#ControllerAdvice
class HttpMessageNotReadableExceptionController {
#ExceptionHandler(HttpMessageNotReadableException::class)
#ResponseBody
#ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleException(
exception: HttpMessageNotReadableException
): PostSignUpResponseError {
val errors = mutableListOf<PostSignUpResponseErrorItem>()
errors.add(
PostSignUpResponseErrorItem(
fieldNamePost = "Role",
text = "Given role does not exist"
)
)
return PostSignUpResponseError(
result = "Invalid user data are given",
errors = errors
)
}
}
where PostSignUpResponseErrorItem and PostSignUpResponseError are:
data class PostSignUpResponseError(
val result: String,
val errors: List<PostSignUpResponseErrorItem>
)
class PostSignUpResponseErrorItem(
val fieldNamePost: PostSignUpRequestFieldName,
val text: String
)
Anyway, I still don't know how to attach this thing to a certain PostMapping method.

Getting image from Sharepoint post with Microsoft Graph

My company has made a custom photo-field in Sharepoint for it's news. I'm trying to use Microsoft Graph to fetch the images, but with no success.
This is the columns description:
{
"columnGroup": "Page Layout Columns",
"description": "",
"displayName": "Thumbnail image",
"enforceUniqueValues": false,
"hidden": false,
"id": "XXXXXXX-XXXX-XXXX-XXX-XXXXXXXXXXXX",
"indexed": false,
"name": "PublishingPageImage",
"readOnly": false,
"required": false
},
In the documentation for Microsoft Graph it is written that you can make a request like this
GET https://graph.microsoft.com/beta/sites/{site-id}/lists/{list-id}/items?expand=fields(select=Column1,Column2)
Although - no matter how I seem to write the request, i can't get the image field.
My most recent try has been this request:
https://graph.microsoft.com/beta/sites/knowit.sharepoint.com/lists/posts/items?expand=fields(select=PublishingPageImage)
The respons I got from Microsoft was this:
{
"error": {
"code": "-1, Microsoft.SharePoint.Client.ClientServiceException",
"message": "Cannot serialize data for type Microsoft.SharePoint.Publishing.Fields.ImageFieldValue.",
"innerError": {
"request-id": "f25e4851-0c1b-4061-ad6a-948d38004046",
"date": "2018-09-17T14:03:01"
}
}
}
Should I use something like .value or .data or .ImageUrl after the request? If i get a link or a data-value doesn't really matter. In the call for /me/ for Microsoft users there is a $value property for getting the user profile photo. Is it something like this?
It depends how image is stored.
If it is attachment you can do following:
string baseURL = $"https://{spTenant}/_api/web/lists('{ AA.config.listID}')/items({ siteData.Id})/AttachmentFiles";
string fileName = await GetFileNameAsync(baseURL);
string getPictureReqUrl = $"{baseURL}('{fileName}')/$value";
Stream responseStream = await GetPictureAsync(getPictureReqUrl);
private static async Task<Stream> GetPictureAsync(string reqUrl)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", SPOToken);
HttpResponseMessage response = await client.GetAsync(reqUrl);
return await response.Content.ReadAsStreamAsync();
}
Important! This is not supported by graph yet, but you can use SharePoint Rest API
If picture is stored in document library you need to use Drive object instead
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/drive

HttpMediaTypeNotAcceptableException when application/json-patch+json is used as 'Content-Type' header

we are using patch operation to support partial update.
#ApiOperation(value="Patch (Partial Update) user payment")
#RequestMapping(method = RequestMethod.PATCH, consumes = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<UserPaymentInfo> patchPaymentInfo(#ApiParam(value = "The user id", required = true)#PathVariable final String uid,
#ApiParam(value = "Whether to reteurn new payment info back") #RequestParam(name = "includeResponse", defaultValue = "false") final boolean includeResponse,#ApiParam(value = "Description of changes")#RequestBody final String userPaymentInfoPatchJson) {
UserPaymentInfo paymentInfo = userPaymentService.patchPaymentInfo(uid,userPaymentInfoPatchJson,includeResponse);
HttpStatus status = includeResponse ? HttpStatus.OK : HttpStatus.NO_CONTENT;
return new ResponseEntity<>(paymentInfo,status);
}
Below mentioned is exception :
{"code": "0000",
"message": "Could not find acceptable representation (HttpMediaTypeNotAcceptableException)",
"host": "localhost",
"url": "/users/000020800464/paymentinfo/test",
"method": "PATCH",
"causes": [
{
"code": "0000",
"message": "Could not find acceptable representation (HttpMediaTypeNotAcceptableException)"
}
]
}
The same endpoint works good for application/json as header value of Content-Type but 'application/json-patch+json' fails.
Does spring boot support patch bcs i am not able to find related header name mentioned in org.springframework.http.MediaType.java

Resources