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

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);
}

Related

Retuning stream in AWS API Gateway -> Lambda function?

I have created an API using AWS api gateway like https://api.mydomain.com/v1/download?id=1234". The download resource has GET method. And the GET method is invoking lambda function using Lambda Proxy Integration.
The Lambda function needs to act as Proxy. It needs to resolve correct backend endpoint based on header x-clientId and then forward the request to that backend endpoint and return response as it is. So it needs to be generic to handle GET request of different content-type.
My lambda function looks like ( .NET Core)
public async Task<APIGatewayProxyResponse> Route(APIGatewayProxyRequest input, ILambdaContext context)
{
var clientId = headers["x-clientId"];
var mappings = new Mappings();
var url = await mappings.GetBackendUrl(clientId, input.Resource);
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var proxyResponse = new APIGatewayProxyResponse()
{
Headers = new Dictionary<string, string>(),
StatusCode = (int)System.Net.HttpStatusCode.OK,
IsBase64Encoded = false,
Body = await response.Content.ReadAsString())
};
}
The handler above works as long as request and response's content-type is application/json or application/xml. However i am not sure how to handle response when backend returns stream.
For download API, the backend returns Content-Disposition: attachment; filename="somefilename and ContentType may be one of the following:
application/pdf
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/x-zip-compressed
application/octet-stream
For these streams, How do i set APIGatewayProxyResponse.Body?
For Excel file I have tried setting body like below
var proxyResponse = new APIGatewayProxyResponse()
{
Headers = new Dictionary<string, string>(),
StatusCode = (int)System.Net.HttpStatusCode.OK,
IsBase64Encoded = true,
Body = Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync())
};
proxyResponse.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
proxyResponse.Headers.Add("Content-Disposition", "attachment; filename=\"Report.xlsx\"");
When i access the Url from the browser and try to open the file. I get error
Excel cannot open the fileReport.xlsxbecuase the file format or file extension is not valid. Verify that the file has not been corrupted and that the extention matches the format of the file
I think the issue is how i am setting the response body
Update 1
So based on AWS doc Binary Data Now Supported by API Gateway. Now as per the documentation
you can specify if you would like API Gateway to either pass the
Integration Request and Response bodies through, convert them to text
(Base64 encoding), or convert them to binary (Base64 decoding). These
options are available for HTTP, AWS Service, and HTTP Proxy
integrations. In the case of Lambda Function and Lambda Function Proxy
Integrations, which currently only support JSON, the request body is
always converted to JSON.
I am using Lambda Function Proxy, which currently support JSON. However the example here shows how to do it with Lambda Proxy.
I think what i am missing here is Binary Media Types setting and Method Response settings. Below is my setting. Not sure if these settings are correct
Binary Media
Method Response
here how solved it
1>add Binary Media Types. API->Settings->Binary Media Types -> add
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
2>In Method Response Add Content-Disposition and Content-Type headers for thestatus 200
3>In Integration Response map these headers to headers that are coming from the backend. And also set content handling convert to binary. (our backend api is returning file blob in body)

Getting HTTP 401 Error calling MS CRM 365 USING SOAP UI

I am trying to call MSCRM 365 web services using SOAPUI, this is what i have done so far
Downloaded Organization WSDL from my cRM instance
Uploaded in SOAPUI
Added three header parameters - Content-Type, SOAPAction and Accept
Added Username and Password in Request Properties
Whenever I send a request to MSCRM, I get "HTTP ERROR 401 - Unauthorized: Access is denied"
Anyone have any ideas?
Thanks,
Nitesh
Since this is Dynamics 365 it does not authenticate using Username / Password. Instead you will need to use OAuth as shown in the link
https://msdn.microsoft.com/en-us/library/gg327838.aspx
// TODO Substitute your correct CRM root service address,
string resource = "https://mydomain.crm.dynamics.com";
// TODO Substitute your app registration values that can be obtained after you
// register the app in Active Directory on the Microsoft Azure portal.
string clientId = "e5cf0024-a66a-4f16-85ce-99ba97a24bb2";
string redirectUrl = "http://localhost/SdkSample";
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext =
new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = authContext.AcquireToken(resource, clientId, new
Uri(redirectUrl));
Use the access token in message requests:
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
Another options would be to shift from Xrm.Client to Xrm.Tools.Connection. See the example in this site.
https://msdn.microsoft.com/en-us/library/jj602970.aspx

JavaCode To Connect API Mgr Using Client Id/Client Secret/Token

I have a BE Java Service, which is RESTFul, which is ported on WSO2 API Manager. It is published and available in Store. I have registered a new Application (by Name ' Java App ') and upon subscribing to that API, it provided me with Client Key and Client Secret along with Token. Using the Token I am able to successfully access the API (from SOAP UI). My requirement is to access the API from a standalone Java Application. Can someone direct me or provide appropriate code that can access the published API.
Regards, Sreedhar.
You can use Apache HTTP client to invoke the API by sending Authorization as a HTTP Header.
String url = "API_URL";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add Authorization Header header
request.addHeader("Authorization", "Bearer :" + accessToken);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
For Generating Token with username, password and Client Key / Secret, You can use following cURL sample to build the HTTP request. More information can be found in token api
curl -k -d "grant_type=password&username=<username>&password=<password>" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh" -H "Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token
You have to base 64 encode Client Key / Secret and send it with Authorization header as Basic.

RestSharp response unauthorized

I am new to web based solutions. I am hitting a rest url using RestSharp library.
My code is as follows:
var cleint = new RestClient("http://REST_URL");
cleint.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest();
request.Method = Method.GET;
request.Resource = "0.json";
IRestResponse response = cleint.Execute(request);
if (response != null && ((response.StatusCode == HttpStatusCode.OK) &&
(response.ResponseStatus == ResponseStatus.Completed)))
{
// var arr = JsonConvert.DeserializeObject<JArray> (response.Content);
}
The url returns a json file, when I hit it manually. But I want to use a C# console application to get the json file and save it to the disk. I am getting an unauthorized response when I run the above mentioned code:
response.ResponseStatus= "Unauthorized"
This is all it needed..
client.Authenticator = new NtlmAuthenticator();
So if your IIS settings have Windows Authentication set as enabled, this is what you are going to need, Http Basic authentication is not enough to by pass the server security

Grails RESTFUL web service api

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