eg:
http://host:port/template/products/?productid=1234,1235
how to implement rest api for the above url where in single queryparam passing multiple values and get the all existing records for the productids
Try something like below to accomplish what you are trying to do:
#RequestMapping(value="/products", method=RequestMethod.GET)
public String getMultipleProductsInfo(#RequestParam List<Long> productIdList) {
String productsInfoAsString = getExistingRecordsForTheProductIds(productIdList);
return productsInfoAsString;
}
Notice the
#RequestParam List productIdList
The comma separated list of product IDs are copied into the productIdList list object. You can either iterate through the list or send it over to the method that is responsible for fetching the results from the datasource, such as your database
Please note that the above code snippet returns the response as String. But you could make your API return a response in other formats too, such as JSON.
Related
I have a request DTO with few input params.
I will be invoking a REST GET method in order to get a response. My response object has nearly 70 attributes and will be getting it in the JSON format.
I have a parameter in the request params called "sortBy" where I will be mentioning any attribute value of response based on which the response objects are to be sorted.
Request DTO :
{
bookBranch,
sortBy,
bookLocation
}
Response Json Object:
bookNo,
bookName,
bookIssueDate,
bookPrice etc (other Book specific attributes)
}
So, Here if I give the bookBranch and bookLocation as input, I will receive the list of all books and its related attriutes list of that branch and location.
Is there a way to sort the list of books based on all the attributes of response object with the value given in the request params
Please help me how can I sort the response objects in case of all using java streams.
Thanks
I have defined a comparator just like below
public static final Map<String, Comparator> myMap=
Map.of("bookno", Comparator.comparing(ResponseDTO::getBookNo), "bookname", Comparator.comparing(ResponseDTO::getBookName),
"bookprice", Comparator.comparing(ResponseDTO::getBookPrice), "dateofissue", Comparator.comparing(ResponseDTO::getDateOfIssue));
and I am checking the value from the request
if (requestDto.getSortBy() != null && myMap.containsKey(dto.getSortBy().toLowerCase())) {
return ResponseList.stream().sorted(myMap.get(dto.getSortBy().toLowerCase())) .collect(Collectors.toCollection(LinkedHashSet::new));
}
The above map takes only 10 entries at a time. What if My response json object has nearly 70 attributes?
This would be tedious to maintain 7 maps and do this check in all 7 maps .
Is there an alternate way to handle this scenario
I am developing REST api using Spring Boot. I've a controller which accepts POST requests.
http://localhost:8085/carride/end-ride
In the above request i want to access the parameter ride_transection_id for finding particular transection object and also some other value as well.
So basically i have 3 way to do that.
1. i can use #PathVariable
#RequestMapping(value = "/end-ride", method = RequestMethod.POST)
public ResponseEntity<?> endRide(#PathVariable("ride_transection_id") long ride_transection_id,#RequestBody
SomeDTORequest someDTORequest ) {
//find transaction using path varibale
}
2.i can use #RequestParam
#RequestMapping(value = "/end-ride", method = RequestMethod.POST
public #ResponseBody item getitem(#RequestParam("ride_transection_id")
long ride_transection_id,#RequestBody SomeDTORequest someDTORequest ){
//find transaction using RequestParam varibale
}
i can use DTO Object SomeDTORequest and accept ride_transection_id into that with other value as well.
#RequestMapping(value = "/end-ride", method = RequestMethod.POST)
public ResponseEntity<?> endRide(#RequestBody SomeDTORequest someDTORequest ) {
//find transaction using path someDTORequest .getID()
}
i am little bit confuses.just want ask which is safest and right way to access the ride_transection_id ?
thanks
You can use any of them but every way is designed for a certain use.
Path variable:
is used when you need to access an entity using a certain field for example i want to access an order and this order is defined by id so to access this order i need the following request Get /order/{id}
Request Parameter:
when you want to send a specific variable or flag for a certain method
for example Get /orders?is_shipped=true, so this will get all shipped orders or you may need orders at certain page Get /orders?page=1
Request body:
when you need to update the entity by the put or patch request as you will update the entity using the entity's json representation which can be send through the request body
for example PUT /orders/{id}
body: {"title": "order_1"}
then the order with id {id} will be updated with the new title
Spring data rest
See also
Basically, all these 3 methods are fine. But if you want to develop or design RESTful services with best practices, I strongly recommend you should provide the querying service with #PathVariable and GET method such as GET /tickets/12. Otherwise, to digest request body with #RequestBody annotation to retrieve querying criteria for POST method is the second suggestion.
Because POST method is usually to be used for creating something. And for querying something, both #PathVariable and #RequestParam annotations are suitable for GET method. More specifically, #RequestParam is often to be used in Filtering, Sorting and Searching results. For example:
Filtering: GET /tickets?state=open - Here, state is a query parameter that implements a filter.
Sorting: GET /tickets?sort=-priority,created_at - Retrieves a list of tickets in descending order of priority. Within a specific priority, older tickets are ordered first.
Searching: GET /tickets?state=closed&sort=-updated_at - Retrieve recently closed tickets.
Please also refer to this article Best Practices for Designing a Pragmatic RESTful API.
Hope this helps you! :)
I have an application where there will be several parameters passed to my endpoint for searching, these parameters are not defined because they are dynamically generated so i cannot map it to a specific model. What would be the best way to map any query parameters into my GET endpoint?
[HttpGet]
public CustomResponse GetResults({something here that will map the parameters?})
{
//perhaps a dictionary? a collection of some sort?
}
Then I need to get all those keys and values and search the database for anything containing that and as i said it could be anything.
So I could pass something like?
/api/Merchandise/GetResults?sku=30021&cupsize=medium&color=red&location=south& {and all the dynamic fields which could be anything}
HttpRequest object has Query property that is an IQueryCollection and holds all passed query parameters.
In other words, in your action method you may do:
[HttpGet]
public CustomResponse GetResults()
{
var queryParams = HttpContext.Request.Query;
// directly get by name
var value1 = queryParams["parameter_name"];
// or queryParams.TryGetValue()
foreach (var parameter in queryParams)
{
string name = parameter.Key;
object value = parameter.Value;
}
}
You could map it to JObject, which is like a Dictionary.
Don't forget:
using Newtonsoft.Json;
I have a dynamically generated form (using jQuery). So beforehand I don't know how many form elements do I have. Does anybody have any idea how we can do it.?
POST the fields in the request body as a JSON-ified map, and use Jackson to to turn it into a Map<String, String> on the controller side. Your controller method would look something like this:
#RequestMapping(value="/url", method=RequestMethod.POST)
public getMap(#RequestBody Map<String, String> fields){
//Manipulate fields as you wish
.
.
.
}
That way you will have your fields as key/pair values inside the map ready for you to manipulate them.
You can turn your fields into a map fairly easily using jQuery (or similar) like this:
var fields = {}
$.each("input:text", function(i, item){
fields[mapKeyValue] = $(item).val();
}
This example assumes that your pair value is the text input, but you can manipulate the values however you want. This is by no means a complete example, but should give you an idea on how to start.
I want to upload an item object with it's image is it possible that i pass a complete object of my Item along with it's image from my Controller if yes then how may i Do it? and I need a Json Pattern also which will be coming from client side.
What would be the Json pattern for my following Item Object.
Class Item{
String ItemID;
String ItemName;
String CategoryID;
List<Image> imagesList;
}
Class Image{
String imageId;
String imageTitle;
byte[] image;
}
and one more thing. Please tell me how can I pass two parameters in my Controller. e.g. if I want to pass Item object in the Request Body along with an extra parameter say String UserID. HOw may I write the following code.
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public void add(#RequestBody Item myItem, String UserID)
{ ...... }
and please tell me what if I pass in the Request in Json format. What will be it looks like?
{ "Item" : { "ItemID": "1", ......}, "UserID" : "hello"}
will it be like this or what? because i tried it i'm getting the Object and string as Null. I also tried it with #RequestParam but same got NULL while debugging.
Currently i'm dealing with this by this.
Class ItemUserPost{
Item item;
String UserID;
}
I'm storing this object in MongoDB. Will be my whole collection of Item will stored along with the images? or i have to use a MultiPart and GridFS API for this. Kindly please refer if related question already posted.
Please Help Urgent.
Thanks in Advance.
The Request Body it's just ONE body. You cannot pass multiple objects or parameters in the same body.
There is 2 turnovers for this:
If you're using REST, you can put the UserID on #RequestMapping(value = "{userId}") and get it from the URL. Or, you can simply put the UserId as query parameter on your url.
Keep using your ItemUserPost object.
--
And for the second question:
Yes, It will store your collection with the images.