Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass user input as a string in an API request?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading