I'm trying to get all data of a user of a user with a timestamp:
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable LocalDateTime timeStamp)
{
....
}
Now to test this Spring Boot rest api, in postman, I made this call GET and url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995.
But it gives me error saying : Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
How can I resolve this ??
You need #DateTimeFormat with custom pattern that matches to your input
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{
}
I don't know if it is the most modest way to do this or not, but here is what I have done :
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable String timeStamp)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter);
...
return datumRepository.findUsingTime(start,end);
}
Passed as string and parsed that. AnddateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT); can be used as well.
Related
when I try calling this endpoint with just this endpoint: /api/v1/data/{provider}/{subject} (I removed #pathvariable dataset parameter when I got rid of the dataset path) I am able to successfully call my API. However, when I add an additional pathvariable (dataset in this case), I can't seem to hit my endpoint anymore. Is there some restriction on number of path variables? Not sure what I'm doing wrong.
#GetMapping("/api/v1/data/{provider}/{subject}/{dataset}")
public List<List<String>> getEDXDatasetHead(
#PathVariable final String provider,
#PathVariable final String subject,
#PathVariable final String dataset,
#RequestParam(required = false, value = "date") final String date
)
https://localhost:8443/api/v1/data/testprovider/testsubject/testdataset
#GetMapping("/api/v1/data/{provider}/{subject}/{dataset}")
There is no particular limit on number of PathVariable that you can add to a method.
But if you want to call your API with many different number of PathVariables you need to add a method for each of them, otherwise spring is not able to understand that you are calling the same method with a shorter number of path variables:
#GetMapping("/api/v1/data/{provider}/{subject}/{dataset}")
public List<List<String>> getEDXDatasetHead(
#PathVariable final String provider,
#PathVariable final String subject,
#PathVariable final String dataset,
#RequestParam(required = false, value = "date") final String date
)
...
#GetMapping("/api/v1/data/{provider}/{subject}")
public List<List<String>> getEDXDatasetHead(
#PathVariable final String provider,
#PathVariable final String subject,
#RequestParam(required = false, value = "date") final String date
)
...
#GetMapping("/api/v1/data/{provider}")
public List<List<String>> getEDXDatasetHead(
#PathVariable final String provider,
#RequestParam(required = false, value = "date") final String date
)
Note: spring doesn't have a particular limitation on the number of PathVariable that can be used in a method. But there are limitations on:
the size of the generated url (if too long not all browser handle it correctly)
the format of the url (check if you url encoded the path variables when you build the url on the client side)
I have a class Model Object class as #RequestBody to a RestController in Spring Boot
#Data
class User {
private String name;
private Date dob;
}
I am calling this API from postman with the following JSON body
{
"name" : "Michael",
"dob" : "13/09/19"
}
I get a status 200 OK with this message
'Error occurred while parsing body. Please try with the correct payload.'
My data is not getting submitted. I know the problem is with date, how do I send the proper date?
You could try to annotate the dob field like this:
#JsonFormat(pattern="dd/MM/yy")
private Date dob;
Source: https://www.baeldung.com/spring-boot-formatting-json-dates
I'm trying to get all data of a user of a user with a timestamp:
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable LocalDateTime timeStamp)
{
....
}
Now to test this Spring Boot rest api, in postman, I made this call GET and url - http://localhost:8080/datum/2/2019-12-15T19:37:15.330995.
But it gives me error saying : Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
How can I resolve this ??
You need #DateTimeFormat with custom pattern that matches to your input
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS") LocalDateTime timeStamp)
{
}
I don't know if it is the most modest way to do this or not, but here is what I have done :
#GetMapping("/datum/{userID}/{timeStamp}")
List<Datum> getDataSingleUserTimeRange(#PathVariable Long userID, #PathVariable String timeStamp)
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter);
...
return datumRepository.findUsingTime(start,end);
}
Passed as string and parsed that. AnddateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT); can be used as well.
I have the below input class and when i trigger the api without 'interactionId' param in the input,
I expect validation error message "interactionId cannot be empty" but the validation passes through which i guess could be due to the fact that interactionId has a default value of 0.
Can someone pls. help to enforce this validation on the 'long' parameter when its not given in input?
with #NotEmpty for the customerId param, its working as expected. Using #NotEmpty for the long param "interactionId" is throwing a different error that #notempty cannot be used for long.
public class Input {
#NotEmpty(message = "customerId cannot be empty")
private String customerId;
#Valid
#NotNull(message = "interactionId cannot be empty")
private long interactionId;
// setters and getters
}
my controller class:
#RestController
public class Controller {
#PostMapping(value="/detailed-customer-transaction", produces =
MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Object> detailTransactions(#Valid #RequestBody Input
params)
{
return new ResponseEntity<>(Dao.detailTransactions(params), HttpStatus.OK);
}
Above issues is resolved after changing to Long instead of long.
Query #2
I need another help. I have a String input param which takes date-time format in below format. Given its a string parameter, how can i validate for the pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
long should be Long, because long is a primary type in java, not an object, so Long is an object that can be checked whether it is null
I have to controller that takes a controller that a Notification and returns a json response.
public #ResponseBody ResponseWrapper<Notification> addNotification(
#RequestParam(required = false) String password,
#Valid Notification notification,
BindingResult bindingResult ){.....}
My Notification that is posted includes a LocalDateTime.
notification.time
How can map a String to LocalDateTime when posting. CustomPropertyEditor or is there a better approach.
Also the time is in my wrapper. How can I format it? LocalDateTime in json includes a lot of information I don't need.
You can annotate your field with #DateTimeFormat and provide a pattern. For example
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime time;
If Spring finds jodatime on your class path, it will use an appropriate DateTimeFormatter to parse the String date value from the request and generate a LocalDateTime object.