Home > Software engineering >  How do I pass user input as a string in an API request?
How do I pass user input as a string in an API request?

Time:11-09

I am trying to take user input (zipCode) and pass that into an API request. How do I format the zipCode user input so that the GET request reads it as a string.

import requests
zipCode_format = ''

def user_input():
    zipCode = input('What is your zipcode? Zipcode: ')
    zipCode_format = "zipCode"
    return zipCode_format

def weather_report():
    params = {
    'access_key': #keyhere,
    'query': zipCode_format,
    'units': 'f'
    }

    api_result = requests.get('http://api.weatherstack.com/current', params)

    api_response = api_result.json()

    print(u'Current temperature in %s is %d degrees Farenheit.' % (api_response['location']['name'], api_response['current']['temperature']))

user_input()
weather_report()

As you can see above, I have tried to declare another variable that turns the zipCode into a string.

CodePudding user response:

Firstly, function user_input() returns which means that in the left side of function call you need to have a variable in which you pass return from function. Secondly, you need to pass this variable to a function.

The third thing is that input() outcome is a string even if you provide number.

zipCode = input("Provide zipCode")
>> 23-312
print(type(zipCode))
>> <class 'str'>

Snippet based on your code

import requests

def user_input():
    zipCode = input('What is your zipcode? Zipcode: ')
    return zipCode

def weather_report(zipCode):
    params = {
    'access_key': #keyhere,
    'query': zipCode,
    'units': 'f'
    }
    api_result = requests.get('http://api.weatherstack.com/current', params)
    api_response = api_result.json()

    print(u'Current temperature in %s is %d degrees Farenheit.' % (api_response['location']['name'], api_response['current']['temperature']))

zipCode = user_input()
weather_report(zipCode)
  • Related