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()

1 Answers1

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"
}
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470