Jersey POST operation with PathParam and JSON Object - post

By design, GET operation should be used only for read Only operation. Howeevre,i am looking for a plausible way of implementaion of following.Implement a POST operation that can be called as it is mentioned below
POST /my-store/order/D : where D is the day the customer place an order
Request: POST /my-store/order/14
{
"customer" : "XYZ",
"order" : {
"item1" : 2
}
}
I tried implementing using below function
#Path("/D")
#POST
#Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Response submitOrder(#PathParam("D") int elapsedDays, #Context UriInfo uriInfo, Order orderInfo){
..........
}
But the above implementation does not seem to working. When I try to test the implementation using MyEclipse REST explorer ,it does not offer option to pass in Order object but allow 'D' parameter only. However, if #PathParam and #Path is removed then it works perfectly fine i.e. allows to consume JSON Order object.
But,the requirement is to pass the days as Path parameter and Order object as JSON input in POST request.
Looking for suggestion on implementation approach and design approach.
Thanks in advance

For one thing, your path should be configured like this:
#Path("/{D}")
I assume your extended ellipses means you have some method parameter that represents the deserialization of your order.

Related

QAF | In Data driven testing, retrieving csv data row directly inside StepDef

In my setup using QAF Gerkin, I have an 80+ data column in the test data file which is very difficult to pass all the columns in steps using "<data_column>". I would like to retrieve all the column data directly in my StepDef according to data-driven iteration. I have tried using getBundle().getString("column_name"), but it is not working.
Eg:
Feature File:
Scenario outline: UI-34_Customer Creation
And I request api "get.sample.call"
And I assert api response status is "200"
And Test Data Retrive
Examples: {"datafile": "data/scenarios/1622630669181.csv", "filter": '(_status==true) && (_id.equalsIgnoreCase("UI-34"))'}
StepDef:
QAFTestStep(description="Test Data Retrive")/**/
public void testDataRetrive(){
System.out.println("============>>>>>>>==========");
System.out.println(getBundle().getString("customer_name"));
System.out.println("============<<<<<<<>>>>>>>==========");
}
Note: I'm able to retrive the data, if I mention the column name directly in Step.
Your step need to accept argument and value need to passed when called. In order to pass record/entry from data-provider you can use args[0] reference as value.
Refer example below:
#QAFTestStep(description="Test Data Retrive {testdata}")
public void testDataRetrive(Map<String, Object> data){
System.out.println("============>>>>>>>==========");
System.out.println(data.get("customer_name"));
System.out.println("============<<<<<<<>>>>>>>==========");
}
Scenario outline: UI-34_Customer Creation
And I request api "get.sample.call"
And I assert api response status is "200"
And Test Data Retrive "${args[0]}"
Examples: {"datafile": "data/scenarios/1622630669181.csv", "filter": '(_status==true) && (_id.equalsIgnoreCase("UI-34"))'}
Refer answer to similar question.

Fetching data from a microservice to rest in grails

I have a rest and a microservice.In microservice i have a table and i want that table data to be fetched to rest and i have written the below way in a rest demoController.
def result = restBuilder().post("http://localhost:2222/api/microservice/fetchData"){
header 'authorization', 'fdgtertddfgfdgfffffff'
accept("application/json")
contentType("application/json")
json "{'empId':1,'ename':'test1'}"
}
But it throws an error "No signature of method: demoController.restBuilder() is applicable for argument types: () values: []".How should i fetch data from a microservice to rest?
You are calling a method named restBuilder() and that method does not exist. If you want that to work, you will need to implement that method and have it return something that can deal with a call to post(String, Closure).
You probably are intending to use the RestBuilder class. The particulars will depend on which version of Grails you are using but you probably want is something like this...
RestBuilder restBuilder = new RestBuilder()
restBuilder.post('http://localhost:2222/api/microservice/fetchData'){
header 'authorization', 'fdgtertddfgfdgfffffff'
accept 'application/json'
json {
empId = 1
name = 'test1'
}
}
You may need to add a dependency on grails-datastore-rest-client in your build.gradle.
compile "org.grails:grails-datastore-rest-client"
I hope that helps.

OData : Why am I getting HTTP 428 (Precondition Required) error while performing an update

So here's my code
sap.ui.getCore().getModel("myModel").update("/ZSystemNameSet(mandt='001')", data, null, function(datay, responsey){
sap.ui.getCore().getModel().refresh();
MessageToast.show("It worked...!! Data: "+datay+"Response: "+responsey);
}, function(datax,responsex){
MessageToast.show("Sorry! Data: "+datax+"Response: "+responsex);
});
Also how do I add the header attributes to the update() call?
Obviously your service uses optimistic locking and expects an If-Match header, containing the ETag of the entity, in the request. You can pass this ETag as parameter to the update method. For further details you should check your service definition and the documentation.
Regarding the update of header attributes: It is hard do answer as there is no information regarding your entity orchestration. Normally you should be able to add a property containing the update information for you header to the data structure you send to the server, e.g. if the header is reachable from your entity ZSystemName via association "Header" you do the following:
data.Header = { "attribute1" : value1, "attribute2" : value2 }

routing help in Txroutes library

I need to route the following to a function :
http://www.example.com/docs/?key1=value1&key2=value2
And the route code for it is
dispatcher.connect(name='xyz', route='/docs/{item}', controller=c, action='docs')
so, can you help me with the “route” part as in what should come there so for an incoming request the action gets called.
As in how to relate route='/docs/{item}' and /docs/?key1=value1&key2=value2
HTTP GET request (/docs/) followed by a query string (?key1=value1&key2=value2). You'd use Twisted's normal facilities for accessing the query string.
def docs(self, request):
return '<html><body>Got %s args</body></html>' % request.args
to retrieve from the array use request.args['key1'][0] to get 'value1'.

HTTPClient GetAsync post object

We currently have a generic MVC method that GET's data from ASP.NET Web API
public static T Get<T>(string apiURI, object p)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Config.API_BaseSite);
HttpResponseMessage response = client.GetAsync(apiURI).Result;
// Check that response was successful or throw exception
if (response.IsSuccessStatusCode == false)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
throw new HttpException((int)response.StatusCode, responseBody);
}
T res = response.Content.ReadAsAsync<T>().Result;
return (T)res;
}
}
Our question is:- obviously, we can not send 'p' as you would with a post,
client.PostAsync(apiURI, new StringContent(p.ToString(), Encoding.UTF8, "application/json")
but how we go about sending this object / JSON with a get.
We have seen sending it as part of the URL, however, is there an alternative?
GET sends the values with the query string (end of url), in regards to "but how we go about sending this object / JSON with a get. We have seen sending it as part of the URL, however, is there an alternative?".
The alternative is POST or PUT.
PUT is best used when the user creates the key/url. You can look at examples such as cnn.com - where the URL's are just short versions of the article title. You want to PUT a page at that URL.
Example:
http://newday.blogs.cnn.com/2014/03/19/five-things-to-know-for-your-new-day-wednesday-march-19-2014/?hpt=hp_t2
has the url of "five-things-to-know-for-your-new-day-wednesday-march-19-2014", which was generated from the article title of "Five Things to Know for Your New Day – Wednesday, March 19, 2014"
In general, you should follow these guidelines:
Use GET when you want to fetch data from the server. Think of search engines. You can see your search query in the query string. You can also book mark it. It doesn't change anything on the server at all.
Use POST when you want to create a resource.
Use PUT when you want to create resources, but it also overwrites them. If you PUT an object twice, the servers state is only changed once. The opposite is true for POST
Use DELETE when you want to delete stuff
Neither POST nor PUT use the query string. GET does

Resources