Home > Enterprise >  Bad Request in Python
Bad Request in Python

Time:01-10

When I run the program below to get a request from openweathermap for the weather, I am getting a 400 status code. Does anyone know how I can get a working status code along with the weather.

import requests

city = input("What is the name of the city?: ")
output = (requests.get("http://api.openweathermap.org/data/2.5/weather?q="   "&appid=*************"))
print(output)

CodePudding user response:

First off, you were not including the city in the url, which is why it is returning an error response.

Secondly, this may not work for cities with spaces, for example, New York.

Try encoding the url like this

import requests
import urllib.parse

city = input("What is the name of the city?: ")
param = {'q': city, 'appid': 'YourAppID'}

url = urllib.parse.urljoin \
    ("http://api.openweathermap.org/data/2.5/weather",
     urllib.parse.urlencode(param)
     )

output = (requests.get(url))
print(output)

CodePudding user response:

maybe this will help

import requests

city = input("What is the name of the city?: ")
url= "http://api.openweathermap.org/data/2.5/weather?q={city}&appid=*************".format(city=city)
response = requests.get(url)
print(response)
  •  Tags:  
  • Related