AWS API Gateway Integration Response - java

I am using AWS Lambda and API Gateway and facing an issue with my API's response code,
In case of an exception I am setting responseCode as 400 in my response,
But the API status is 200.
I found that my solution is related to AWS API Gateway's Integration Response,
I created all the possible Http Status codes that my application needs,
And I set the Lambda Error Regex in Integration Response,
But I still get API status as 200 despite me sending "responseCode" : "400", in my APIs response(response type is JsonObject in Java).
I have the following code AWS Lambda code,
I am passing ErrorCode as query parameter to my Get method,
And returning the same Error code in response eg. "responseCode" : "400".
My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.
public class MainHandler implements RequestHandler<JSONObject, JSONObject> {
public JSONObject handleRequest(JSONObject request, Context context) {
try {
JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
System.out.println("RequestJson : " + requestJson);
JSONObject params = (JSONObject) requestJson.get("params");
System.out.println("Params : " + params);
JSONObject queryString = (JSONObject) params.get("querystring");
System.out.println("QueryString : " + queryString);
String error = (String) queryString.get("errorCode");
System.out.println("ErrorCode : " + error);
JSONObject resp = new JSONObject();
resp.put("responseCode", error);
return resp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
AWS API Gateway Method Response -
AWS API Gateway Integration Response -
Postman response -
The API status shows 200 Ok, whereas I want it as 400.
I am referring the following links -
1. https://forums.aws.amazon.com/thread.jspa?threadID=192918
2. Is there a way to change the http status codes returned by Amazon API Gateway?

Your Lambda Error Regex is not a regular expression. Changing it to .*"responseCode":\s"400".* should do it.
But for that use case it would be better to activate Lambda proxy integration. This provides a more flexible way to set the response code directly from the lambda function.

Related

ElasticSearch SearchTemplate request Java API

I'm stuck with a SearchTemplate request, until now I've been able to write queries through the QueryBuilder and execute them calling the "search" method of the RestHighLevelClient java client, but when I try to execute the searchTemplate method I get a parse exception from the server "request body or source parameter is required".
So far I've been reading the documentation but nothing, the guide about the SearchTemplate is very poor.
This is how I'm currently trying to follow the basic steps from the official documentation:
SearchTemplateRequest request = new SearchTemplateRequest();
request.setRequest(new SearchRequest(indexPI));
request.setScriptType(ScriptType.INLINE);
request.setScript( "{" +
" \"query\": { \"match\" : { \"{{field}}\" : \"{{value}}\" } }," +
" \"size\" : \"{{size}}\"" +
"}");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("from","");
scriptParams.put("size","");
scriptParams.put("field", "title");
scriptParams.put("value", "elasticsearch");
scriptParams.put("size", 5);
request.setScriptParams(scriptParams);
SearchTemplateResponse response = elasticSearchClient.searchTemplate(request,
RequestOptions.DEFAULT);
The error I get:
Elasticsearch exception [type=parse_exception, reason=request body or source parameter is required]
At this point, I'm trying to understand how to set the request body for the above request and actually wondering if it is possible to do.
Any clue about what is missing besides the "unsettable" request body from the exception?

AngularJS $http get return null status 0

I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

Java : How to handle POST request without form?

I'm sending a http post request from javascript, with some json data.
Javascript
var data = {text : "I neeed to store this string in database"}
var xhr= new XMLHttpRequest();
xhr.open("POST","http://localhost:9000/postJson" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
xhr.setRequestHeader("Connection", "close");
//Also, I've tried a jquery POST
//$.post('postJson', {'data=' : JSON.stringify(data)});
//But this doesn't make a request at all. What am I messing up here?
Route
POST /postJson controllers.Application.postJson()
Controller
public static Result postJson(){
//What should I write here to get the data
//I've tried the below but values is showing null
RequestBody rb=request().body();
final Map<String,String[]> values=rb.asFormUrlEncoded();
}
What is the way to parse the POST request body?
Much thanks!
Retreive the request body directly as JSON... no need to complicate your life.
public static Result postJson() {
JsonNode rb = request().body().asJson();
//manipulate the result
String textForDBInsertion = rb.get("text").asText(); //retreives the value for the text key as String
Logger.debug("text for insertion: " + textForDBInsertion
+ "JSON from request: " + rb);
return ok(rb);
}
Also, I recommend you use the AdvancedRestClient Chrome plugin for testing. This way you can eliminate from the equation client-side code errors.
Cheers!

Converting java JSONObject to javascript

I have a JSONObject I'm sending through AJAX.
JSONObject obj = new JSONObject();
obj.put("nbLike", result);
obj.put("username", "bill");
Then in the success function I want to access the obj properties. eg : username
I'have tried with JSON.parse(obj) but I got an error : Uncaught SyntaxError: Unexpected token '
server side the log shows : {"username":"bill","nbLike":1} //log.info(obj)
client side the log show : ['username':'bill', 'nbLike':1] //console.log(result)
I'd like something like :
console.log("Username : " + obj.username)
Thank you
Convert JSONObject to String before sending it to frontend and add "application/json" to Content-type of your response. Then you can use it as simple js object, don't need to convert it.

Blogger JSON API add a post

I want to add post to my blog using Blogger API. I successfully got rights to use Blogger API and activated them in Google API console. I used this tutorial to obtain access_token. I found this question , so before ever request I obtain new request_token.
When I make first request to add post, I got en error: 401 "message": "Invalid Credentials", "location": "Authorization".
When I make second request to add post with new token, I got error: 403 "message": "Daily Limit Exceeded. Please sign up"
Code for my request is:
final JSONObject obj = new JSONObject();
obj.put("id", mUserID);
final JSONObject requestBody = new JSONObject();
requestBody.put("kind", "blogger#post");
requestBody.put("blog", obj);
requestBody.put("title", msg[0]);
requestBody.put("content", msg[0] + " " + msg[1]);
final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/" + mUserID + "/posts");
request.addHeader("Authorization", "Bearer " + mToken);
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(requestBody.toString()));
final HttpResponse response = mHttpClient.execute(request);
final HttpEntity ent = response.getEntity();
Log.i(SocialPoster.LOG, EntityUtils.toString(ent));
ent.consumeContent();
UPDATE
Solution was found: simply adding "?key={MY_API_KEY}" to request's URL solved the problem
The Tutorial site you linked states
"The API Key is mandatory as it identifies your application and therefore allows the API to deduct quota and use the quota rules defined for your project. You need to specify the API Key on your Tasks service Object."
useTasksAPI(String accessToken) {
// Setting up the Tasks API Service
HttpTransport transport = AndroidHttp.newCompatibleTransport();
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
Tasks service = new Tasks(transport, accessProtectedResource, new JacksonFactory());
service.accessKey = INSERT_YOUR_API_KEY;
service.setApplicationName("Google-TasksSample/1.0");
// TODO: now use the service to query the Tasks API
}
Sounds to me like you are missing the API key, using it wrong, misplaced it in your code or supplied it to the service in the wrong way.
I haven't looked over the code here, but this is Google's sample code for what you are trying to do. Test your API key with this code.

Categories