I’m trying to create an app to generate the weather at a certain location based on the IP address visiting my site. My function is supposed to get their IP address using ip-api.com and then send that IP to the waetherapi API and get it’s weather and location, then return it in JSON format.
These are my original functions to get the IP address, location and weather:
def get_ip(ip):
visitor_ip = requests.get(f"https://ip-api.com/json/{ip}")
response = visitor_ip.json()
city = response.get("city", "Unknown")
return city
def get_weather(city):
api_key = os.getenv("WEATHERAPI_KEY")
weather_reply = requests.get(f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={city}&aqi=no")
weather = weather_reply.json()
if "current" in weather:
temperature = weather['current']['temp_c']
else:
temperature = "N/A"
if "location" in weather:
city_new = f"{weather['location']['name']}"
else:
city_new = "N/A"
return temperature, city_new
Here is the expected JSON response from the weatherapi.com website for the API using the IP address I provided:
http://api.weatherapi.com/v1/current.json?key=**************&q=165.73.223.224&aqi=no
Response Code:
200
….
Response Headers:
{
"Transfer-Encoding": "chunked",
"Connection": "keep-alive",
"Vary": "Accept-Encoding",
"CDN-PullZone": "93447",
"CDN-Uid": "8fa3a04a-75d9-4707-8056-b7b33c8ac7fe",
"CDN-RequestCountryCode": "GB",
"Age": "0",
"x-weatherapi-qpm-left": "5000001",
"CDN-ProxyVer": "1.04",
"CDN-RequestPullSuccess": "True",
"CDN-RequestPullCode": "200",
"CDN-CachedAt": "07/07/2024 13:18:56",
"CDN-EdgeStorageId": "1054",
"CDN-Status": "200",
"CDN-RequestId": "d953ffe88adfc6650d8a7d0d88cdbb90",
"CDN-Cache": "MISS",
"Cache-Control": "public, max-age=180",
"Content-Type": "application/json",
"Date": "Sun, 07 Jul 2024 13:18:56 GMT",
"Server": "BunnyCDN-DE1-1054",
"Via": "1.1 varnish (Varnish/6.0)"
}
Response Body
{
"location": {
"name": "Ifo",
"region": "Ogun",
"country": "Nigeria",
"lat": 6.82,
"lon": 3.2,
"tz_id": "Africa/Lagos",
"localtime_epoch": 1720358270,
"localtime": "2024-07-07 14:17"
},
"current": {
"temp_c": 30.3
}
- This is the expected output:
{
"client_ip": "165.73.223.224",
"greeting": "Hello, Mark! The temperature is 30.3 degrees Celsius in Ogun Nigeria"
"location": "Ogun Nigeria",
}
- This is what I get:
{
"client_ip": "165.73.223.224",
"greeting": "Hello, Someone! Unfortunately, I could not determine your location",
"location": "Unknown"
}
Eworitse Egbejule is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.