API calls using requests

Introduction Reading Time: 12 min

Table of Contents

Description

APIs (Application Programming Interfaces) allow programs to access data from web services. The requests module is a powerful and simple way to send HTTP requests (GET, POST, PUT, DELETE) and handle responses.

Prerequisites

  • Basic Python knowledge
  • Understanding of HTTP methods (GET, POST, etc.)
  • Basic idea of JSON format

Examples

Here's a simple example of a data science task using Python:


#GET Request (Fetch Data)
import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

# Status code
print(response.status_code)  # 200

# JSON data
data = response.json()
print(data["title"])  # Print the title of the post

#POST Request (Send Data)
import requests

url = "https://jsonplaceholder.typicode.com/posts"
payload = {
    "title": "Tech In My Style",
    "body": "Learning Python APIs!",
    "userId": 1
}

response = requests.post(url, json=payload)
print(response.status_code)  # 201 (Created)
print(response.json())

#Passing Headers and Parameters
url = "https://api.example.com/data"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
params = {"q": "python", "limit": 10}

response = requests.get(url, headers=headers, params=params)
print(response.json())


          

Real-World Applications

Getting live weather, stock, or news updates

Sending data to analytics or database services

Integrating with services like Twilio, Stripe, or Firebase

Where topic Is Applied

Finance

  • Stock price APIs, currency exchange

Healthcare

  • Patient data from EHR systems

Marketing

  • Social media APIs, email automation

Resources

Data Science topic PDF

Download

Harvard Data Science Course

Free online course from Harvard covering data science foundations

Visit

Interview Questions

➤ It's used to make HTTP requests to communicate with APIs and fetch or send data.

➤ params is used to pass query parameters (in GET), data or json is for request body (in POST/PUT).

➤ 200 = OK, 404 = Not Found, 500 = Server Error. These indicate response status.

➤ Use .json() method to convert it to Python dictionary.

➤ Use try-except with requests.exceptions.RequestException and timeout=seconds.