0

I'm trying to query an open source API that returns IP geolocation information by sending a GET request with the IP.

I'm testing the code with a key that contains an IP address (located in key1). I'm trying to fetch the information after the request is sent but I'm not sure what I'm doing wrong.

I have tried appending the IP to the end of the url (as the geoip API instructs) but I keep getting syntax errors.

import json
from botocore.vendored import requests

def lambda_handler(resp, requests, event):

    event = event.key1

    url = "https://freegeoip.app/json/" +event

    headers = {
        'accept': "application/json",
        'content-type': "application/json"
        }

    response = requests.request("GET", url, headers=headers)

    print(response.text)

I have the code working in regular python syntax below, just don't know how to get it working with lambda

import requests


userIP = '54.81.183.174'

def theFunction():
  url = "https://freegeoip.app/json/" + userIP

  headers = {
        'accept': "application/json",
        'content-type': "application/json"
        }

  response = requests.request("GET", url, headers=headers)

  print(response.text)

theFunction()
0

1 Answer 1

2

Your code is using the requests module, which is not installed with AWS Lambda.

You can package it for use with an AWS Lambda function (see python - Cannot use Requests-Module on AWS Lambda - Stack Overflow), but it is simpler to use urllib, which is part of standard Python3.

Here is some code that works:

import urllib.request
import json

def lambda_handler(event, context):

  ip = event['ip']

  with urllib.request.urlopen("https://freegeoip.app/json/" + ip) as f:
    data = json.loads(f.read())

  print(data)
  print(data['city'])

You can trigger it with test data:

{
  "ip": "54.81.183.174"
}
Sign up to request clarification or add additional context in comments.

7 Comments

Wow this has been bugging me for hours and was so simple. Thanks! I have one question though, why is the response null even though the logs get me the info I wanted?
You haven't provided enough information to answer that (eg what do you mean by "the logs get me the info I wanted"), but it might also be due to the incorrect parameters in the lambda_handler() function.
That is my fault! I forgot to include my callback function after I had taken it out for debugging.
would I be able to send the test data as a list?
The data is sent to the Lambda function as a string, which is then interpreted as a JSON object. You can pass a list as JSON: [1, 2, 3] then use it in a loop (eg for ip in event:
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.