Lesson 63 of 70 – Python APIs
90%

Python APIs

An API (Application Programming Interface) allows different software applications to communicate with each other. Python can use APIs to request data from web services and can also be used to create APIs.

Note: Web APIs commonly exchange data using HTTP requests and formats such as JSON.
What is an API?

An API is a set of rules and interfaces that allows one program to communicate with another program or service.

For example, a weather application can use a weather API to request current weather information from a server.

Python Application
       |
       | API Request
       ↓
    Web Server
       |
       | API Response
       ↓
Python Application
Why Use APIs?

APIs allow applications to use data and functionality provided by other systems.

  • Get data from web services
  • Send data to servers
  • Connect different applications
  • Access third-party services
  • Build mobile and web applications
  • Automate tasks
  • Connect frontend and backend systems
What is a Web API?

A Web API is an API that communicates over the web, usually using HTTP or HTTPS.

A Python program can send an HTTP request to an API endpoint and receive a response from the server.

Client → HTTP Request → API Server

Client ← HTTP Response ← API Server
API Endpoint

An endpoint is a URL through which an API provides a particular resource or operation.

https://api.example.com/users

For example, an API might provide separate endpoints for users, products and orders.

/users
/products
/orders
HTTP Methods

Web APIs commonly use HTTP methods to describe the operation being requested.

Method Common Purpose
GET Retrieve data
POST Create or submit data
PUT Replace or update a resource
PATCH Partially update a resource
DELETE Delete a resource
GET Request

A GET request is commonly used to retrieve information from a server.

GET /users

In Python, the requests library can be used to send HTTP requests.

import requests

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

print(response.status_code)
API Response

An API server returns a response to the client. The response usually contains a status code and data.

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

print(response.status_code)
print(response.text)
HTTP Status Codes

HTTP status codes tell us whether a request was successful or whether there was a problem.

Status Code Meaning
200 OK / Successful request
201 Resource created
400 Bad request
401 Authentication required or failed
403 Forbidden
404 Resource not found
500 Server error
Checking Status Code
import requests

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

if response.status_code == 200:
    print("Request successful")
else:
    print("Request failed")
What is JSON?

JSON stands for JavaScript Object Notation. It is a commonly used format for exchanging structured data between applications.

{
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

JSON objects are commonly represented as Python dictionaries after being decoded.

Reading JSON from an API

The json() method of a compatible HTTP response can decode a JSON response into Python data.

import requests

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

data = response.json()

print(data)
Accessing JSON Data
data = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

print(data["name"])
print(data["course"])
Output:
Rahul
Python
API Query Parameters

Query parameters are values added to a URL to provide additional information to an API.

https://api.example.com/users?city=Patna

The requests library allows query parameters to be passed using the params argument.

import requests

params = {
    "city": "Patna"
}

response = requests.get(
    "https://api.example.com/users",
    params=params
)

print(response.url)
Sending Data with POST

A POST request is commonly used to send data to an API.

import requests

data = {
    "name": "Rahul",
    "course": "Python"
}

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

print(response.status_code)

The json argument sends the Python data as JSON.

PUT Request

PUT is commonly used when a client wants to replace or update a resource.

import requests

data = {
    "name": "Rahul",
    "course": "Python Full Stack"
}

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

print(response.status_code)
PATCH Request

PATCH is commonly used when only part of a resource needs to be updated.

import requests

data = {
    "course": "Python"
}

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

print(response.status_code)
DELETE Request

DELETE is commonly used to remove a resource from an API.

import requests

response = requests.delete(
    "https://api.example.com/users/1"
)

print(response.status_code)
API Headers

HTTP headers provide additional information about a request or response. They are commonly used for content types, authentication tokens and other metadata.

import requests

headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Accept": "application/json"
}

response = requests.get(
    "https://api.example.com/users",
    headers=headers
)

print(response.status_code)
API Authentication

Some APIs require authentication before they allow access to protected resources.

Common authentication approaches include:

  • API keys
  • Bearer tokens
  • OAuth
  • Session-based authentication
headers = {
    "Authorization": "Bearer YOUR_TOKEN"
}

response = requests.get(
    "https://api.example.com/profile",
    headers=headers
)
Security Tip: Never publish real API keys, passwords or private access tokens in source code that is shared publicly.
API Timeout

A timeout prevents a program from waiting indefinitely for a server response.

import requests

response = requests.get(
    "https://api.example.com/users",
    timeout=10
)

print(response.status_code)

The timeout value is specified in seconds.

Handling API Errors

Network errors, invalid URLs, timeouts and unsuccessful HTTP responses should be handled appropriately.

import requests

try:

    response = requests.get(
        "https://api.example.com/users",
        timeout=10
    )

    response.raise_for_status()

    data = response.json()

    print(data)

except requests.exceptions.RequestException as error:

    print("Request error:", error)

The raise_for_status() method raises an exception for HTTP error responses.

API Response Headers

Response headers contain metadata returned by the server.

import requests

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

print(response.headers)

A specific header can be accessed using its name.

print(response.headers.get("Content-Type"))
API with Python Dictionary

Python dictionaries are convenient when preparing structured JSON data.

student = {
    "name": "Amit",
    "age": 21,
    "course": "Python",
    "fees": 15000
}

print(student["name"])
print(student["course"])
Output:
Amit
Python
API and REST

REST (Representational State Transfer) is a commonly used architectural style for web APIs.

REST-style APIs commonly use HTTP methods and resource-based URLs.

GET     /students
GET     /students/10
POST    /students
PUT     /students/10
DELETE  /students/10

The exact behavior of an API depends on its documentation.

API Documentation

API documentation explains how to use an API. It normally contains:

  • Base URL
  • Endpoints
  • HTTP methods
  • Parameters
  • Request body format
  • Authentication requirements
  • Response format
  • Error codes
Important: Always read the documentation of the API you are using because different APIs may have different authentication methods, parameters and response formats.
Complete API Example
import requests

url = "https://api.example.com/students"

try:

    response = requests.get(
        url,
        timeout=10
    )

    response.raise_for_status()

    students = response.json()

    for student in students:
        print(student)

except requests.exceptions.RequestException as error:

    print("API Error:", error)
Common API Mistakes
  • Using the wrong endpoint.
  • Using an incorrect HTTP method.
  • Ignoring the HTTP status code.
  • Not handling network errors.
  • Not setting a reasonable timeout.
  • Sending incorrect JSON data.
  • Using invalid authentication credentials.
  • Exposing API keys or tokens publicly.
  • Not reading the API documentation.
Real-World Uses of Python APIs
  • Weather applications
  • Payment systems
  • Map and location services
  • Social media integrations
  • SMS and email services
  • Online shopping systems
  • Banking integrations
  • AI services
  • Data collection
  • Mobile application backends
Key Points
  • API stands for Application Programming Interface.
  • APIs allow different software systems to communicate.
  • Web APIs commonly communicate using HTTP or HTTPS.
  • GET is commonly used to retrieve data.
  • POST is commonly used to submit or create data.
  • PUT and PATCH are commonly used for updates.
  • DELETE is commonly used to delete resources.
  • JSON is widely used for exchanging structured API data.
  • The Python requests library can be used to make HTTP requests.
  • HTTP status codes indicate the result of a request.
  • API authentication may use API keys, tokens or other mechanisms.
  • Timeouts and exception handling make API programs more reliable.
  • API documentation should always be checked before integration.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to retrieve data from an API?