When building a web application or API locally on your own machine, you'll likely spin up a development server on localhost to test it out. Often, you'll want to access this local server from other scripts and applications running on your machine.
Python's
The Localhost URL
To access localhost, you'll simply use the address
So to access a web server running on port 8000, you'd use this URL:
http://localhost:8000
The same URL works for Python requests.
Sending Requests to Localhost
Import
import requests
response = requests.get("http://localhost:8000/api/status")
print(response.text)
This will send a GET request to the
Handling Security Warnings
When accessing HTTPS URLs on localhost, you may get SSL certificate warnings since localhost uses a self-signed cert by default.
You can disable these warnings:
requests.packages.urllib3.disable_warnings()
Or change the verify option:
requests.get("https://localhost:8000", verify=False)
Summary
Accessing a development server on localhost is easy with Python requests:
Leveraging requests allows you to integrate and test your local APIs in scripts as you build out your application.