Working with APIs


Working with APIs

Learn the basics of connecting with external services using APIs in Python.


What is an API?

An API (Application Programming Interface) allows two software programs to communicate with each other. Many websites and services expose their data and functionality through APIs.



Making HTTP Requests Using requests Library

We use the requests library to send HTTP requests to APIs.

import requests

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

This sends a GET request to GitHub’s API and prints the response status code (e.g., 200 means success).



Parsing JSON Data

Most APIs return data in JSON format. You can use the .json() method to convert the response to a Python dictionary.

import requests

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

print(data["login"])
print(data["public_repos"])

This code fetches user data from GitHub's API and prints the username and number of public repositories.



Example: Fetching Data from a Public API

Let's fetch a random joke using the Official Joke API.

import requests

url = "https://official-joke-api.appspot.com/jokes/random"
response = requests.get(url)
joke = response.json()

print(joke["setup"])
print(joke["punchline"])

This code fetches a random joke and prints both the setup and the punchline.



Error Handling for API Requests

Always check the response status and handle errors gracefully.

import requests

url = "https://api.github.com/users/invaliduser"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Failed to fetch data:", response.status_code)

This ensures that only valid responses are processed.