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.
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.
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)
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").
In Python, the most popular library for interacting with APIs is requests.
First, ensure you are in your Virtual Environment and install the package:
pip install requests
We will use a free, public API (JSONPlaceholder) that provides "fake" data for testing.
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}")
Most professional APIs (like WeatherStack or AlphaVantage) require a secret "API Key" to track usage. You usually pass this in a dictionary called params.
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
| Term | Description |
| JSON | The standard text format for API data (dictionaries/lists). |
| GET | Request used to "Read" data. |
| POST | Request used to "Create" or "Send" data. |
| Header | Metadata sent with the request (like authentication tokens). |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION