API Gateway: exposing the lambda function
In this article we want to take the lambda function which was created in the last article and expose it as a web service. For that we will use API Gateway which is a service from AWS that lets us expose different AWS services as web services including lambda functions.
Creating and configuring the gateway
To configure this you need to go to “api gateway” and click “Create API” to create a new one. For our lambda function we need a “REST API” (click “Build”). Under “Settings” give a API name like “clothes-classification” and click on “Create API”. From the “Actions” drop down select “Create Resource” and give a Resource name like “predict” (Actually in the REST world resources are nouns, but we will go with the past naming from our flask web service). Nothing more is needed, just click “Create Resource”.
Now we need to create a method for our resource. You can do this from the “Actions” dropdown by selecting “Create Method”. Select the “POST” method. Remember
“data = {'url': 'http://bit.ly/mlbookcamp-pants'}”
is the payload what we’re going to send to the service while using the post request. As “Integration type” select “Lambda Function” and the “Lambda Function” name is “clothing-classification”. Click on “Save” and accept adding permissions to Lambda function.
To test the function you can find a “Test” link with a flash light symbol. Here you need to configure the “Request Body”. Type {"url": "http://bit.ly/mlbookcamp-pants"}
and click “Test”. The output is the same as seen before:
{
"dress": -1.8251237869262695,
"hat": -5.563746929168701,
"longsleeve": -1.7097409963607788,
"outwear": -1.1727796792984009,
"pants": 8.934737205505371,
"shirt": -2.175368070602417,
"shoes": -2.9585258960723877,
"shorts": 2.3701159954071045,
"skirt": -1.7067642211914062,
"t-shirt": -4.354998588562012
}
Deploying/Exposing the gateway
Tests are running successfully. Now we want to take this API gateway and deploy it. This is also done over the “Actions” drop down menu. There you can find the API action “Deploy API”. We create a new Stage and give the name “test” and click “Deploy”. What happens now is, that AWS creates an URL that you can use for testing the api gateway. This url we need for the test.py file where we use it as “url”. The first part is the url which we got from the api gateway as mentioned and the second part is the method we created there which will invoke the lambda function. When starting the test.py file we’ll get the same output as before.
But there is one important remark. Using it as described here is not save because you open your service for everyone in the world. To limit the access is outside the scope of the course but keep that in mind.