<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Janmajay Kumar on Medium]]></title>
        <description><![CDATA[Stories by Janmajay Kumar on Medium]]></description>
        <link>https://medium.com/@janmajayalexander?source=rss-6d045a73efaf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MXClYegIFMcG4nt9.jpg</url>
            <title>Stories by Janmajay Kumar on Medium</title>
            <link>https://medium.com/@janmajayalexander?source=rss-6d045a73efaf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:42:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janmajayalexander/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating Real-Time Data Pipelines: Integrating Weather and Flight APIs with Python and MySQL]]></title>
            <link>https://medium.com/@janmajayalexander/building-a-data-pipeline-with-python-fetching-weather-and-flight-data-into-mysql-c6b5629cb006?source=rss-6d045a73efaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6b5629cb006</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[weather-api]]></category>
            <category><![CDATA[python-automation]]></category>
            <dc:creator><![CDATA[Janmajay Kumar]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 16:51:08 GMT</pubDate>
            <atom:updated>2024-10-10T11:39:20.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*Z6dbO_SB99koEin8Ca7Cjw.jpeg" /></figure><blockquote>In this article, we’ll walk you through the steps of building an <strong>automated data pipeline</strong> that integrates data from <strong>OpenWeather API</strong> and <strong>AeroDataBox API</strong> to store real-time <strong>weather</strong> and <strong>flight information</strong> into a <strong>MySQL database</strong>. Along the way, we’ll learn about the importance of <strong>data pipelines</strong> in ensuring smooth and scalable data processing workflows and how to secure sensitive credentials such as API keys and database passwords.</blockquote><h3>The Importance of Database Pipelines in Modern Data Engineering</h3><p>In today’s data-driven world, businesses and organizations rely on vast amounts of data to make informed decisions, optimize operations, and predict future trends. This data comes from multiple sources: customer transactions, IoT devices, weather APIs, flight information, and more. The challenge lies not only in collecting this data but also in storing, processing, and analyzing it effectively.</p><p>This is where <strong>database pipelines</strong> come into play. A well-structured database pipeline ensures data flows seamlessly from source to storage and then to analysis. It connects different systems and data sources, ensuring the right information is available in the right format at the right time.</p><h3>What is a Database Pipeline?</h3><p>A <strong>database pipeline</strong> is a series of steps that data goes through from collection to storage in a database, and then further to processing or analysis. The pipeline typically involves multiple stages:</p><ol><li><strong>Data Collection</strong>: Fetching data from various sources like APIs, internal systems, or third-party services.</li><li><strong>Data Transformation</strong>: Cleaning, formatting, and preparing the data for storage.</li><li><strong>Data Loading</strong>: Storing the data in a structured format in a database.</li><li><strong>Data Retrieval</strong>: Querying the database to retrieve stored data for analysis, reporting, or decision-making.</li></ol><p>A pipeline’s primary function is to <strong>automate</strong> and <strong>streamline</strong> the flow of data, minimizing manual intervention and ensuring consistency across systems.</p><h3>Why Are Database Pipelines Important?</h3><h4>1. Handling Large Volumes of Data</h4><p>With the exponential growth in data generation, managing and processing this vast amount of information becomes critical. Manually fetching and storing data from multiple sources is not only time-consuming but also prone to errors. A database pipeline allows for <strong>scalable data collection</strong>, ensuring you can handle millions of data points without performance degradation.</p><p>For instance, in a system fetching weather and flight data, a pipeline can automatically collect new data every few hours, ensuring the database is always up-to-date. This makes the pipeline essential for industries like finance, healthcare, travel, and logistics, where real-time data is key to business decisions.</p><h4>2. Consistency and Accuracy</h4><p>One of the biggest challenges in data engineering is maintaining <strong>data quality</strong>. Inconsistent, missing, or incorrectly formatted data can lead to erroneous insights. Pipelines allow you to apply <strong>data transformations</strong>, ensuring the data is cleaned, validated, and normalized before being stored in the database.</p><p>For example, fetching weather data from various cities may lead to inconsistencies in units (e.g., temperatures in Celsius or Fahrenheit). A well-structured pipeline will ensure that the data is standardized, eliminating potential errors during analysis.</p><h4>3. Efficiency and Automation</h4><p>A key advantage of database pipelines is their ability to <strong>automate</strong> repetitive tasks. Instead of manually querying APIs and inserting data into databases, a pipeline does this automatically. This not only reduces the workload but also ensures that data is updated at regular intervals.</p><p>In modern applications like business intelligence, automation through pipelines is critical. Companies no longer have to wait for manual data dumps; instead, they can access real-time insights through automated pipelines that feed data into dashboards or reporting systems.</p><h4>4. Centralized Data Management</h4><p>With multiple data sources (APIs, third-party systems, IoT devices), organizations need a central location to store and manage data. Database pipelines help bring <strong>centralization</strong> to data storage, ensuring that data from various sources can be accessed, retrieved, and analyzed from a single point.</p><p>For example, an organization might collect weather data, customer transaction data, and social media trends, all from different sources. A pipeline brings this data together into a single database, making it easier to correlate, analyze, and generate insights.</p><h4>5. Facilitating Advanced Analytics</h4><p>Once the data is stored and structured, database pipelines make it easier to retrieve and process the data for <strong>advanced analytics</strong>. Whether it’s machine learning, statistical analysis, or reporting, a pipeline ensures that the data is always <strong>readily available</strong> in a structured format.</p><p>In a weather and flight data project, for example, combining flight schedules with weather forecasts can provide insights into potential delays or disruptions, improving decision-making for airlines and passengers alike.</p><h3>Best Practices for Building Effective Database Pipelines</h3><p>To build an effective database pipeline, there are several best practices to consider:</p><ol><li><strong>Scalability</strong>: Ensure your pipeline can handle increasing volumes of data as your system grows.</li><li><strong>Data Integrity</strong>: Implement validation checks at each stage to ensure data consistency and accuracy.</li><li><strong>Error Handling</strong>: Build error-handling mechanisms to manage API failures or database connection issues, ensuring the pipeline is resilient.</li><li><strong>Automation</strong>: Automate as much of the process as possible, from data collection to storage and retrieval, minimizing manual intervention.</li><li><strong>Security</strong>: Protect sensitive data by securing API keys and database credentials, implementing access control, and using encryption where necessary.</li></ol><h3>Tools for Building Database Pipelines</h3><p>Several tools and libraries can help you build robust database pipelines:</p><ul><li><strong>Python</strong>: Ideal for building custom pipelines due to its flexibility and the availability of libraries like requests, pandas, and SQLAlchemy.</li><li><strong>Airflow</strong>: A platform for programmatically authoring, scheduling, and monitoring workflows.</li><li><strong>SQLAlchemy</strong>: For seamless interaction with databases in Python.</li><li><strong>Docker</strong>: For containerizing your pipeline, making it easier to deploy and scale.</li><li><strong>MySQL</strong>: A reliable and scalable relational database for storing structured data.</li></ul><h3>Real-World Example: Weather and Flight Data Pipeline</h3><p>To bring the concept of database pipelines to life, let’s walk through a real-world example. Imagine a system that:</p><ul><li>Fetches <strong>weather data</strong> for a list of cities from the OpenWeather API.</li><li>Fetches <strong>flight data</strong> for a list of airports from the AeroDataBox API.</li><li>Stores the data in a <strong>MySQL</strong> database for further analysis.</li><li>Retrieves the data for <strong>reporting</strong> or advanced analytics (e.g., predicting flight delays based on weather conditions).</li></ul><p>This system is built using Python and MySQL, and the database pipeline handles everything from fetching data, transforming it (e.g., converting temperature from Kelvin to Celsius), and storing it in the database, to retrieving data for real-time dashboards.</p><p>I created a data pipeline. You can view the entire project on<a href="https://github.com/QED137/Data-Engineering/tree/main"> GitHub</a></p><h3>A Brief Walkthrough of the Project</h3><p>This project demonstrates the construction of a <strong>data pipeline</strong> that integrates real-time <strong>weather</strong> and <strong>flight information</strong> using external APIs. The data pipeline begins by scraping city information (latitude, longitude, city, and country) from <strong>Wikipedia</strong> using <strong>BeautifulSoup</strong>, followed by fetching weather data from <strong>OpenWeather API</strong> and flight details from <strong>AeroDataBox API</strong>. All the data is stored in a <strong>MySQL database</strong>, from which it can be queried and analyzed using <strong>Python</strong>.</p><p><strong>Key Steps in the Project:</strong></p><ol><li><strong>Fetching City Data from Wikipedia</strong> Using BeautifulSoup, we scrape the coordinates and country for each city from Wikipedia:</li></ol><pre>from bs4 import BeautifulSoup<br>import requests<br>from lat_lon_parser import parse<br><br>def cities_data(cities):<br>    city_data = []<br>    for city in cities:<br>        url = f&quot;https://www.wikipedia.org/wiki/{city}&quot;<br>        response = requests.get(url)<br>        city_soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br>        latitude = city_soup.find(class_=&quot;latitude&quot;).get_text()<br>        longitude = city_soup.find(class_=&quot;longitude&quot;).get_text()<br>        country = city_soup.find(class_=&quot;infobox-data&quot;).get_text()<br><br>        city_data.append({<br>            &quot;City&quot;: city,<br>            &quot;Country&quot;: country,<br>            &quot;Latitude&quot;: parse(latitude),<br>            &quot;Longitude&quot;: parse(longitude),<br>        })<br>    return pd.DataFrame(city_data)</pre><p>2. <strong>Fetching Weather Data from OpenWeather API</strong> We use the OpenWeather API to retrieve weather data like temperature, humidity, and weather conditions for the cities. The following is a brief sketch of the code. (Full code one can find on <a href="https://github.com/QED137/Data-Engineering/tree/main">GitHub</a>)</p><pre>def get_weather_data(lat, lon, api_key):<br>    url = f&quot;https://api.openweathermap.org/data/2.5/forecast?lat={lat}&amp;lon={lon}&amp;appid={api_key}&amp;units=metric&quot;<br>    response = requests.get(url)<br>    if response.status_code == 200:<br>        weather_data = response.json()<br>        return weather_data<br>    else:<br>        print(f&quot;Failed to retrieve data: {response.status_code}&quot;)</pre><p>3. <strong>Fetching Flight Data from AeroDataBox API</strong> The AeroDataBox API provides flight information such as scheduled arrivals for specific airports. The following is a brief sketch of the code. (Full code one can find on <a href="https://github.com/QED137/Data-Engineering/tree/main">GitHub</a>)</p><pre>def get_flight_data(icao_list, api_key):<br>    flight_items = []<br>    for icao in icao_list:<br>        url = f&quot;https://aerodatabox.p.rapidapi.com/flights/airports/icao/{icao}/2024-10-10T00:00/2024-10-10T23:59&quot;<br>        headers = {<br>            &#39;x-rapidapi-key&#39;: api_key<br>        }<br>        response = requests.get(url, headers=headers)<br>        flights_json = response.json()<br>        <br>        for item in flights_json[&quot;arrivals&quot;]:<br>            flight_items.append({<br>                &quot;arrival_airport_icao&quot;: icao,<br>                &quot;flight_number&quot;: item.get(&quot;number&quot;, None),<br>                &quot;scheduled_arrival_time&quot;: item[&quot;arrival&quot;][&quot;scheduledTime&quot;].get(&quot;local&quot;, None)<br>            })<br>    return pd.DataFrame(flight_items)</pre><p>4. <strong>Storing Data in a MySQL Database</strong> The retrieved data is stored in a MySQL database for future retrieval and analysis. We use SQLAlchemy to interact with the database. The following is a brief sketch of the code. (Full code one can find on <a href="https://github.com/QED137/Data-Engineering/tree/main">GitHub</a>)</p><pre>from sqlalchemy import create_engine<br><br>def connect_database(config):<br>    connect_string = f&#39;mysql+pymysql://{config[&quot;user&quot;]}:{config[&quot;password&quot;]}@{config[&quot;host&quot;]}:{config[&quot;port&quot;]}/{config[&quot;database&quot;]}&#39;<br>    engine = create_engine(connect_string)<br>    return engine<br><br>def push_to_database(df, table_name, engine):<br>    df.to_sql(table_name, con=engine, if_exists=&#39;append&#39;, index=False)</pre><p>5. <strong>Retrieving and Analyzing Data</strong> Once the data is stored, it can be queried and analyzed from the database. Here’s how we retrieve the weather data for analysis:</p><pre>def retrieve_from_db(table, engine):<br>    query = f&quot;SELECT * FROM {table}&quot;<br>    return pd.read_sql(query, con=engine)<br><br>engine = connect_database(config)<br>weather_df = retrieve_from_db(&#39;weather_data&#39;, engine)</pre><p>6.<strong> main.py </strong>The project also contains a main.py file, which serves as the central point for executing the code and controlling the various components of the data pipeline. You can maneuver this file to adjust what data is fetched, stored, or retrieved, depending on the desired output.</p><p>7.<strong> Automating with Cron job</strong></p><p>To ensure the pipeline runs automatically at regular intervals, I used a <strong>cron job</strong> for scheduling. This allows the system to fetch weather and flight data, store it in the database, and send notifications — without manual input.</p><p>For example, to run the script daily at midnight, I set up the following cron job:</p><pre># Open the crontab editor<br>crontab -e<br><br># Add this line to schedule the Python script<br>0 0 * * * /path/to/your/project/automation.sh</pre><p>and automation.sh look like the following, one can tailor it according to the need :</p><pre>#!/bin/bash<br><br># Navigate to your project directory<br>#cd /path/to/your/project<br><br># Activate your virtual environment if needed<br># source /path/to/venv/bin/activate<br><br># Log file location<br>LOG_FILE=&quot;automation.log&quot;<br><br># Execute your Python script for weather data<br>echo &quot;Fetching weather data...&quot; &gt;&gt; $LOG_FILE<br>python3 main.py --weather &gt;&gt; $LOG_FILE 2&gt;&amp;1<br>echo &quot;Weather data fetched successfully!&quot; &gt;&gt; $LOG_FILE<br><br># Execute your Python script for flight data<br>echo &quot;Fetching flight data...&quot; &gt;&gt; $LOG_FILE<br>python3 main.py --flights &gt;&gt; $LOG_FILE 2&gt;&amp;1<br>echo &quot;Flight data fetched successfully!&quot; &gt;&gt; $LOG_FILE<br><br># Send a desktop notification (optional, for Linux)<br>notify-send &quot;Automation Complete&quot; &quot;Weather and Flight data fetching completed.&quot;<br><br># Optionally, send an email notification if required</pre><h4><strong>For further details, you can explore the full project on my</strong><a href="https://github.com/QED137/Data-Engineering"><strong> GitHub</strong></a></h4><h3>Database Schema Overview.</h3><p>The diagram above illustrates the database schema used in my data pipeline project. It highlights how different tables, such as <strong>weather</strong>, <strong>flights</strong>, <strong>airports</strong>, and <strong>cities</strong>, are structured and interconnected:</p><ul><li>The <strong>cities</strong> table stores essential city information like name, country, latitude, and longitude.</li><li>The <strong>weather</strong> table records weather data for each city, including temperature, rain probability, and wind speed.</li><li>The <strong>flights</strong> table tracks flight arrivals for various airports, including ICAO codes and scheduled times.</li><li>The <strong>airports</strong> table connects airport data with cities, allowing for efficient retrieval of flight and weather data for specific locations.</li></ul><p>This relational design ensures seamless interaction between weather and flight data, making it easier to store, retrieve, and analyze relevant information efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*u9tYu73XSJI3_XbVX3jZ2g.png" /></figure><h3>Conclusion</h3><p>Database pipelines are indispensable in today’s data-centric world, especially when they are <strong>automated</strong> and designed to handle <strong>real-time data</strong>. In this project, we demonstrated how to integrate weather and flight APIs into a MySQL database, automate the process using cron jobs, and ensure seamless data flow.</p><p>By automating data pipelines, you not only eliminate manual tasks but also ensure that your data is always up to date, enabling accurate and timely data-driven decisions. Whether you’re managing weather data, flight schedules, or any other real-time information, building a well-structured and automated pipeline can streamline the process and unlock the full potential of your data.</p><p>With proper database pipeline infrastructure, organizations can <strong>scale their data operations</strong>, improve <strong>efficiency</strong>, and make <strong>more accurate data-driven decisions</strong>. For further details, explore the full project on my <a href="https://github.com/QED137/Data-Engineering"><strong>GitHub</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6b5629cb006" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>