7. Working with APIs

Introduction to APIs and RESTful Services

What is an API?

An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. It acts as an intermediary that enables seamless data exchange between systems.

Types of APIs:

  1. Web APIs – Used to interact over the internet (e.g., REST, SOAP, GraphQL).

  2. Library APIs – Interfaces provided by libraries and frameworks.

  3. Operating System APIs – Allows software to interact with OS features (e.g., Windows API, POSIX API).

  4. Hardware APIs – Interfaces for hardware communication (e.g., GPU APIs like OpenGL, Vulkan).

What is a RESTful API?

A RESTful API (Representational State Transfer API) is a web API that follows REST principles, making it scalable and easy to use.

Characteristics of RESTful APIs:

  • Stateless: Each request from a client contains all necessary information, and the server does not store client context.

  • Client-Server Architecture: The client and server are independent, allowing for flexible implementations.

  • Uniform Interface: Consistent resource access using HTTP methods (GET, POST, PUT, DELETE).

  • Resource-Based: Data is treated as resources, each identified by a unique URL.

  • Cacheable: Responses can be cached to improve performance.

HTTP Methods Used in RESTful APIs:

  • GET – Retrieve data from a resource.

  • POST – Create a new resource.

  • PUT – Update an existing resource.

  • DELETE – Remove a resource.

Example: Calling a REST API in Python

import requests

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

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

Student Activity:

  • Research real-world APIs like OpenWeather, Twitter, or GitHub APIs.

  • Write a Python script that calls an API, extracts specific data, and processes it.

  • Making API requests using Python’s requests module

  • Parsing API responses

Example: Fetching Data from an API

import requests
response = requests.get('https://jsonplaceholder.typicode.com/users')
print(response.json())

Student Activity:

  • Write a Python script that calls an API and extracts useful information.

Last updated