Handling User Input in Python Requests

Feb 3, 2024 ยท 2 min read

When building Python applications that make web requests, it's common to need to accept user input to customize those requests. For example, you may want to allow the user to provide search terms, specify API parameters, upload files, and more. Here's how to handle user input with Python's requests library.

Getting Textual Input

The simplest approach is to get a string from the user with the input() function:

search_term = input("Enter search term: ")
response = requests.get(f"https://api.example.com/search?query={search_term}") 

You can then inject that text directly into the request URL, headers, body, etc.

Getting Numeric Input

For numbers, wrap input() with int() or float() to convert to numeric types:

limit = int(input("How many results? "))
params = {"limit": limit}
response = requests.get("https://api.example.com/search", params=params)

File Uploads

To upload a file, first read it into memory and attach it directly to the files parameter:

filename = input("Enter the file to upload: ")
with open(filename, 'rb') as f:
    file_data = f.read()

response = requests.post(
    files={"file": file_data})

This encodes and attaches the binary file data automatically.

Handling Passwords

For sensitive input like passwords, use getpass to hide text entry:

import getpass
password = getpass.getpass("Enter password: ")
response = requests.post("/login", auth=(username, password)) 


Make sure to validate dangerous inputs like filenames, IDs, etc to avoid security issues. Overall, Python's requests library makes it simple to handle user input, but be careful when injecting it directly into sensitive API calls.

Some key takeaways:

  • Use input() to get text, wrap with int()/float() for numbers
  • Attach files directly to files parameter
  • Hide inputs with getpass where necessary
  • Validate dangerous inputs
  • Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you

    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />


    Don't leave just yet!

    Enter your email below to claim your free API key: