How to use API to invoke Lambda function - api

Im trying to setup an API which will invoke a Lambda function. The function is written with Pyhton.
I have setup a URL Query parameter and also a mapping template.
When using the api URL I have added parameters at the end of the URL so I can invoke it
To get this working I believe I need to somehow add these parameters into my python script. Can anyone tell me how this is done?
Thanks

Check my code below
https://github.com/mmakadiya/aws_lambda-API_gateway-Import-XML-data
You can update the lambda function with below code
import JSON
def lambda_handler(event, context):
print("####################################")
print(event)
print("####################################")
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
When you will trigger a POST request like below
https://gjtf9q4422.execute-api.ap-south-1.amazonaws.com/Dev?autooff=yes?autoon=no?testparam=haha
the "event" will print the query string like this. Simply you can grab it from the "event' parameter as well.
query_string

Related

How to make a MultiMock Http Callout Test for Salesforce?

If I have an Apex function that is named authorize() that just gets a username, password, and session token, and another function called getURL('id#', 'key'), that takes an id# for the record as a string and a key for the image to return as a string as parameters. getURL calls the authorize function inside it in order to get the credentials for its callout. The authorize is a post request, and the getURL is a get request.
I am trying to figure out how to test both of these callouts just so I can make sure that getURL is returning the proper JSON as a response. It doesn't even have to be the URL yet which is its intention eventually. But I just need to test it to make sure these callouts are working and that I am getting a response back for the 75% code coverage that it needs.
I made a multiRequestMock class that looks like this:
public class MultiRequestMock implements HttpCalloutMock {
Map<String, HttpCalloutMock> requests;
public MultiRequestMock(Map<String, HttpCalloutMock> requests) {
this.requests = requests;
}
public HTTPResponse respond(HTTPRequest req) {
HttpCalloutMock mock = requests.get(req.getEndpoint());
if (mock != null) {
return mock.respond(req);
} else {
throw new MyCustomException('HTTP callout not supported for test methods');
}
}
public void addRequestMock(String url, HttpCalloutMock mock) {
requests.put(url, mock);
}
}
I then began to write a calloutTest.cls file but wasn't sure how to use this mock class in order to test my original functions. Any clarity or assistance on this would be helpful Thank you.
I believe in your calloutTest class you use Test.setMock(HttpCalloutMock.class, new MultiRequestMock(mapOfRequests)); then call the getUrl and/or authorize methods and instead of the request really executing the response returned will be that which is specified in the response(HttpRequest) method you have implemented in the MultiRequestMock class. That is basically how I see it working, for more info and an example you can see this resource on testing callout classes. This will get you the code coverage you need but unfortunately cannot check you are getting the correct JSON response. For this, you may be able to use the dev console and Execute Anonymous?
You may want to look at simplifying your HttpCalloutMock Implementation and think about removing the map from the constructor as this class really only needs to return a simple response then your calloutTest class can be where you make sure the returned response is correct.
Hope this helps

How to access Parent imported functions from Module

I'm trying to create a test helper for testing an app that uses the Maru Framework. This is a simplified version of what I'm trying to achieve:
defmodule App.ExtendedMaru do
#moduledoc false
defmacro __using__(opts) do
quote do
use Maru.Test, unquote(opts)
end
end
def post_body(url, body) do
build_conn()
|> Plug.Conn.put_req_header("content-type", "application/json")
|> put_body_or_params(Poison.encode! body)
|> post(url)
end
end
The issues are with the build_conn/0 and post/2 functions. build_conn/0 is defined in Maru.Test and can thus be reached with import Maru.Test inside this module.
However, post/2 is a private function defined inside the __using__ macro for Maru.Test. So, it is present in the module that uses this one, but it's not available to post_body/2. I can't just use Maru.Test here as I'm required to pass the opts and haven't found a way to do so.
Is it possible to access the post/2 function that should be defined in the module that's including this one?
EDIT: How the code ended up:
defmodule Legacy.ExtendedMaru do
#moduledoc """
Adds a few extra function helpers for testing using the Maru framework. Use
it as you would Maru.Test, ie:
`use Legacy.ExtendedMaru, for: An.Api.Module`
"""
defmacro __using__(opts) do
quote do
use Maru.Test, unquote(opts)
unquote(add_post_body())
end
end
defp add_post_body() do
quote do
#doc """
Makes a POST request with the given body. Correctly encodes the body in the
requested format and sets Content-Type headers.
## Parameters
- url: The URL for the POST request
- body: The body to send on the request
- opts: For customizing function behaviour:
- format: What format to send the body in. Defaults to 'json'.
"""
#spec post_body(String.t, map(), keyword(String.t)) :: Plug.Conn.t
def post_body(url, body, opts \\ []) do
format = opts[:format] || "json"
build_conn()
|> add_content(body, format)
|> post(url)
end
def add_content(conn, body, "json") do
Plug.Conn.put_req_header(conn, "content-type", "application/json")
|> put_body_or_params(Poison.encode! body)
end
end
end
end
Your problem arises from two separate things:
The post_body method is private, so you can't call it outside of your Module.
The post_body method is not in the __using__ macro so it's not available to any of the other modules that use it.
There are two simple solutions to this:
Move the post_body method inside the __using__ macro. Once you do this, all modules that use it, will be able to call post_body except the original module.
(or) Make the post_body method public and call defdelegate on it inside __using__. This way you'll be able to call it in all modules including the original one.

Yii using making API call & request->getRawBody

I know that instead of using file_get_contents in Yii you can somehow use Yii::app()->request->getRawBody() but where do you specify the url you are making the call to?
No, they are not equivalent. You only use CHttpRequest::getRawBody() to retrieve the content of the request payload of the CURRENT request.
Below is the getRawBody implementation:
public function getRawBody()
{
static $rawBody;
if($rawBody===null)
$rawBody=file_get_contents('php://input');
return $rawBody;
}
To answer your question, the url is php://input

Getting results from api

I am trying to do a domain availability search using an API from free domain API.
After i create an account, it shows:
**Make a REST request using this URL:**
http://freedomainapi.com/?key=11223344&domain=freedomainapi.com
And looking in the documentation page, it has only:
Request http://freedomainapi.com?key=YOUR_API_KEY&domain=DOMAIN_NAME
Result:
{
"status": "success",
"domain": "freedomainapi.com",
"available": false
}
I am very new to APIs...
What I need is to show a domain search box, and when the user enters, it should return with result.
It claims to show domain suggestions as well. I hope it will also work.
Using jquery and a jsonp proxy
http://jsfiddle.net/mp8pukbm/1/
$.ajax({
type: 'GET',
url: "https://jsonp.nodejitsu.com/?callback=?",
data: {url: 'http://freedomainapi.com?key=14ejhzc5h9&domain=freedomainapi.com'},
dataType: "jsonp",
success: myfn
});
function myfn(data) {
console.log(data);
}
you have to use the proxy because cross domain json is not permitted
EDIT:
i made an update to show the result in a div (stringified)
http://jsfiddle.net/mp8pukbm/2/
EDIT #2: i created a test key on that site, you have to use your own
EDIT #3: and there's your combo: http://jsfiddle.net/mp8pukbm/4/
Assuming that you will use java script for showing the search box, you can use AJAX feature of java script (or jQuery or Dojo) ... All you need to do is a "GET" request that like you can pasted and you will get the result back on the response object. To try out the API you can use "Postman" application in Chrome. https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
In the response object of the AJAX call you will get a JSON object which you can parse and display the result.
Normally when we use REST we need to differentiate one REST call from another.
Assuming this url
http://freedomainapi.com/checkAvailability?key=YOUR_API_KEY&domain=DOMAIN_NAME
In Application layer we need to write an interface
#GET
#Path("/checkAvailability")
#Produces({MediaType.APPLICATION_JSON})
public ReturnObject getDomainAvailability(#QueryParam("key") String key,
#QueryParam("domain") String doaminName );
Once interface is done you need to write your implementation class.
This class will intract with business layer and perform search task and based on
result collected will create ReturnObject.
ReturnObject => will contain status, domain and availability
On screen
$.ajax({
type: "GET",
url: 'root/checkAvailability',
success: function(jsonData)
{
// read json and perform operation
}
,
error: function (error)
{
// handle error
}
});
If you are using JAVA as backend then you can use gson to parse the result, which is a json. After parsing you can read the values from result and display accordingly :)
Any API is a way to extend a given software. (Might be a website or an application)
In both ways there is a certain way to communicate with the software. In your example freedomainapi.com allows you to fetch if given domain is avaiable. There is no such thing as a suggestion tho, atleast i cannot find any suggestions at all.
Given output is a message format know as JSON. It can be easily interpreted by many major Languages such as Java, Javascript and PHP.
Given String might be easily interpreted as a Map consisting of a status (String), a domain (string) and avaiable (boolean)
A domain availability search could not be easier, assuming K is your key, D is your search input (Domain):
Download http://freedomainapi.com/checkAvailability?key=K&domain=D as input
Parse JSON from input as json
return json["status"] == "success" and json["avaiable"]
Depending on your language you might need to use methods to access properties of json, but that does not influence the basic usage of this api.
on user enters, it calls click_button function and I am assuming your result displaying div id is "main_container" you can give domain suggestions by passing related DOMAIN_NAME s as arguments to click_button function
function click_button(DOMAIN_NAME){
$.ajax({
url : 'http://freedomainapi.com?key=YOUR_API_KEY&domain=DOMAIN_NAME',
type: 'GET',
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
data=JSON.parse(data);
if(data['available']){
$('#main_container').html($('#main_container').html()+'<br>'+DOMAIN_NAME+': Available');
else{
$('#main_container').html($('#main_container').html($('#main_container').html()+'<br>'+DOMAIN_NAME+': Not Available');
}//success
});//ajax
}
hope it helpful !

rails controller creating instead of updating when passing in an id

I am trying to add a file to a model using qqfile (though that really isn't relevant here).
I look at the params being passed to the server for update, and I have
{ id: 63, photo: 'foto_file.jpg'}
My understanding was that if an object was passed with an id parameter, rails would understand that as an already existing object, and update that model. If no id parameter is present, Rails would use create.
Is that not correct?? How in this instance can I tell rails to update rather than create?
I'm assuming more code isn't needed here, as my controllers won't really help with the solution because I think the decision is made by rails before it really hits the controller. But I'm happy to post the controller code if it is needed.
--------------- my javascript used to update or create the model ---------------------
render: function(){
var start_form=HandlebarsTemplates['user/userForm'](user.attributes);
$(this.el).html(start_form);
var uploader = new qq.FileUploader({
element: document.getElementById('file-upload'),
action: '/users',
onSubmit: function(id, fileName){
if(MyApp.user.id){
uploader.setParams({
id: MyApp.user.id
});
}
},
debug: true
});
},
The update method is only used when you sent a PUT request, not a POST request. Make sure you're using the PUT method. (If you show your form's code, I can give a more specific answer).
Update -- With your code, try adding this as a parameter to your qq.FileUploader call:
params: {
_method: "put"
}
Rails will look for a _method parameter to handle PUT/DELETE requests.
I couldn't get Dylan's javascript method to work, so in my controller I redirected to my update if the response had an id.
def create
if params[:id]
return self.update
end
#then all my regular create stuff here
end
def update
#all the usual update stuff
end