Swagger validation for request parameter and custom error message - validation

I need a help regarding swagger validation with spring boot.
In Req1 it is not showing the field name, could you help with this? Also how to give custom error message for any validations?
Update:
In the response of the req1 is not showing field name(productCode) in message but in response of req2 we could see the field name.
type: object
description: get details request object
required: [productCode]
properties:
productCode:
type: string
minLength: 1
description: Identifier for application
--Req1-----
{
"productCode":""
}
--Res1-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: string \"\" is too short (length: 0, required minimum: 1)"
}
--Req2-----
{ }
--Res2-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: object has missing required properties ([\"productCode\"])"
}

Related

nestjs-i18n in DTO validation just throw bad request error

im using nestjs-i18n in my dto and it just throw bad request error instead of my error messsage.
this is my dto:
export class SignUpDto{
#ApiProperty()
#MinLength(5, {
message: i18nValidationMessage('i18n.MIN', {message: 'err'})
})
username:string;
}
and i18n.json file:
{
"MIN": "You need to write at least 5 letter"
}
but this is the error in swagger:
{
"statusCode": 400,
"message": "Bad Request"
}
what is the problem?

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);
}

How to match objects in an array in no particular order in JsonPath?

I am working with Spring and MockMvc. I'm writing a unit test for a specific controller response. It looks something like this:
{
"errors": [
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym."
},
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull."
}
]
}
There is no guarantee of the order of the array errors. This is partly because of Spring's SmartValidator. I would like to check if both objects are in the the array, regardless of order.
Here is my code now:
mvc.perform(post("/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(validExampleUserRegistrationDtoBuilder().addressLine1(null).pseudonym("oyasuna").build())))
.andDo(result -> System.out.println(result.getResponse().getContentAsString()))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.errors.length()").value(2))
.andExpectAll(
jsonPath("$.errors[0].error").value("Bean validation failed."),
jsonPath("$.errors[0].message").value("Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull.")
)
.andExpectAll(
jsonPath("$.errors[1].error").value("Bean validation failed."),
jsonPath("$.errors[1].message").value("Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym.")
);
Use containsInAnyOrder to verify (use your required json path)
andExpect(jsonPath("$
.message", containsInAnyOrder("1-st expected message", "2-nd expected message")))
.andExpect(jsonPath("$
.error", containsInAnyOrder("1-st expected error, "2-nd expected error")))

Golang GMAIL API 400: Invalid label:

Using Gmail API to read my mailbox. The message reading process is working as expected but I want to change the label of reading messages just for acknowledgment purposes so that I can have track of the reading messages list in my Gmail inbox only. Tried given two methods to change the label but non of them worked for me. Need suggestion on the same
Methods:
Codebase is written in Golang (as a backend)
Tried with Google API Explorer
(METHOD 1) -
Go sample code:
gmsg: = gmail.ModifyMessageRequest {
RemoveLabelIds: [] string {
"INBOX". //system defined label
},
AddLabelIds: [] string {
"INBOXING" //my custom label. created through Gmail
},
}
_, errDelete: = gService.Users.Messages.Modify("me", messageid, &gmsg).Do()
if (errDelete != nil) {
logs.Error("GMAIL SERVICE ERROR:: for [", accountEmail, "] while moving message to [INBOXING] folder ", errDelete.Error())
}
Got below error :
{"level":"error","msg":"GMAIL SERVICE ERROR:: for [sample#gmail.com] while moving message to [INBOXING] folder googleapi: Error 400: Invalid label: INBOXING, invalidArgument","time":"2021-08-09 20:05:13"}
(METHOD 1) -
Gmail Modify API
Payload
{
"addLabelIds": [
"INBOXING"
],
"removeLabelIds": [
"INBOX"
]
}
Response from Google API -
{
"error": {
"code": 400,
"message": "Invalid label: INBOXING",
"errors": [
{
"message": "Invalid label: INBOXING",
"domain": "global",
"reason": "invalidArgument"
}
],
"status": "INVALID_ARGUMENT"
}
}
Observation - *
On modifying message with custom label's Gmail API return's 400 bad
request, but if we request with system labels it allows us to modify
the label.
You are using the label name instead of label id. To obtain the label id, you have to use the Method: users.labels.list
Response:
Once you have the ID, you can now use it in Method: users.messages.modify
Request body:
Response:

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.

Resources