Listen up. If you're building Python applications, understanding Python API Basics is non-negotiable. This is where basic scripts turn into enterprise-grade software.
1Api basics Part 1
APIs (Application Programming Interfaces) are how modern software systems talk to each other over the web. Instead of scraping a website's HTML, an API gives you a defined, structured way to request exactly the data you need ā a weather service, a stock price feed, or the training data behind an AI model can all be exposed this way.
For a Python developer, 'using an API' almost always means making HTTP requests to a remote server and getting a structured response back, most commonly in JSON. The 'requests' library is the de facto standard for this: it wraps the low-level details of TCP connections, DNS resolution, and the HTTP protocol into a handful of simple function calls like requests.get() and requests.post().
Understanding APIs matters well beyond web development ā nearly every machine learning pipeline that needs live or third-party data (stock prices, geolocation, translation services, hosted model inference) leans on this same request/response pattern, so the fundamentals covered in this lesson apply directly to real AI-integration work.
# Example
print("Running Python...")Script completed successfully.
2Api basics Part 2
We use the requests library's .get() function to fetch data from a URL ā here, GitHub's public API. requests.get(url) opens the connection, sends the HTTP GET request, and returns a Response object once the server replies.
That Response object carries everything about the server's reply: response.status_code tells you whether the request succeeded (200), was rejected (403, 401), or hit a server error (500), and response.text or response.json() gives you the actual body of the reply. Checking the status code before trying to use the response body is standard practice ā code that blindly calls .json() on a failed request will crash with a confusing parsing error instead of a clear 'request failed' message.
GET is intentionally 'read-only' in the HTTP spec: it should never modify data on the server, which is why it's the correct method whenever you're only retrieving information, whether that's a GitHub repo's metadata or a batch of rows for a training dataset.
import requests
url = 'https://api.github.com'
response = requests.get(url)
print(f'Status: {response.status_code}')Script completed successfully.
3Api basics Part 3
This terminal output shows the result of checking response.status_code after the GET request: 200, meaning 'OK' ā the request reached the server and the server successfully processed it. Status codes are grouped by range, and knowing the ranges lets you branch your code sensibly: 2xx means success, 4xx means the client made a mistake (like 404 Not Found or 401 Unauthorized), and 5xx means the server itself failed.
A production-quality API call doesn't just print the status code ā it checks it. A common pattern is if response.status_code == 200: before processing the body, or using response.raise_for_status(), which raises an exception automatically for any 4xx or 5xx response so errors don't silently propagate as malformed data further down the pipeline.
This matters even more once you start feeding API responses into an AI pipeline: a failed request that goes unchecked can inject empty or error-page content into a dataset, corrupting training data in a way that's hard to trace back to its source.
> Status: 200
# Request successful.Script completed successfully.
4Step-by-Step Breakdown
APIs are how modern apps talk to each other. They provide the data needed to fuel AI models. Let's learn how to tap into those streams.
We use the 'requests' library to interact with web APIs. A GET request fetches data from a server.
A status code of 200 means success! Your request reached the server and data is ready to be used.
Checkpoint: Which HTTP method is used to retrieve data from an API?
- āPOST
- āGET
Most APIs return data in JSON format. Python converts this into a dictionary using the .json() method.
By treating the API response as a dictionary, you can easily extract data for your machine learning models.
Checkpoint: What method converts an API response into a Python dictionary?
- ā.dict()
- ā.json()
To send data (like posting a prediction), use the POST method. You can pass headers for authentication too.
Checkpoint: Which HTTP method is typically used to SEND data to a server?
- āGET
- āPOST
APIs are the gateway to the modern web. Start integrating live data into your Python apps now!
Interpret a Real Status Code. Finish is_successful(): HTTP status codes in the 200s always mean success.
Level Up š
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Surface API Errors as Readable Messages
Don't let a failed request fail silently or crash with a raw stack trace ā catching `requests.exceptions.RequestException` and printing a clear message helps every user of your CLI tool or script, including those relying on screen readers, understand what went wrong.
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Request failed: {e}')SEO Implications
- 1
High Search Volume for 'Python requests' Tutorials
Terms like 'python requests get json', 'python API authentication', and 'requests post example' are among the most searched Python how-to queries, since nearly every real project eventually needs to call an external API.
Best Practices
Always Check status_code or Use raise_for_status()
Never assume a request succeeded ā check `response.status_code` or call `response.raise_for_status()` before parsing the body, so failures surface immediately instead of as a confusing downstream error.
Keep Secrets Out of Source Code
Store API keys and tokens in environment variables (`os.environ`) or a `.env` file excluded from version control ā never hardcode an `Authorization` header value directly in a script you might commit or share.
Frequent Bugs
Calling .json() on a response that wasn't actually successful (e.g. a 404 error page), causing a confusing JSONDecodeError instead of a clear 'request failed' message.
Check `response.status_code == 200` or call `response.raise_for_status()` before calling `.json()`, and wrap network calls in a try/except for `requests.exceptions.RequestException`.
Real-World Examples
Calling a Hosted Model's Prediction Endpoint
A Python backend sends feature data to a deployed AI model's REST API and reads back the prediction, authenticating with a bearer token stored in an environment variable.
import os, requests
headers = {'Authorization': f"Bearer {os.environ['API_KEY']}"}
payload = {'data': [1, 2, 3]}
res = requests.post('https://api.ai.com/v1/predict', json=payload, headers=headers)
res.raise_for_status()
print(res.json())