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
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
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
filename = input("Enter the file to upload: ")
with open(filename, 'rb') as f:
file_data = f.read()
response = requests.post(
"https://api.example.com/upload",
files={"file": file_data})
This encodes and attaches the binary file data automatically.
Handling Passwords
For sensitive input like passwords, use
import getpass
password = getpass.getpass("Enter password: ")
response = requests.post("/login", auth=(username, password))
Validation
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: