Grails RESTFUL web service api - web-services

I am currently developing a web app which should do restful service calls to existing web service api.
What I have is the base URL and the API names.
Any help on how do I start working on it?
I suppose I need to use httpbuilder for the base url I have, then followed by /api name. But how do I test it on grails if its working?
When I paste the base url on the browser it does return some xml information, so what I need is to do it on grails instead.
XML response when I paste the url through browser
<ns1:createNewUserResponse>
<userId>21</userId>
</ns1:createNewUserResponse>
So I need to be able to get this response through my web-app (grails) instead of pasting it on the browser.
EDIT*
this is a good example I found useful
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
but i do not understand the query part and how do I alter it to my need?
the URL I have contains credential of username and password, the response should return a securityToken which I need to get it out from the results. Any help would be greatly appreciated!

You can start with groovy-wslite, it provides both SOAP and REST webservice clients.

To make a call to a resfull service look at Groovy HttpBuidler - http://groovy.codehaus.org/HTTP+Builder

Related

Virtual Hosting on Next.js app with Apollo GraphQL

I have a webapp made with Next.js and Apollo as show in example with-apollo. I want to serve multiple domains with my webapp (name-based virtual hosting). Unfortunately HttpLink of ApolloClient requires absolute server URL with domain but this makes backend app unable to recognize domain which user really visited. Is there a way to configure HttpLink with a dynamic URL based on real request or use relative URL or anything else?
Either use an Apollo Link to intercept the query and set uri property on the context
const authMiddleware = setContext((operation, { uri }) => {
return refreshToken().then(res => ({
uri: this.getURI()
})
}))
Or intercept the request with Angular's HttpClient interceptor and change the endpoint.
https://github.com/apollographql/apollo-angular/tree/master/packages/apollo-angular-link-http#options
Source: Updating uri of apollo client instance
The NextPageContext object passed to getInitialProps includes the req object when called on the server-side. So you can do something like:
WithApollo.getInitialProps = async ctx => {
const { AppTree, req } = ctx
const linkBaseUrl = req ? req.protocol + '://' + req.get('host') : ''
...
}
You can then pass this base url down to createApolloClient along with the initial state and prepend your HttpLink's url with it. On the client side, this will prepend an empty string (you only need the full URL on the server).

WSO2 Api manager- Respose body data is null using API SDK

I've created an API using WSO2 Api Manager and gave a backend application URL as a production URL. I'm getting 200 response code and Json responce body in web console of the API but when I use JAVA SDK of that API using client. I'm not able to get the response data even though I'm getting 200 response code.
The below mention java code I'm using to consume the API.
Thanks in Advance!
DefaultApi defaultApiTest = new DefaultApi();
ApiClient apiClient = defaultApi.getApiClient();
apiClient.addDefaultHeader("Accept", "application/json");
apiClient.addDefaultHeader("authorization", "Bearer " + "e88aa28a-4e0e-34a1-aec1-55616bf1e7a1");
apiClient.setBasePath("<Production URL of the API>");
defaultApiTest.setApiClient(apiClient);
ApiResponse<?> response = defaultApiTest.getWithHttpInfo();
if(null != response){
JSON data = apiClient.getJSON();
String value = data.toString();
System.out.println(value);
}

How to get Request property in SOAP UI for REST service test

I created a simple project in SOAP UI, and now am trying to extract some test suit properties using Setup Script. Only thing is, RawRequest and Request properties are empty, but I want to display them. Request does exist, but request and raw request properties are null. This is only case with REST services.
def tcaseList = testSuite.getTestCaseList();
// for each testCase
def countTestCases = tcaseList.size();
for(tc = 0;tc<countTestCases;tc++){
def countTestSteps = tcaseList[tc].getTestStepList().size();
for(i=0;i<countTestSteps;i++)
{// get testStep
def testStep = tcaseList[tc].getTestStepAt(i);
runner = tcaseList[tc].run(new com.eviware.soapui.support.types.StringToObjectMap(), false);
def request = testStep.getPropertyValue("RawRequest");
log.info(request.toString())
Any ideas why this property is null, and how to extract request and display it.
In REST Request on SOAPUI the RawRequest property is only available on REST Request which use POST which sends data not only parameters, in REST Request which use GET the RawRequest is empty. If you want instead to get the value of the GET parameters you can use this in your code:
...
def paramValue = testStep.getPropertyValue("parameterName");
...
In REST Request which use POST and sends data you're already doing correctly with your code:
def request = testStep.getPropertyValue("RawRequest");
I add the follow images to illustrate what I'm explaining:
POST with not empty Request:
GET with empty Request:
UPDATE
So if you want to get all the parameters from your REST Requests you can add the follow groovy snippet to your code:
// your for loop...
for(i=0;i<countTestSteps;i++){// get testStep
def testStep = tcaseList[tc].getTestStepAt(i)
...
// code to get REST Request parameters and log to the console
// to avoid errors if you've testSteps which doesn't are RestTestSteps (i.e groovy...)
if(testStep instanceof com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep){
// ? is groovy operator to avoid NPE
def parameters = testStep?.getTestRequest()?.getParams()
// loop through the map parameters
parameters.each { k,v ->
// for each params print the name and the value
log.info "$k : ${v.getValue()}"
}
}
...
If you need more info take a look at RestTestRequestStep API.
Hope this helps,

simple azure web service, http404 error on publish when adding /dowork to URL

I am trying my first web app service using Azure services. I've created it in VS, and it works locally. All it does it return a string that says "hello user" is JSON.
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "/DoWork")]
public string DoWork()
{
// Add your operation implementation here
return "hello user";
}
// Add more operations here and mark them with [OperationContract]
}
}
Problem is when I publish it, says successful. I can see it running on portal.
When I goto published site I get the standard THIS WEB APP HAS BEEN SUCCESSFULLY CREATED, but... when I add the /DoWork to the URL I get HTTP error 404.
I know I must be missing something simple...
any ideas?
you're missing the name of the service. In your case would be something like:
http://engineappservicev001.azurewebsites.net/something.svc/dowork
More info in here:
http://www.codeproject.com/Articles/571813/A-Beginners-Tutorial-on-Creating-WCF-REST-Services

post data - ngResource AngularJS

Hello !
I develop a RESTful webapp with AngularJS, I use the ngResource module to send http requests. The webservice is developped with FuelPHP.
I'm having a problem to creating a resource with the $save method of ngResource. My web service doesn't receive post data.
When I check the http request with Firebug, I can see the post data.
I don't understand why the post data are not received by the webservice. So if you have an idea, it would be cool to help me.
Sorry for my bad level in English.
Here is the code :
Service :
app.factory('Medication', ['$resource', 'global', function ($resource, global) {
return $resource(global.API+'/medication/medication', {}, {})
}])
Method in the controller :
$scope.addMedication = function() {
var newMed = new Medication();
newMed.name = 'nameValue';
newMed.increaseinr = 1;
newMed.details = 'detailsValue';
newMed.$save();
}
I believe this is an issue with how PHP is handling the POST. When using AngularJS $resource it will POST the object with JSON as the post's BODY. PHP does not see this as a regular parameter. I've had to do this in other PHP (never used Fuel)
$requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody, true);
Then you should be able to inspect $requestBody as a normal json object.
You need to config the $save method with a request method of 'POST'
you can set the default option 'transformRequest' of $http to change the transfer formation of the post data.
var myApp = angular.module('myApp');
myApp.config(function ($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return $.param(data);
}
});
Thanks for your answers.
Indeed, data is post in the request's body.
With FuelPHP, I used Input::json('key') to get the values (and not Input:post('key'))