I am making app with Rest Services and i want to handle the exceptions and status code.
When i send the correct parametars to Postman i get the response and the status code is 202 OK so that is good.
When i send the first parameter correct and for seccond i send some chars i get status code 400 Bad Request and some message so that is good too.
But, when i send the first parameter correct and in the seccond i delete one number i am getting Status: 404 Not Found (Which is correct) and blank page in Postman without some message.
So my question is:
Is that alright to get only status code 404 and blank page or i need to change something in the code to get the message too.
My second question is about Internal Server Error 500. How can i implement it and how to test it?
#CrossOrigin
#RequestMapping(value = "/blaa/{startDate}/{endDate}", method = RequestMethod.GET)
public ResponseEntity<List<Nodes>> listsOfbla(#PathVariable Long startDate,
#PathVariable Long endDate) {
startEndDateRequestTotal.inc();
List<Nodes> listOfbla= NodesService.getFromToData(startDate, endDate);
LOG.info("GET Request was made with two paramaters ", startDate, endDate);
for (int i = 0; i < listOfbla (); i++) {
if (listOfbla(i).getStampm().equals(startDate)) {
for (int j = 0; j < listOfbla (); j++) {
if (listOfbla(j).getStampm().equals(endDate)) {
return new ResponseEntity<List<Nodes>>listOfbla HttpStatus.OK);
}
}
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
if (listOfbla.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
LOG.info("Retruning Nodes objects from specified date");
return new ResponseEntity<List<Nodes>>(listOfbla, HttpStatus.OK);
}
For your first question:
That is enough you receive the status code and you can make for example.
If status code = 404 send me this message.
Related
I Have a RESTful web service created using Java connected to a db containing cars and implamenting CRUD operations and testing using Postman.
Currently it just uses the conventional HTTP GET returning status 200ok when a car in the database is returned successfully.
I am trying now to implement a conditional GET to return status 304 when a second GET request is submitted and the entity has not been modified from the previous GET request.
Reading about the conditional GET i know it uses the Last-modified and if-modified-since headers but struggling on how to go about implementing this.
Within the db i have a trigger to update a TIMESTAMP associated with each entity after they have been modified and i presume this will be the value that will be checked to see if the entity has been modified since the last request ?
Any Help appreciated
The Current GET request:
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{reg}")
public Response getOneCar(#PathParam("reg") String reg) {
Car car = dao.getCarDetails(reg);
System.out.println("GET CarReg == "+reg);
if(car == null){ // no car with that reg exists
return Response
.status(Response.Status.NOT_FOUND)
.entity("<carNotFound reg='"+reg+"' />")
.build();
}else{
car.setLink(new ArrayList<Link>());
Link linkSelf = new Link();
linkSelf.setRel("self");
linkSelf.setUri(context.getPath());
Link deleteLink = new Link();
deleteLink.setRel("/linkrels/car/delete");
deleteLink.setUri(context.getPath());
Link updateLink = new Link();
updateLink.setRel("/linkrels/car/update");
updateLink.setUri(context.getPath());
car.getLink().add(linkSelf);
car.getLink().add(deleteLink);
car.getLink().add(updateLink);
return Response
.status(Response.Status.OK)
.entity(car)
.build();
}
}
Example of one of the entities:
<car>
<id>3</id>
<regNo>03G333</regNo>
<make>Ford</make>
<model>Focus</model>
<link rel="self" uri="cars/03G333"/>
<link rel="/linkrels/car/delete" uri="cars/03G333"/>
<link rel="/linkrels/car/update" uri="cars/03G333"/>
<time>2018-03-23 10:00:05.772</time>
</car>
Thanks for the response #Andrew,
I am currently trying to do this using the "If-Modified-Since" and "Last-Modified" Headers.
On The server i am sending a "Last-Modified" Header to the client which takes the timestamp from the current car in the db as shown in the image --> postman server responce
Now i am trying to configure postman to send back the "if-Modified-Since" header.
if i compare these values and depending on the timestamp being the same or different i can determine the response to be sent back.
currently having trouble configuring postman to send the "If-Modified-Since" Header and then taking this value in on the Server somehow.
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String lastmodifiedDate = car.getTime();
date = sdf.parse(lastmodifiedDate);
} catch (ParseException ex) {
}
return Response
.status(Response.Status.OK).lastModified(date)
.entity(car)
.build();
}
}
I have a resource in my service with pagination and I would like to know how could I process the next request to get the second page.
Here is the java resource:
#GetMapping(value = "/partner/codes")
public Page<String> getCodes(#PageableDefault(size = 5) Pageable pageable) {
final List<String> userIds = service.getIds();
int start = pageable.getOffset();
int end = (start + pageable.getPageSize()) > userIds.size() ? userIds.size() : (start + pageable.getPageSize());
return new PageImpl<String>(userIds.subList(start, end), pageable, userIds.size());
}
And the response the response with 5 results:
{
"content":[
"4a136aa6-00d4-44f0-bb48-d192fd8bc010",
"bebebaf2-b881-4733-8a65-1ecf80b5192e",
"1a0f9d07-1393-48a8-8883-37d87681e84b",
"d2580fdc-db6c-4fa3-89d4-2b52898a20bf",
"2c90e683-4ed4-45a4-b70b-614a3339670b"
],
"last":false,
"totalPages":3,
"totalElements":57,
"size":20,
"number":0,
"sort":null,
"numberOfElements":20,
"first":true
}
I'm sorry, as there was nothing explicit in the documentation, I hadn't noticed that just passing the parameters in the query string.
?page=2&size=20
And the client should create the rule using the response message.
So I have in my code POST method :
#POST
#Path("/send/{userPost}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#PathParam("userPost") String userPost ) {
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartek Szlapa");
userPosts.add(post);
User user = new User(99,"Bartek","Szlapa",userPosts);
String output = user.toString();
return Response.status(200).entity(output).build();
}
unfortunately its not working. I'm getting 404 error. Server is configured correctly because other methods work perfectly. Funny thing is that when I remove {userPost} , parameter : #PathParam("userPost") String userPost and send empty request : http://localhost:8080/JavaAPI/rest/api/send it works - I'm getting new User object with null at some fields. Do you know why I cannot send parameter ? Thanks in advance for help! :)
What you are sending is not a path parameter to send your value as a path parameter based on your api , let us say you are trying to send "test"
http://localhost:8080/JavaAPI/rest/api/send/test
if you want to use query params
#POST
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#QueryParam("userPost") String userPost ) {
and your request should be
http://localhost:8080/JavaAPI/rest/api/send?userPost=test
Your "userPost" parameter is not in the Path : localhost:8080/JavaAPI/rest/api/send?=test
You defined this path :
#Path("/send/{userPost}")
So, your URI should be :
localhost:8080/JavaAPI/rest/api/send/test
I am using Spring MVC 4. Here is my controller code:
#RestController
public class NewValueController
{
#RequestMapping(value="/receiveUpdatedScore",method=RequestMethod.POST,produces={"application/json"})
public NewValue receiveUpdateScore(#RequestParam(value="score") short score,
#RequestParam(value="user_id") String user_id,
#RequestParam(value="device_model") String device_model,
#RequestParam(value="api_key") String api_key,
#RequestParam(value="gen_t") long gen_t,
Model model)
{
int newScore = (int) score;
NewValue algorithm=new NewValue();
NewValue newvalue=algorithm.getNextValue(newScore);
return newvalue;
}
}
I am making this Request using Advanced rest client(also tried same in Postman):
{"score":"50","user_id":"zyz","device_model":"xiami","api_key":"sasa5454","gen_t":"545666"}
But I am getting following error
Error:
HTTP Status 400 - Required Short parameter 'score' is not present
message: Required Short parameter 'score' is not present
description: The request sent by the client was syntactically incorrect.
What is the mistake I am not able to detect here. Please help me to resolve it.
I think this is because score is expected as part of the url and not some JSON that you post
I have made a REST client-server, and everything works more or less fine. Here is the dilemma: I have an option to retrieve user by its username, which works fine when the user actually exists. However, when he doesn't, i get 204 http code, which is fine, since I made a null return. I would like my method to return a plain string to client console when no user is found, say, "No such user found...", but the method return type is User (class) logically, to return a user object when such is found.
Here is the server side:
#GET
#Path("/{uName}")
#Produces({ "application/json", "application/xml"})
public User getUserByUsername(#PathParam("uName") String uName) {
returnAll = usrList.getUsers();
for (User u : returnAll) {
if (u.getUserName().equals(uName))
return u;
}
return null;
}
And here is the relevant part of client:
case 3:
sc.nextLine();
System.out.println("Enter username");
userName = sc.nextLine();
restConnect("http://localhost:8080/rest/user/"
+ userName, "GET");
promptKey();
Changing a method to return a String type would obviously disrupt the code when user is actually found. What can I do to make two type return function? Thanks
EDIT:
When user was found, my method would return the first user in list with get(0) which is wrong. It was a residue of me testing something with the ID's
EDITx2: working client
case 3:
sc.nextLine();
System.out.println("Enter username");
userName = sc.nextLine();
try{
restConnect("http://localhost:8080/rest/user/"
+ URLEncoder.encode(userName, "UTF-8"), "GET");
}
catch(RuntimeException e){
System.out.println("No such user...");
}
promptKey();
Your code should be returning a 4xx error when the user does not exist and the client should have a branch when an error is returned.
Think about how things should work for a client that you did not develop yourself and the definition of the API will probably be more clear.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for additional result code details.