Skip to main content

Command Palette

Search for a command to run...

Python Basics — Day 21 External Libraries (pip, requests)

Published
3 min read
S

Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey

Building skills in Python and full-stack development, with a focus on web apps and system design

Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering

From Python basics to full-stack projects, sharing my progress as I grow into a developer

Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development

🎯 Learning Goal

Learn how to install and use external Python libraries with pip,
and apply the requests module to communicate with real-world web APIs (e.g. GitHub & Weather APIs).
By the end of this lesson, you’ll have a working API data fetcher that displays live data from the internet.


🧩 Problem Scenario

Imagine you want to build a small app that:

  • Fetches your GitHub profile info (name, followers, public repos)

  • Checks current weather for your city

  • Handles errors safely when internet or API is unavailable

You’ll need to use:

  • pip → to install the external library

  • requests → to send and receive data from web servers (APIs)


🚀 Step 1 – Installing Packages with pip

Python includes pip, a package installer that lets you add new features easily.

# 1. Install a library
pip install requests

# 2. Upgrade it
pip install --upgrade requests

# 3. Check installed packages
pip list

Result: You now have the requests library ready to send HTTP requests.


⚙️ Step 2 – Understanding HTTP Requests

Every web service communicates via HTTP.
You can use requests to send a request and receive a response.

import requests

url = "https://jsonplaceholder.typicode.com/todos/1"
res = requests.get(url)

print("Status Code:", res.status_code)
print("Response JSON:", res.json())

💡 You’ve just fetched live data from a test API — similar to what browsers do behind the scenes.


🧠 Step 3 – Mini Project ① GitHub Profile Fetcher

Fetch your GitHub profile info directly from GitHub’s open API.

import requests

def get_github_info(username):
    url = f"https://api.github.com/users/{username}"
    res = requests.get(url)
    if res.status_code == 200:
        data = res.json()
        print(f"👤 Name: {data['name']}")
        print(f"📦 Public Repos: {data['public_repos']}")
        print(f"👥 Followers: {data['followers']}")
    else:
        print("❌ Failed to fetch data:", res.status_code)

get_github_info("octocat")

Output Example:

👤 Name: The Octocat
📦 Public Repos: 8
👥 Followers: 5000+

🌦️ Step 4 – Mini Project ② Weather Fetcher (OpenWeatherMap API)

Now, let’s connect to a real weather API.
Sign up at openweathermap.org for a free API key.

import requests

def get_weather(city, api_key):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    res = requests.get(url)
    if res.status_code == 200:
        data = res.json()
        temp = data["main"]["temp"]
        desc = data["weather"][0]["description"]
        print(f"🌍 City: {city}")
        print(f"🌡️ Temperature: {temp}°C")
        print(f"☁️ Condition: {desc}")
    else:
        print("❌ Error:", res.status_code)

# Example
get_weather("Zurich", "YOUR_API_KEY")

Output Example:

🌍 City: Zurich
🌡️ Temperature: 22°C
☁️ Condition: clear sky

🧱 Step 5 – Add Error Handling

APIs can fail due to slow internet or invalid URLs.
Let’s make the code more robust.

import requests

def safe_request(url):
    try:
        res = requests.get(url, timeout=5)
        res.raise_for_status()   # raise error if status ≠ 200
        return res.json()
    except requests.exceptions.RequestException as e:
        print("⚠️ Request failed:", e)
        return None

Now your script won’t crash if something goes wrong.


🧩 Step 6 – Combine Everything into One Project

Here’s your final integrated mini-project:
a combined API Fetcher that shows GitHub + Weather data together.

import requests

def get_github_info(username):
    url = f"https://api.github.com/users/{username}"
    try:
        res = requests.get(url, timeout=5)
        res.raise_for_status()
        data = res.json()
        print(f"\n👤 GitHub User: {data['name']}")
        print(f"📦 Public Repos: {data['public_repos']}")
        print(f"👥 Followers: {data['followers']}")
    except requests.exceptions.RequestException as e:
        print("GitHub request failed:", e)

def get_weather(city, api_key):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    try:
        res = requests.get(url, timeout=5)
        res.raise_for_status()
        data = res.json()
        print(f"\n🌍 City: {city}")
        print(f"🌡️ Temperature: {data['main']['temp']}°C")
        print(f"☁️ Condition: {data['weather'][0]['description']}")
    except requests.exceptions.RequestException as e:
        print("Weather request failed:", e)

def main():
    get_github_info("octocat")
    get_weather("Seoul", "YOUR_API_KEY")

if __name__ == "__main__":
    main()

Result:
When you run the script, it fetches live GitHub info and current weather for your chosen city.


📊 Key Takeaways

ConceptDescriptionExample
pip installInstall new librariespip install requests
requests.get()Fetch API datarequests.get(url)
res.json()Convert JSON → Python dictdata = res.json()
try / exceptHandle request errorsraise_for_status()
Real-world useConnect Python to live APIsGitHub, Weather, Currency APIs

Python Basics

Part 21 of 21

A collection of study notes from my university and self-learning journey. This series covers Python fundamentals step by step — from setup to core concepts — to help both myself and others build a solid foundation in coding.

Start from the beginning

Python Basics — Day 1(Python Setup & Basic Functions )

I upload these materials primarily for my own self-study. Still, I hope they might be helpful to someone else as well. Day 1 — Python Setup & Basic Functions (print, type) 01. Setting up the Environment Install Python (version 3.10+ recommended) In...

More from this blog

S

Sabin’s DevLog

21 posts

I plan to upload everything I study and prepare here. I hope it can be helpful to others, and I also want my future self to see the learning journey I’ve been through.