Working with APIs | Dataplexa

Working with APIs in Python

APIs (Application Programming Interfaces) allow programs to communicate with external services. They help you send requests, receive data, and interact with applications over the internet. APIs are widely used in weather apps, payment systems, maps, social media, and automation tools.

What Is an API?

An API is a set of rules that lets one application request information from another. APIs return data in structured formats such as JSON, which Python can easily process. They allow developers to access powerful services without building everything from scratch.

Types of API Requests

The most common request types are: GET → Retrieve information POST → Send data PUT → Update existing records DELETE → Remove records Each method has a specific purpose and is used depending on what your program needs to do.

Using the requests Library

Python’s requests library makes it very easy to interact with APIs. It handles connections, sending queries, and receiving structured responses. This keeps your code simple and readable.

import requests

response = requests.get("https://api.example.com/data")
print(response.status_code)
print(response.text)

Parsing JSON Data

Many APIs return data in JSON format, which Python can convert into dictionaries. This allows you to access values using keys and work with the data easily. JSON parsing is essential for processing API results in real applications.

import requests

response = requests.get("https://api.example.com/users")
data = response.json()

print(data["name"])
print(data["email"])

Sending Parameters in the URL

You can pass additional data to an API using parameters. These parameters help filter results, request specific items, or customize responses. This is common when working with search-based or query-based APIs.

import requests

params = {"city": "London", "unit": "metric"}
response = requests.get("https://api.example.com/weather", params=params)

print(response.json())

POST Request (Sending Data)

A POST request sends new information to an API. It is commonly used for creating users, submitting forms, or uploading data. POST requests often return a confirmation or an ID for the new record.

import requests

payload = {"name": "Oliver", "age": 28}
response = requests.post("https://api.example.com/create", json=payload)

print(response.json())

Handling API Errors

APIs may fail due to network issues, invalid requests, or server problems. Python allows you to check status codes to detect errors early. This ensures your program handles failures gracefully and safely.

import requests

response = requests.get("https://api.example.com/data")

if response.status_code == 200:
    print("Success:", response.json())
else:
    print("Error:", response.status_code)

Using Headers and Authentication

Some APIs require API keys or authentication tokens. Headers are used to pass these securely during the request. This protects your access and ensures only authorized users can retrieve data.

import requests

headers = {"Authorization": "Bearer YOUR_API_TOKEN"}
response = requests.get("https://api.example.com/profile", headers=headers)

print(response.json())

Real-World Use Cases

APIs are used for fetching weather updates, user profiles, and financial market data. They help automate workflows such as sending messages or processing online orders. They allow Python applications to integrate with modern web services easily.


📝 Practice Exercises


Exercise 1

Write a program that sends a GET request to an example API and prints the status code.

Exercise 2

Send a POST request with a JSON body containing a username and password.

Exercise 3

Make a GET request with URL parameters (e.g., country=USA).

Exercise 4

Make a GET request to an authenticated endpoint using a header token.


✅ Practice Answers


Answer 1

import requests

response = requests.get("https://api.example.com/info")
print(response.status_code)

Answer 2

import requests

data = {"username": "test_user", "password": "secret123"}
response = requests.post("https://api.example.com/login", json=data)

print(response.json())

Answer 3

import requests

params = {"country": "USA"}
response = requests.get("https://api.example.com/location", params=params)

print(response.json())

Answer 4

import requests

headers = {"Authorization": "Bearer TOKEN123"}
response = requests.get("https://api.example.com/details", headers=headers)

print(response.json())