Python

An API (Application Programming Interface) acts as a bridge that allows two different software applications to talk to each other. In Python, APIs are most commonly used to fetch data from web servers (like weather updates, stock prices, or social media feeds) and integrate them into your own programs.

1. Theoretical Overview

What is a Web API?

Think of an API as a waiter in a restaurant.

  • You (the Client) are at the table with a menu of options.

  • The kitchen (the Server) has the ingredients to prepare your food.

  • The API is the waiter who takes your request to the kitchen and brings the response (food) back to you.

Key Concepts

  • Endpoint: A specific URL where the API can be accessed (e.g., https://api.github.com/users).

  • Request: The message you send to the server. It usually consists of a Method (GET to retrieve data, POST to send data).

  • Response: The data the server sends back, usually in JSON (JavaScript Object Notation) format, which looks very similar to a Python dictionary.

  • Status Codes: Numbers that tell you if the request was successful:

    • 200: OK (Success)

    • 404: Not Found

    • 401: Unauthorized (API key missing or wrong)

Why use APIs?

  • Real-time Data: Get live updates without storing massive databases yourself.

  • Efficiency: Use services built by others (like Google Maps or OpenAI) instead of coding them from scratch.

  • Automation: Connect different apps to trigger actions (e.g., "If it rains, send a Slack message").

2. Code Implementation

In Python, the most popular library for interacting with APIs is requests.

A. Installing the Library

First, ensure you are in your Virtual Environment and install the package:

Bash
pip install requests

B. Making a GET Request

We will use a free, public API (JSONPlaceholder) that provides "fake" data for testing.

Python
import requests

# 1. Define the API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"

# 2. Send the GET request
response = requests.get(url)

# 3. Check the status code
if response.status_code == 200:
    # 4. Parse JSON data into a Python dictionary
    data = response.json()
    print("Success! Data retrieved:")
    print(f"Title: {data['title']}")
    print(f"Body: {data['body']}")
else:
    print(f"Failed to fetch data. Status code: {response.status_code}")

C. Handling API Keys

Most professional APIs (like WeatherStack or AlphaVantage) require a secret "API Key" to track usage. You usually pass this in a dictionary called params.

Python
import requests

api_key = "YOUR_SECRET_KEY"
url = "https://api.weatherapi.com/v1/current.json"

query_params = {
    "key": api_key,
    "q": "Dehradun"
}

response = requests.get(url, params=query_params)
# Resulting URL: .../current.json?key=YOUR_KEY&q=Dehradun

3. Summary Table

TermDescription
JSONThe standard text format for API data (dictionaries/lists).
GETRequest used to "Read" data.
POSTRequest used to "Create" or "Send" data.
HeaderMetadata sent with the request (like authentication tokens).
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now