<?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 Da-Eng on Medium]]></title>
        <description><![CDATA[Stories by Da-Eng on Medium]]></description>
        <link>https://medium.com/@hana.amulic?source=rss-1228f7071427------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Da-Eng on Medium</title>
            <link>https://medium.com/@hana.amulic?source=rss-1228f7071427------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:12:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hana.amulic/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[How data from the internet finds its way to my database every day without any help (Data pipeline)]]></title>
            <link>https://medium.com/@hana.amulic/how-data-from-the-internet-finds-its-way-to-my-database-every-day-without-any-help-data-pipeline-dfa4bb4035b3?source=rss-1228f7071427------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa4bb4035b3</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Da-Eng]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 13:50:31 GMT</pubDate>
            <atom:updated>2021-12-02T16:21:40.659Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>{ Level : “Beginner”, Language : “Python”, Database : “mySQL”, Platform : “AWS”}</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NP81E3CKEWIF02-idnEDKQ.png" /></figure><p><strong>Gans</strong> (not Guns)…that’s how it all started. The instructor at Data Scientist Bootcamp I’m attending asked us to help a company named Gans to “collect data from external sources that can potentially help Gans predict e-scooter movement”.</p><p>Who are they? To be completely honest, I don’t know much about them, but I will share what I know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQQYpAPPetOP3ZRdHV1qmQ.png" /></figure><p>Another thing you should know about Gans is that they are a fictional company my instructor made up for learning purposes. I am telling you this because some of the requests “Gans” make are a bit strange. But, I have to give it to my instructor I did learn a lot fulfilling those requests. I guess in this case the means justify the ends.</p><p>In this article, you will see some extraordinary (okay, more like average to low) skills of:</p><ul><li><strong>web scraping</strong></li><li><strong>API using</strong></li><li><strong>data storing</strong></li><li><strong>automating all of the above</strong></li></ul><h3>WEB Scraping</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBZ3jjzbraueZwbiypK7zw.png" /><figcaption>Table on Wikipedia that contains information we need</figcaption></figure><p>The first request from Gans was to collect demographical data for the biggest European cities. To make it more fun, we had to do it scraping the notorious Wikipedia. Since Wikipedia doesn’t have a convenient API we used a Python library called <a href="https://beautiful-soup-4.readthedocs.io/en/latest/"><strong><em>Beautiful Soup</em></strong></a><strong><em>. </em></strong>It’s a library for pulling data out of HTML and XML files. It parses a document using Python’s built-in HTML (or XML) parser.</p><pre>url = (&quot;<a href="https://en.wikipedia.org/wiki/List_of_European_cities_by_population_within_city_limits">https://en.wikipedia.org/wiki/List_of_European_cities_by_population_within_city_limits</a>&quot;) <br>response = requests.get(url)<br>soup = <strong>BeautifulSoup</strong>(response.content, &quot;html.parser&quot;)</pre><p>To parse the content of `response` given from wikipedia (content is HTML document) we pass it into the BeautifulSoup constructor together with parser we want to use (HTML parser). What we get is a tree of Python objects.</p><pre>parent = soup<strong>.find</strong>(class_ = &#39;wikitable sortable&#39;)<br>children = parent<strong>.contents</strong>[1]<br>dictionary = {&quot;City&quot;: [],&quot;Country&quot;:[],&quot;Population&quot;:[]}<br>for i, child in enumerate(children):<br>    if((i != 0) &amp; (i%2 == 0)):<br>        dictionary[&#39;City&#39;].append(child.contents[3].get_text(&quot;|&quot;,             strip=True).replace(&#39;\n&#39;,&#39;&#39;))<br>        dictionary[&#39;Population&#39;].append(child.contents[7].get_text(&quot;|&quot;, strip=True))<br>        dictionary[&#39;Country&#39;].append(child.contents[5].get_text(&quot;|&quot;, strip=True))<br>    if(i == 40):<br>        break</pre><p>This code would be much nicer and “generic” if the site we were scraping isn’t Wikipedia. That was some messy HTML we were dealing with.</p><p>In the <em>parent</em> variable, we stored the first <em>tag (type = </em>bs4.element.Tag) that has class “wikitable_sortable”. We found it with <a href="https://beautiful-soup-4.readthedocs.io/en/latest/#searching-the-tree">.find() method</a>. That is actually a table that contains the data we need. Iterating through its children (.contents is a list of all children) was really messy and this code is a result of many printing, examining, and selecting what we actually want to store. Data was saved into a dictionary so it is easy to convert it to a DataFrame later on. Data also needed some cleaning. You can see the entire code on my <a href="https://github.com/hanaamulic/Web_scraping_and_APIs/blob/main/ScrappingPopulationEuropeCities.ipynb">GitHub</a>. There is also a code for scraping for Countries 2-letter-codes that we needed later on.</p><h3>API using</h3><p>Gans asked us to collect weather and flight arrivals info for all the big cities and their airports every day for the next day from today (tomorrow, yes but…</p><pre>today = datetime.date.today()<br>tomorrow = today + datetime.timedelta(days=1)</pre><p>You see it now?</p><p><strong>Weather API — OpenWeatherMap</strong></p><p>For collecting data about weather we used <a href="https://openweathermap.org/api">OpenWeatherMap</a> web API. We could have used library <a href="https://pyowm.readthedocs.io/en/latest/">PyOWM</a> (It is a wrapper library for OpenWeatherMap APIs) for little assistance but since OpenWeatherMap has very good documentation we decided not to use any wrappers and just collect responses we get from APIs directly.</p><p>After signing up on OpeanWeatherMap website you are provided with an API key. Once you get it you are ready to start exploiting their data.</p><p>We have decided to use their <a href="https://openweathermap.org/api/hourly-forecast">Hourly Forecast 4 days</a> API. <a href="https://openweathermap.org/api/hourly-forecast#name5">API call (By City Name)</a> we made request to looks like this:</p><pre>url = (f&quot;<a href="http://api.openweathermap.org/data/2.5/forecast?q={row[&#39;CityCountry&#39;]}&amp;appid={API_key}&amp;units=metric">http://api.openweathermap.org/data/2.5/forecast?q={row[&#39;CityCountry&#39;]}&amp;appid={API_key}&amp;units=metric</a>&quot;) <br>response = requests.get(url)<br>json = response.json()</pre><p>What you need to provide is City name followed by Country 2-letter-code (E.g. “Berlin, DE”) and your API key. You can add “&amp;units=metric” at the end of the url to make sure you get your response values in metric units like temperature in Celsius (by default it is in Kelvins). As you can see from the code, the response you get is in JSON format by default (you can change it to XML or HTML by adding a <em>mode </em>parameter).</p><p>You can see <a href="https://openweathermap.org/api/hourly-forecast#JSON">here</a> how <em>json</em> response looks like. Since you get a response for 4 days and 8 different times of day you need to iterate through each time (json[‘list’]) and select only the data you are interested in. You can see on my <a href="https://github.com/hanaamulic/Web_scraping_and_APIs/blob/main/OpenWeatherApi.ipynb">GitHub</a> how we stored data in<em> dictionary</em> and in <em>DataFrame</em> later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*xERUtVYH-_Ah7kHxomaZmQ.png" /><figcaption>Jsons don’t have the same structure for all times or days</figcaption></figure><p>To avoid errors when reading data for non-existing keys (e.g. [‘snow’]) it is a good practice to wrap your code in “try-except” blocks for handling those errors.</p><pre>try:<br>    dictionary[&#39;Snow&#39;].append(list_element[&#39;snow&#39;][&#39;3h&#39;])<br>except:<br>    dictionary[&#39;Snow&#39;].append(&#39;0&#39;)</pre><p><strong>Flights API - AeroDataBox</strong></p><p>For collecting data for arrivals in cities’ biggest airports we decided to use <a href="https://www.aerodatabox.com/#h.v9n2rrqyqcv4">AeroDataBox API</a>. At this moment, API is managed exclusively through the <a href="https://rapidapi.com/aerodatabox/api/aerodatabox/">RapidAPI platform</a>. You can subscribe and start using AeroDataBox API as soon as you have an account on RapidAPI. Same as at the OpenWeatherMap, you need an API key for AeroDataBox API too. You can get it from RapidAPI for free by subsribing for BASIC plan. This will give you 200 free request to API so be careful while testing your code.</p><p>We were using “Airport flights, departures and arrivals (FIDS/schedules) by airport ICAO code” API. This API gives flight informations for period of max 12 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCrFuKxePgKs0NCCr96LDw.png" /></figure><p>After you adjust all parameters to your needs (E.g. We needed only arrivals) you can just copy the generated code to your notebook. You will get <em>json</em> in response and once again, you need to iterate through it and save the information you need. Wrapping your code in “try-except” is a good practice here too since not the same data is available for all flights. On my <a href="https://github.com/hanaamulic/Web_scraping_and_APIs/blob/main/AerodataboxAPI.ipynb">GitHub</a>, you can see how we manipulated and stored data from this API. You will see that we were fortunate to have a .csv file with all airports in the world and their ICAO codes. You can use <a href="https://github.com/hanaamulic/Web_scraping_and_APIs/blob/main/data/airports.csv">ours</a> or go scraping for it for some practice.</p><p><strong>API keys</strong></p><p>Hardcoding API keys is not the best practice, so we recommend saving them to another Python module and importing them from there. Especially if you are storing your code on some open-source platforms.</p><h3><strong>DATA storing</strong></h3><p>All the data we got from web scraping and APIs needed to be stored somewhere. We decided to use MySQL and MySQL Workbench interface. If you never used them or you just don’t have them on your computer, you should <a href="https://www.simplilearn.com/tutorials/mysql-tutorial/mysql-workbench-installation">download and install</a> them for purposes of following up on this tutorial.</p><p><strong>Creating a database</strong></p><p>Once you know what kind of data you want to store you need to think about how your tables are going to look like and how are you going to connect them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*q_8CJ_9kZTuae9O-so7hjA.png" /><figcaption>gans database</figcaption></figure><p>You can see that we created 3 tables (weather, cities, and flights) and connected them by “CityCountry” (E.g. “Berlin, DE”). Each city has multiple weather and flight elements (one-to-many relation). If you run <a href="https://github.com/hanaamulic/Web_scraping_and_APIs/blob/main/Sql_tables_creation.sql">this .sql file</a> in MySQL workbench, you will create the same database.</p><p><strong>Connecting to database</strong></p><p>For storing data directly from our code to our database we used <a href="https://www.sqlalchemy.org/">SQLAlchemy</a>. It’s a Python library that facilitates the communication between Python programs and databases. Most of the time, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.</p><pre>schema=&quot;gans&quot;<br>    host=&quot;127.0.0.1&quot;<br>    user=&quot;root&quot;<br>    password=API_keys.mysqlPassword<br>    port=3306<br>    con = f&#39;mysql+pymysql://{user}:{password}@{host}:{port}/{schema}&#39;<br>df.to_sql(&#39;weather&#39;,con=con,if_exists=&#39;append&#39;,index=False)</pre><p>The ‘mysql+pymysql’ refers to the type of the database (mysql) and the DBAPI you are using (pymysql). The “user” and “password” are the credentials to login to the database server. The “host” is the location of the database server. The “port” refers to the optional database port and “schema” is the name of the database you want to connect to. Once you create adequate string “con” you just pass it on to <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html">.to_sql()</a> function together with informations like name of the table you are reffering to (“weather”), rule what you want to use if table already exists (“append”) and wether or not you want to pass the DataFrame index as a column. Reading from database is similar if not even easier.</p><pre>df = pd.read_sql_table(&#39;cities&#39;,con=con)</pre><h3>Amazon AWS</h3><p><a href="https://aws.amazon.com/">Amazon AWS</a> is a cloud platform that offers over 200 fully-featured services. The ones we used in our project are AWS RDS, AWS Lambda, AWS IAM, and AWS EventBridge. A lot of letters, right? Let’s try to explain them.</p><p>But first, <a href="https://portal.aws.amazon.com/billing/signup?nc2=h_ct&amp;src=header_signup&amp;redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start">create</a> your account on Amazon AWS.</p><p><a href="https://aws.amazon.com/rds/"><strong>AWS RDS</strong></a></p><p>Since we didn’t want to store all this data on our local machine we decided to store it in a cloud. We chose Amazon RDS (Relational Database Service) to manage our database. Amazon RDS is a managed relational database service that provides you with several familiar database engines to choose from, including MySQL. So basically, you will create a database in a cloud and you will be able to connect to it from your MySQL Workbench, your code, etc. and nothing will be stored on your local computer.</p><p><a href="https://www.youtube.com/watch?v=Ng_zi11N4_c">This video</a> will be enough for you to get you started with AWS RDS.</p><p><a href="https://aws.amazon.com/iam/"><strong>AWS IAM</strong></a></p><p>IAM stands for Identity Access Management. It is used to set users, permissions, and roles. It allows you to grant access to the different parts of the AWS platform. For this project create a role for Lambda functions with AdministratorAccess policy and save it as “LambdaAdminAccess”.</p><p><a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html"><strong>AWS Lambda</strong></a></p><p>AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you. Without worrying whether your computer has the power to run code, do you have enough resources or capacity, you just need to provide your code (Lambda supports Python) and leave the rest to Lambda. Be sure to add layers in AWS Lambda so that your code has access to the libraries you used. We used AWSDataWrangler-Python38 layer as well as a custom layer to import libraries like sqlalchemy. We also saved our APIkeys.py file that contains APIkeys inside a custom layer so we can access them too. You can have your entire code in one function and then call it from lambda_handler() or you can have several functions and call them from lambda_handler() or you can put your entire code in lambda_handler(). The importantthing to know is that only the code inside lambda_handler() gets triggered.</p><p><a href="https://aws.amazon.com/eventbridge/"><strong>AWS EventBridge</strong></a></p><p>Amazon EventBridge is a service that provides real-time access to changes in data in Amazon Web Services services, your own applications and Software-as-a-Service (SaaS) applications without writing code. It means you don’t have to push the button or create any kind of trigger to run your (in our case) Lambda function, EventHandler does that for you. We <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-get-started.html">set up</a> our EventHandler to trigger our Lambda function every day at 00:00.</p><h3>Let’s sum it up</h3><p>At the end we have our code running in the cloud every day at 00:00 collecting data from internet and saving it to database that is also in a cloud. All we had to do was:</p><ul><li>Scrap sites for information about cities</li><li>Use APIs to collect flight and weather data</li><li>Create and setup a database in the cloud</li><li>Put our code in the cloud</li><li>Schedule our code to be run whenever we want</li></ul><h3>Gans? Who are they? Why do they need this data?</h3><p>I have no idea but I loved collecting this data for them. I really learned a lot working on this project. The fact that I created my own data pipeline makes me feel closer to ‘Data Scientist’ title. After learning these basics I feel I would have no problem confronting bigger and more complicated tasks. I hope you enjoyed this article and that you learned something too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa4bb4035b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>