I try to build my first api. I got problem when i want to register new user. The problem is when i want to send request from postman. I using also SwaggerUI, so when i use Post Request to my end point /registration in SwaggerUI by textfields always i got http status 201 so its works good. Problem is when i want to make Mock to this controller or when i want to send new user in postman request but not always. I show you in example
If i use postman -> post: localhost:8080/registration -> Raw -> JSON
{
"email": "testtest#gmail.com",
"id": 0,
"password": "Test1234567 ",
"username": "testtest"
}
Then i got message
{
"status": "BAD_REQUEST",
"timestamp": "01-03-2021 11:44:26",
"message": "Value cannot be empty!",
"debugMessage": null,
"subErrors": null
}
So its should be good because i used catch exception. But Value isnt empty, so whats happend?I dont know.
But when i go to x-www-form-urlencoded and there i put keys: email, username and password then, user is created!
Another, when im put this same info to Swagger then also my user is created.
Below i add my code from controller and test.
#Test
void shouldCreateNewUser() throws Exception {
UserRegistrationDto user = new UserRegistrationDto( null,"seba12345", "lelelele1908#gmail.com", passwordEncoder.encode("Respeck123"));
mockMvc.perform(post("/registration")
.header("header1", "1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isCreated());
}
#PostMapping("/registration")
public ResponseEntity<UserRegistrationDto> registerUser(UserRegistrationDto userRegistrationDto) {
HttpHeaders headers = new HttpHeaders();
userService.save(userRegistrationDto);
return new ResponseEntity<>(userRegistrationDto, headers, HttpStatus.CREATED);
}
You need #RequestBody in your controller method to tell Spring that you want the content of the request body:
#PostMapping("/registration")
public void post(#RequestBody MyDTO dto) {
...
}
Related
public String deleteProduct(#RequestBody String prodId ,HttpServletRequest request ) throws NotLoggedInException {
String userName = (String) request.getSession().getAttribute("user");
System.out.println(userName);
if (userName == null) {
throw new NotLoggedInException("You have not logged in");
}
String userRole = (String) request.getSession().getAttribute("role");
if (!userRole.equalsIgnoreCase("productmaster")) {
throw new AuthorizedUserRoleNotFoundException("you are not authorized to add the products");
}
if(pservice.deleteProduct(prodId))
{
return "Product deleted";
}
return "Product not deleted";
}
Output:
{
"timestamp": "2022-11-20T13:17:24.172+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public java.lang.String"
}
Please tell someone why its showing like this
#Requestbody annotation requires you to pass some request body in json, map form. But you are just passing prodId. I think you should just change #RequestBody annotation.
(#Request Param prodId ,#Requestbody HHttpServletReques request)
The #RequestBody annotation comes with the required attribute defaulting to true. This means that the request should always contain a body, otherwise it will throw an exception. From the error message it appears that your request does not contain a body.
You need to either set the required attribute to false or always provide a body.
I am getting below response when I am calling an API.
Response postRequestResponse = ConnectionUtil.getwebTarget()
.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
.path("bots")
.path(ReadSkillID.readSkillId())
.path("dynamicEntities").path(dynamicEntityID)
.path("pushRequests").path(pushRequestID).path(operation)
.request()
.header("Authorization", "Bearer " + ConnectionUtil.getToken())
.get();
Below output I am getting.
{
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I have to return this output to client with an additional field in the response. How can modify the above response and make it
{
"EntityName": "NewEntity", //New field
"createdOn": "2020-08-17T12:19:13.541Z",
"updatedOn": "2020-08-17T12:19:23.421Z",
"id": "C84B058A-C8F9-41F5-A353-EC2CFE7A1BD9",
"status": "TRAINING",
"statusMessage": "Request Pushed into training, on user request"
}
I am adding this additional field here
"EntityName": "NewEntity"
How can I do that. many things I tried but got exception.
get JSON from postRequestResponse (i have no idea what framework you are using, so you have to figer it out on your own, but the Response datatype will probably have a getResponseBody or similar method returing the JSON)
add EntityName
serialize it again to json.
class YourBean {
#Autowired
private ObjectMapper objectMapper;
public void yourMethod() {
// 1
final InputStream jsonFromResponse = ...
// 2
Map dataFromResponse = objectMapper.readValue(jsonFromResponse, Map.class);
dataFromResponse.put("EntityName", "NewEntity");
// 3
final String enrichedJson = objectMapper.writeValueAsString(dataFromResponse);
}
}
enrichedJson contains EntityName and whatever comes from the API.
#PostMapping
public UserResponse createUser(#RequestBody UserRequest userDetail) {
UserResponse returnValue = new UserResponse();
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetail, userDto);
UserDto storedData = userService.createUser(userDto);
BeanUtils.copyProperties(storedData, returnValue);
return returnValue;
}
this is the code I am getting this error
{
"timestamp": "2020-05-13T12:24:04.866+0000",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported",
"path": "/users"
}
I have tried a lot of different ways still not getting the solution
This is the image from the postman
image from postman
Are you using Postman to fire the request? you might want to check these settings
Edit. Add another image for troubleshooting
That because your service is only accepting application/json content type. If you want to accepting application/x-www-form-urlencoded you can add consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE inside #PostMapping annotation
bellow is sample of service that accept application/json and give application/json response.
#PostMapping(path = "/v1/agent/create", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ApiResponseWrapperDto createAgent(#RequestBody ApiRequestWrapperDto request) throws Exception {
return this.agentManagementApiHandler.createAgent(request);
}
Hope this solve your problem.
Thanks
I am trying to consume api with two different responses. when providing proper input and headers, it gives one json object. That is working fine with code given below.
but when one of the inputs or headers are missing then api is returning other json which states error details while hitting through Postman but same is not getting achieved by client code. It throws exception but api should return json with error details.
first I tried with postForobject(), then changed to exchange() assuming postForObject returning object and api is not getting expected object format. so tried with String.clas instead of particular class
what can be done to get two different json object by hitting same url?
when success:
{
"contacts": [
{
"input": "98########",
"status": "valid"
}
]
}
when input or header missing:
"errors": [
{
"code": 1###,
"title": "Access denied",
"details": "invalid deatils"
}
]
below is my code:
public static void main(String[] args) throws Exception {
RestTemplate restTemplate = new RestTemplate();
String check_Contact_Async = "https://port/contacts/";
sslByPass();
//headers = setHeaders();
contactsDTO = getInput();
final HttpEntity<ContactsDTO> entity = new HttpEntity<ContactsDTO>(contactsDTO, headers);
try {
//WsResponse res = restTemplate.postForObject(check_Contact_Async, entity, WsResponse.class);
ResponseEntity<String> responseEntity = restTemplate.exchange(
check_Contact_Async, HttpMethod.POST, entity,
String.class);
System.out.println(responseEntity);
} catch (Exception exception) {
System.out.println(exception);
}
}
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:498)
at com.websystique.springmvc.apitest.Example.main(Example.java:120)
any clue will be helpful
Thanks
I need to invoke a form-data typed API using Rest Assured. Here is my code.
private Map<String, String> getFormParamsMap() {
Map<String, String> formParams = new HashMap<>();
formParams.put("creatorId", "Instructor1");
formParams.put("creatorPlatform", "Web");
formParams.put("creatoredSource", "File");
formParams.put("creatoredType", "Auto");
formParams.put("deckId", "5a605b472e02d86561172dad");
formParams.put("userId", "kind");
return formParams;
}
public void invoke() {
response = given()
.header("Content-Type", "application/form-data")
.header(AUTHORIZATION_HEADER_NAME, accessToken) //Some API contains access token to run with the API
.headers(headers)
.formParams(getFormParamsMap()) // requestParamsMap here.
.when()
.post(invokingEndpoint);
}
When I execute this, I am getting the below error.
Message: java.lang.IllegalArgumentException: Don't know how to encode creatorPlatform=Web&creatoredType=Auto&deckId=5a605b472e02d86561172dad&creatorId=Instructor1&creatoredSource=File&userId=kind as a byte stream.
Please use EncoderConfig (EncoderConfig#encodeContentTypeAs) to specify how to serialize data for this content-type.
For example: "given().config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs("application/form-data", ContentType.TEXT))). .."
Stack Trace:
io.restassured.internal.http.EncoderRegistry.encodeStream(EncoderRegistry.java:130)
When I use .config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs("application/form-data", ContentType.TEXT))) in the invoke() method, it gives the result as below.
{
"status": 400,
"message": "Content type 'application/x-www-form-urlencoded;charset=ISO-8859-1' not supported",
"error": "Bad Request",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException"
}
My request is not x-www-form-urlencoded type, it is form-data type. I can execute it using postman.
Appreciate your support on this.
Thanks.
I have solve this issue by using encodeContentTypeAs("multipart/form-data", ContentType.TEXT)
Ex:-
public void invoke() {
response = given()
.config(
RestAssured.config()
.encoderConfig(
encoderConfig()
.encodeContentTypeAs("multipart/form-data", ContentType.TEXT)))
.headers(headers)
.formParams(formParams)
.when()
.post(oAuthBaseURI).then().extract().response();
}
Please add the consumer as well.
See here for the encoders available for Rest Assured.
This might be causing the problem -
encodeContentTypeAs("application/form-data", ContentType.TEXT)
You can also try this -
.encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false).encodeContentTypeAs("application/form-data", ContentType.TEXT));
As far as I can tell, headers(headers) method replaces all headers, and then RestAssured uses x-www-form-urlencoded content type as default.
Try adding "Content-Type" header after the call to headers(headers).