JAX-RS Post method with multiple parameters - java

I want to make a JAX-RS web service using jersey implementation.
I need a post method with 3 parameters.
#POST
#Path ("/addData")
#produce(MediaType.Application_Json)
#Consume(MediaType.Application_JSON)
public User addData(int id, String name, String pass){
User u = new User();
u.setId(id);
u.setName(name);
u.setPass(pass);
return u;
}
#POST
#Path ("/addData")
#produce(MediaType.Application_Json)
#Consume(MediaType.Application_JSON)
public User addSingleData(int id){
User u = new User();
u.setId(id);
return u;
}
There is a separate User class as follow:
public class User{
int id;
String name;
String pass;
// here are the getter setter and constructors
}
First, can I use jersey-media-moxy-2.3.jar file for conversion to JSON (i dont want to use maven). because this jar file is not converting content to json but if i use maven its working fine without parameters in post method.
second, how to get param in body of method if i am using only one param. i.e. second method
third, how to use multiple params in post method.
fourth, in further i need to upload and download an image. how to do that.
last, i am not able to get data in json format.
NOTE: I am making web service for android mobile. i am going to consume it via andorid.

for RESTful API, you should not be relay on the usual web application parameter passing style,
... URL..?param=value
you should form a url in a way that, it make sense to access the resource:
for example:
#POST
#Path("/{courseId}/subjects/{"subjectId"}/description")
public Message get(#PathParam("courseId") String courseId,
#PathParam("subjectId") String subjectId) {
// ....
}
this resource endpoint is giving a way to post a new description for a specific subject under a specific course. So this is how you could access multiple Path parameters in the same Post request.
On the other hand, if you are talking about how to get value of all fields on your 'User' class then you should consider annotating the class with #XmlRootElement
#XmlRootElement
public class User{
int id;
String name;
String pass;
//empty contractors is mandatory in addition to the public getter and
// setters
public User(){
}
// here are the getter setter and constructors
}
now if you send with a POST method something like below : [JSON format] :
{
"id":"123"
"name":"user name"
"pass":"pass"
}
jersey will take of creating instance of User class with the data in the body of the request. which is the reason why you will need mandatory empty constructor in your User class, jersey will first create the instance of the class using the empty constructor and calls setters of each field to set values.
with that in place, if you simple put User in parameter of your method you will have object passed to your method.
#POST
#Path ("/addData")
#produce(MediaType.Application_Json)
#Consume(MediaType.Application_JSON)
public User addData(User newUser){
//do something
return newUser;
}

Related

Spring FeignClient - Treat RESTful xml response as JSON

I'm using Spring FeignClient to access a RESTful endpoint, the endpoint returns an xml,
I want to get the response as a JSON, which in turn will map to a POJO.
1) When I access the endpoint on the browser, I get response as below,
<ns3:Products xmlns:ns2="http://schemas.com/rest/core/v1" xmlns:ns3="http://schemas/prod/v1">
<ProductDetails>
<ProdId>1234</ProdId>
<ProdName>Some Text</ProdName>
</ProductDetails>
</ns3:Products>
2) #FeignClient(value = "productApi", url = "http://prodservice/resources/prod/v1")
public interface ProductApi {
#GetMapping(value="/products/{productId}", produces = "application/json")
ProductDetails getProductDetails(#PathVariable("productId") String productId)
// where, /products/{productId} refers the RESTful endpoint
// by mentioning, produces = "application/json", I believe the response xml would be converted to JSON Java POJO.
3) POJO
public class ProductDetails {
private String ProdId;
private String ProdName;
//...setters & getters
}
4) Service Layer
ProductDetails details = productApi.getProductDetails(productId);
In the 'details' object, both ProdId & ProdName are coming as null.
Am I missing anything here? Firstly, Is it possible to get response as JSON instead of XML?
If that RESTful service is programmed to return only xml-response, then you cannot ask it to give you json-based response.
But in your case the problem is with class where you want to map the result.
This xml response actually wraps ProductDetails tag into ns3:Products.
So you need to create another class which will hold a reference to ProductDetails object:
public class Product { //class name can be anything
private ProductDetails ProductDetails;
//getters, setters
}
Then change the type of getProductDetails method to Product.
If you still get nulls in your response, then it's probably because of ObjectMapper configuration. But you can always add #JsonProperty annotation for your fields (in
this case it would be #JsonProperty("ProductDetails") for ProductDetails field in Product, and #JsonProperty("ProdId") and #JsonProperty("ProdName") for fields in ProductDetails).

Fixed name in rest service's input parameters

I implemented a rest web service by Jax-RS and CXF.
#Path("/StudentServices")
#Produces({"application/json"})
public class Student
{
#POST
#Path("/save")
public String persist(#QueryParam("StudentName") String name,
#QueryParam("StudentAge") String age)
{
System.out.println("*******************************");
System.out.println(" Incomming student with = " + name + " " + age);
System.out.println("*******************************");
return "Hello " + name;
}
}
Actually, I want to call the service with the url: localhost:9000/StudentServices/save
and with the body message as JSON: {"StudentName": "John", "StudentAge": "30"}
but when the request arrived to persist method, its inputs is null or empty. I examined with some others way like Jackson annotations, JAXB annotations but no one worked correctly.
Furthermore, I want to fix parameters' name when my service has input primitive types and String, because when I use a class for input, it works fine.
You cannot use #QueryParam to read the body of the request.
As specified in the #QueryParam docs, It binds the value(s) of a HTTP query parameter to a resource method parameter, resource class field, or resource class bean property. Values are URL decoded unless this is disabled using the Encoded annotation. so if you forward the request like below your exisiting code should work:
localhost:9000/StudentServices/save?StudentName=John& StudentAge=30
Now if you want to accept json request Then you will have to create seprate javaBean.
#XmlRootElement
public class StudentRequest {
private String studentName;
private int studentAge;
// getter and setter
}
And in your Controller. (i.e. Student.)
#Path("/StudentServices")
public class Student {
#POST
#Path("/save")
#Produces({"application/json"})
public String persist(StudentRequest studentRequest)
{
//your custom logic
}
}
Also specify your produces or consumes annotation on method level. It gives flexibility to return some other content type from other method.
You are defining the Parameter as QueryParam this means, that JAX-RS is expecting them as parameter added to your url, e.g. localhost:9000/StudentServices/save?StudentName=John&StudentAge=30
What you want is that the data is send in the body. So you can define a simple POJO:
public class Student {
private String StudentName;
private int StudentAge;
// getters and setters
}
And use it as parameter in the JAX-RS method:
#POST
#Path("/save")
public String persist(Student student) {
System.out.println("*******************************");
System.out.println(" Incomming student with = " + student.getStudentName() + " " + student.getStudentAge());
System.out.println("*******************************");
return "Hello " + student.getStudentName();
}
The JAXB provider is transforming your body data (JSON) into the corresponding POJO and you can access the data via the getters.

How to parse RESTful API params with Dropwizard

Let's say I have:
#GET
public UserList fetch(#PathParam("user") String userId) {
// Do stuff here
}
Now, let's say I have my own type for userId, let's call it UserId. Is it possible to parse that String to UserId when it is passed into the fetch method, i.e.:
#GET
public UserList fetch(#PathParam("user") UserId userId) {
// Do stuff here
}
I realize I can parse the String once I am inside the method, but it would be more convenient that my method gets the type I want.
Well you've attempted to make a GET call with a request body is what I find not very helpful. Do read Paul's answer here -
you can send a body with GET, and no, it is never useful to do so
What would be good to practice is, to make a PUT or a POST call (PUT vs POST in REST) as follows -
#POST
#Path("/some-path/{some-query-param}")
public Response getDocuments(#ApiParam("user") UserId userId,
#PathParam("some-query-param") String queryParam) {
UserId userIdInstance = userId; // you can use the request body further
Note - The ApiParam annotation used is imported from the com.wordnik.swagger.annotations package. You can similarily use FormParam,QueryParam according to your source of input.
Dropwizard is using Jersey for HTTP<->Java POJO marshalling. You could use the various annotations from Jersey #*Param (#FormParam, #QueryParam, etc.) for some of the parameters.
If you need to use map/marshall to/from Java POJOs take a look at the test cases in Dropwizard:
#Path("/valid/")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class ValidatingResource {
#POST
#Path("foo")
#Valid
public ValidRepresentation blah(#NotNull #Valid ValidRepresentation representation, #QueryParam("somethingelse") String xer) {
return new ValidRepresentation();
}
This defines an API endpoint responding to HTTP POST method which expects ValidRepresentation object and "somethingelse" as HTTP method query parameter. The endpoint WILL respond ONLY when supplied with JSON parameters and will return only JSON objects (#Produces and #Consumes on the class level). The #NotNull requires that object to be mandatory for the call to succeed and #Valid instructs Dropwizard to call Hibernate validator to validate the object before calling the endpoint.
The ValidRepresentation class is here:
package io.dropwizard.jersey.validation;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
public class ValidRepresentation {
#NotEmpty
private String name;
#JsonProperty
public String getName() {
return name;
}
#JsonProperty
public void setName(String name) {
this.name = name;
}
}
The POJO is using Jackson annotations to define how JSON representation of this object should look like. #NotEmtpy is annotation from Hibernate validator.
Dropwizard, Jersey and Jackson take care of the details. So for the basic stuff this is all that you need.

Jersey MOXy not parsing snake_case

I'm passing a JSON object from a PUT request to my server. The request itself works, however the fields in the JSON which have an underscore (snake_case) seem to bi ignored. The request outputs the received data to see what comes out, and the value with the underscore converts to camelCase, and doesn't get parsed. Here's the class:
Public User{
private int id;
private String name;
private int some_value;
}
The JSON object I pass to the PUT request:
{ "id":1, "name":John, "some_value":5 }
The PUT method only returns what MOXy caught in this case
#PUT
#Path("user")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public User addUser(User user){
return user;
}
And the output is:
{ "id":1, "name":John, "someValue":0 }
Notice how "some_value" changed to "someValue" and didn't get the actual value updated. Any idea on why this is happening?
MOXy follows Java Bean conventions by default, which suggest camel case. If you don't want to (or can't) use camel case, you can add an annotation to the field:
#XmlElement(name = "some_value")
private int some_value;
If you don't want to annotate all your fields, use an XMLNameTransformer.

RESTful put id and body

I need to have my Java server receive a PUT request to create a new user from an id and a json body, the URI needs to be like:
/usermanagement/user/$id { "name":john, "type":admin }
Given that I've made a simple Java class and can later convert the JSON to a POJO using Jackson, here's my problem:
How do I specify the PUT request to accept both the id and the JSON body as parameters? So far I've got:
#PUT
#Path("{id}")
#Consumes(MediaType.APPLICATION_JSON)
public String createUser(#PathParam("id") int id){
User user = new User();
User.setId(id);
return SUCCESS_MSG;
}
And this works, but I've had no luck adding the JSON body and having the function parse it. I've tried:
public String createUser(#PathParam("id") int id, String body){
return body;
}
It should return the same input JSON when testing in Postman, however it always returns a "resource not available" error.
I feel there's something obvious that I'm missing here?
As per REST API conventions, a POST method on a uri like /usermanagement/users is what is needed. PUT method is used for updating an existing resource. You can go through this wonderful article on how to design pragmatic RESTful API. http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api.
If you are trying to create a new user, why give it an ID? You have to POST the data such as user name, lastname, email, ... and let the backend generate an ID (like an auto-incremented id, or some UUUID) for this new resource.
For example, in my app, I use a json body for a POST request like below:
{
"loginId": "ravi.sharma",
"firstName": "Ravi",
"lastName": "Sharma",
"email": "myemail#email.com",
"contactNo": "919100000001",
"..." : ".."
}
Moreover, your response should return HTTP-201, after successful creation, and it should contain a location header, pointing to the newly created resource.
Instead of Using String body, use a Class with Member variables name and Type Like this.
public class User {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
(This works in Spring Boot Web out-of-box. incase of Spring MVC, you might need to add Jackson dependency): On your Controller , Add #RequestBody Annotation, then Jackson will take care of the un-marshaling of JSON String to User Object.
public String createUser(#PathParam("id") int id, #RequestBody User user){

Categories

Resources