HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Fetch Data from an API (e.g., OpenWeatherMap)

Fetching data from an API in Python is a straightforward process. It involves sending HTTP requests to an API endpoint and handling the response. The `requests` library is a popular choice for this task due to its simplicity and ease of use. By utilizing this library, you can quickly retrieve and process data from various online services.

In this example, we’ll use the OpenWeatherMap API to get current weather information. You need to provide an API key and specify the city you’re interested in. The response is typically in JSON format, which can be easily parsed and utilized for your application needs. This method allows you to integrate real-time data into your Python projects seamlessly.

To fetch data from an API like OpenWeatherMap using Python, you typically use the `requests` library to send HTTP requests and handle the responses.

Below is a step-by-step example of how to do this.

Prerequisites

1. Install the `requests` library if you haven’t already. You can install it using pip:

pip install requests

2. Obtain an API key from OpenWeatherMap by signing up on their website.

Example Code

This example demonstrates how to fetch the current weather data for a specific city.

import requests

# Define your API key and base URL
API_KEY = 'your_api_key_here'
BASE_URL = 'http://api.openweathermap.org/data/2.5/weather'

# Specify the city for which you want to get the weather data
city = 'Chennai'

# Construct the full URL
url = f'{BASE_URL}?q={city}&appid={API_KEY}&units=metric'

# Send a GET request to the API
response = requests.get(url)

# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()

# Extract relevant information from the data
main = data['main']
weather = data['weather'][0]
temperature = main['temp']
weather_description = weather['description']
city_name = data['name']

# Print the results
print(f"Weather in {city_name}:")
print(f"Temperature: {temperature}°C")
print(f"Condition: {weather_description.capitalize()}")
else:
# Print an error message if the request failed
print(f"Failed to retrieve data: {response.status_code}")

Explanation

1. API Key: Replace `’your_api_key_here’` with your actual OpenWeatherMap API key.
2. City: Replace `’Chennai’` with any city you want to query.
3. URL Construction: The URL includes the city name, API key, and units (metric for Celsius).
4. Request and Response: `requests.get(url)` sends the HTTP GET request, and `response.json()` parses the JSON data from the response.
5. Error Handling: The code checks if the request was successful by verifying the status code.

Notes

  • Rate Limits: Be aware of the rate limits imposed by the API, especially if you’re making frequent requests.
  • Error Handling: In production code, you might want to add more robust error handling to manage different types of HTTP errors and exceptions.

Feel free to customize the code according to your needs, such as fetching weather data for different cities or adding more details to the output.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Example Python Code to Send an Email
Up Next
Example Python Code to Extract Text from PDF
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.