RESTful API with Java Jersey and MongoDB - java

I am newbie with RESTful services, I am trying to make a restful api with the Jersey framework and MongoDB, my question is : How can i search data in the URL.
e.g : "localhost:9999/home/users/find?id=12345", it will return the user with the id = 12345
How can we do that with Jersey ?
Thank's

You want to look into #PathParam and #QueryParam. You can find more about both of them here:
http://docs.oracle.com/cd/E19776-01/820-4867/6nga7f5np/index.html
In short, a path param is the bit between the '/', in your example this is "find". and the query param is id, which has a value of 12345.
You will then need to look this up in a database I assume to get your result to return.

You may want to look at an article I wrote a few years ago. I have a full stack MongoDb, Jersey, Jetty server user admin application at the following github [here](https://github.com/pmkent/angular-bootstrap-java-rest"Angular Bootstrap Java Rest")!

To use a query parameter in Jersey, you'll define it in the jersey Method signature like so:
#GET
#Path("home/users/find")
public Response myMethod(#QueryParam("id") int id) {
// utilizes the id specified in the url parameter "id"
User user = someMongoMethodToFindById(id);
}
Once you harvest the id correctly, you can then query your MongoDB however you'd like based on that passed-by-reference id.
In Jersey, this method is often wrapped in a class in which all related Jersey Resources can be organized. My examples given utilize the Jersey Annotation style.
#Path("home/users")
public class UserResources {
#Path("find")
public Response myMethod(#QueryParam("id")) {
...
}
}

Related

Is there a way to filter or sort data in a RESTful API?

From my understanding (although I am just learning this so I am likely wrong), we use URIs in RESTful APIs to identify resources.
In particular, I've read this comment many times across the web:
#RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while #PathVariable is more suitable for RESTful web services where URL contains values.
When reading this, it seems like we need to use #PathVariable to properly build a RESTful API instead of using #RequestParam (which is not RESTFUL given the way it identifies resources through query parameters instead of URIs). Is this correct? If so, how can I build a RESTful API that is also capable of sorting or filtering like you would be able to do with #RequestParam?
An example is here:
#GetMapping("/{id}")
Resource<Car> get(#PathVariable Long id) {
Car car = carService.findById(id);
return assembler.toResource(car);
}
vs
#GetMapping("/{id}")
Resource<Car> get(#RequestParam(required = true) Long id) {
Car car = carService.findById(id);
return assembler.toResource(car);
}
For filtering, one option is to use Spring Data JPA Specifications, which allows you to return entities that match your specification, which you define as predicates using the Spring criteria API.
Spring Data JPA also includes sorting capability, utilized by either providing a PageRequest or using Sort directly. Spring defines special parameters such as Pageable and Sort, which can be used to apply paging and sorting to your queries dynamically.
Or you can sort via URL parameters indicating the name of the property on which you wish to sort the results.
You should examine the Pageable type in Spring. Generally, what you've shown here is called something like an item resource: It's one specific Car, specified by ID at /cars/{id}. There's nothing to sort or filter. Those are applied to the collection resource /cars, perhaps something like /cars?sort=year&page=0&size=10. Spring has integrated support for automatically extracting query parameters indicating sorting and paging and passing those instructions to Spring Data repositories.

Can we implement both #pathparam and #queryparam for the same endpoint

I am teaching myself REST API development. As part of this, I am creating a Java web server. However, I am stuck on something, and don't know how to proceed.
I have an endpoint called /users, through which users will GET the data. However, I want to implement the option of finding a user and limiting the number of users returned. For example:
GET /users/300 should return the user with ID 300.
If I get the query GET /users?count=10, I want to limit the return to 10 users.
For this, I have settled on the using #QueryParam and #PathParam. The question is: Can I use both of them in the same method?
For example:
#Path("/User")
#Produces({"application/json"})
public List<User> getUsers() {
// ...
}
#GET
#Path("/{id}")
public JSONObject getUserwithId(#PathParam("id") int id) {
return jsonObjectwithId;
}
#Path("?count")
public JSONObject getUserwithCount(#QueryParam("count") int count) {
return noOfusers;
}
I want to whether this is possible.
Yes, I have done this before on web services I have personally worked on. It's not that common, since REST interfaces just don't usually merit the needed complexity. But, it is perfectly permissible for #QueryParam and #PathParam to be used by the same method. I see that you are using Jersey. Based on this thread, if you are actually using Jersey 1.x, you may need to upgrade if you are currently having issues.

How to create a java client for a Spring service?

I have a service definition using Spring annotations. Example (source):
#RequestMapping(value = "/ex/foos/{id}", method = GET)
#ResponseBody
public String getFoosBySimplePathWithPathVariable(
#PathVariable("id") long id) {
return "Get a specific Foo with id=" + id;
}
The question is whether spring (or another library) can auto-create a remote implementation (client) of the same API without the need to manually type paths, method type, param names, etc. (like needed when using RestTemplate)?
Example of an such a client usage:
FooClient fooClient = new FooClient("http://localhost:8080");
String foo = fooClient.getFoosBySimplePathWithPathVariable(3l);
How can I get to such a client "generated" implementation"?
You are probably looking for Feign Client. It does everything you need: calling one service via HTTP is similar to calling method of Java interface. But to make it work you need Spring Cloud, standard Spring framework doesn't have this feature yet.
You can generate it using Swagger Editor. You shoud just define the path of the resources and then it'll generate for you the client for almost any language of your choice

How to return a subset of object properties from a Spring Boot restful GET call?

Newbie question...
I'm building my first Spring Boot restful service and want to support a GET call that returns a collection of entities. like:
/api/customers/
However, for certain consumers -like a list page in a web UI - they would only need a subset of the customer entity properties.
I'm thinking that I could add request parameters to my GET call to set the consumers specific field requirements, like
/api/customers/?fields=id,name,address
But what's the best way of implementing this inside the Java restful controller?
Currently in my rest controller the 'GET' is request mapped to a Java method, like
#RequestMapping(value="/", method= RequestMethod.GET)
public Customer[] getList() {
Customer[] anArray = new Customer[];
....
return anArray;
}
Is it possible to somehow intervene with the default Java to Json response body translation so that only the required properties are included?
TIA
Adding fields parameter is a good idea, best practice according to http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#limiting-fields
How to leave fields out?
1) Set them to null, possibly in a dedicated output class annotated with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Or
2) Use SimpleBeanPropertyFilter See a good step by step tutorial here 5. Ignore Fields Using Filters

Flow of data between Angular 2 and Spring

I am about to start my first real project for work (new grad), and I was tasked with creating an internal address book for the company (displaying name, phone extension number, email etc).
My mentor told me that I need to pull the address data from Active Directory.
He also told me that I need to use Angular 2 for the front end, and Spring for the backend. I still need to learn these frameworks, but he realizes this which is precisely why he gave me this task.
However, I am struggling to understand the flow of data between the frameworks.
This is what I am thinking so far http://imgur.com/a/xiH6m.
If someone could please explain what is right/wrong with the diagram and perhaps explain how the data would flow in such a project. I would prefer to bother my mentor with more specific questions.
Just create a REST service with Spring that returns the data as JSON. You can use a simple POJO on the server side, and the converter for Spring should convert it to JSON. Maybe something like
#RestController
public class EmployeesController {
#Autowired
private LdapService service;
#RequestMapping(value = "/employees/{empId}")
public Employee getEmployee(#PathVariable("empId") Long empId) {
Employee emp = ldapService.getEmployee(empId);
return emp;
}
}
With Spring, it should convert the Employee object to JSON on the outbound response (given you have the JSON converter configured).
In Angular, just make a simple Http request to the endpoint, and you will get back JSON, for which you can convert it to an Employee object on the client side. Maybe something like
class Employee {
// employee properties
}
#Injectable()
class EmployeeService {
constructor(private http: Http) {}
getEmployee(empId: number): Observable<Employee> {
return this.http.get(`${empBaseUrl}/${empId}`)
.map(res => res.json() as Employee)
}
}
Here, in the service, you make the Http request to the employee endpoint on the server, and get the result back as JSON, for which you convert it to an object with res.json() and cast it to Employee
That's pretty much it.
Your "Converts to useful format" will not happen on its own. You need a Controller layer there. REST Controller to be precise.
AngularJS 2 is built to work easily with REST. You can use Spring MVC to create REST Controllers which can generate JSON Response.
for Example you can have an Endpoint
GET /contacts/data
which will return
[
{"name":"ABC",
"email":"someone#abc.com",
"telephone":"0101010101"
},
...
]
The following Spring documentation will be a good starting point eventhough it talks about Angularjs 1.

Categories

Resources