<?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 Samarth G Vasist on Medium]]></title>
        <description><![CDATA[Stories by Samarth G Vasist on Medium]]></description>
        <link>https://medium.com/@samarthgvasist?source=rss-2998cf14ab0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AFu69km80E8iPO8_QyJXiw.jpeg</url>
            <title>Stories by Samarth G Vasist on Medium</title>
            <link>https://medium.com/@samarthgvasist?source=rss-2998cf14ab0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:47:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samarthgvasist/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[Building Scalable Python Web Apps: Nginx, Gunicorn and Falcon]]></title>
            <link>https://medium.com/@samarthgvasist/building-scalable-python-web-apps-nginx-gunicorn-and-falcon-7d74000099d0?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d74000099d0</guid>
            <category><![CDATA[wsgi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[falcón]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[gunicorn]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 14:02:44 GMT</pubDate>
            <atom:updated>2023-09-18T14:03:26.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjo95X-tniTq_JkBC__y8w.png" /></figure><blockquote>With the rise in software systems adopting microservices architecture, APIs have become the most important mechanisms by which different components communicate with each other. Python being a very popular programming language, is widely used to build APIs. It offers a wide range of frameworks for API development such as flask, django, falcon and many more. Python’s simplicity, readability, and the availability of a vast ecosystem of libraries and frameworks make it a popular choice for building APIs, whether it’s a small internal service or a large-scale public-facing API.</blockquote><h4>Overview</h4><p>Let’s say we have built a simple <em>flask</em> web app. It is a simple small <em>app</em> and we run it locally using the app.run() function.</p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>@app.route(&quot;/&quot;)<br>def hello_world():<br>    return &quot;&lt;p&gt;Hello, World!&lt;/p&gt;&quot;<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>While running this flask application, we observe the following terminal messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9BKcoVhVEPYkPv0oZrDfw.png" /><figcaption>Flask Warning: This is a development server. Do not use it in a production deployment</figcaption></figure><p>We clearly get the message that <strong>this is just a development server. Do not use it in production deployment. </strong>Generally, we expect that running the flask application server in production is the same as this. But that’s not the case. The <em>flask</em> <em>built-in server</em> is <em>not</em> <em>suitable</em> for <em>production</em>, even the <em>official</em> <a href="https://flask.palletsprojects.com/en/1.1.x/deploying/"><em>documentation</em></a> suggests the same.</p><p>The <em>Python</em> <em>development</em> <em>server</em> is not suitable for <em>production</em> use, given its inherent lack of <em>security</em>, <em>stability</em>, and <em>efficiency</em>. It is mainly intended for <em>fast-paced development</em> and <em>debugging</em>. Hence when it comes to production deployments, python <strong><em>WSGI web frameworks</em></strong> like <strong><em>flask, django</em></strong> or <strong><em>falcon</em></strong> use a <em>WSGI server</em> such as <strong><em>uwsgi</em></strong> or <strong><em>gunicorn</em></strong> due to its <em>high</em> <em>performance</em> and <em>scalability</em> and its <em>integration</em> capabilities with web servers such as <strong><em>Nginx</em></strong>. This combination is often preferred for serving web applications in production environments due to its security and performance benefits.</p><blockquote>In this article, let’s understand the process of setting up Falcon Python, Gunicorn, and Nginx to create a robust and scalable web application stack. Let&#39;s have a look at the below block diagram to understand how a request from the client will be served by interaction across multiple components in the below web server tech stack</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*758hwOZvoOVuV2NjnyWJlA.png" /><figcaption>Block Diagram</figcaption></figure><h4>Components</h4><p><strong>Nginx</strong>: <em>Nginx</em> is a <em>high-performance web server </em>and r<em>everse proxy server.</em> When a <em>client</em> makes an <em>HTTP request </em>to our <em>server</em>, <em>Nginx</em> receives the <em>request</em> first.</p><ul><li>When the <em>request</em> comes to serve <em>static</em> files such as <em>HTML or CSS</em>, <em>nginx</em> can serve them directly without passing the request to <em>gunicorn</em>.</li><li>It serves as a <em>reverse proxy </em>by forwarding the <em>requests</em> to <em>gunicorn</em> for processing at the <em>configured port</em> where the <em>gunicorn</em> is <em>listening</em>.</li></ul><p><strong>Gunicorn</strong>: <em>Gunicorn</em> is a <em>WSGI</em> <em>HTTP</em> server for running <em>Python</em> web applications. It’s responsible for managing multiple <em>worker</em> <em>processes</em> and handling the <em>execution</em> of your <em>Falcon</em> <em>application</em>. When <em>Nginx</em> receives an <em>HTTP</em> <em>request</em>, it forwards it to one of the <em>Gunicorn</em> <em>worker</em> <em>processes</em>. <em>Gunicorn</em> takes care of running your <em>Falcon</em> <em>application</em> code to generate an HTTP response. It provides a bridge between <em>Nginx</em> and your Python application, ensuring that multiple requests can be handled <em>concurrently</em> through its <em>worker</em> <em>processes</em>.</p><p><strong>Falcon</strong>: <em>Falcon</em> is a <em>lightweight</em>, <em>high-performance WSGI Python web framework</em> designed for quickly and efficiently building <em>RESTful APIs</em>. It defines the <em>application’s routes</em>, <em>request-handling logic</em>, and <em>response generation</em>. It contains all the <em>business</em> <em>logic</em> involved in processing the <em>API</em> <em>request</em>. <em>Gunicorn</em> runs our <em>Falcon</em> application, and it <em>delegates</em> the <em>request</em> and <em>response</em> <em>handling</em> to the appropriate <em>Falcon</em> code.</p><h4>Flow</h4><p>So, the typical flow of a request through this stack is:</p><ol><li><em>An incoming HTTP request reaches Nginx.</em></li><li><em>Nginx forwards the request to one of the Gunicorn worker processes at the configured port where the gunicorn is listening.</em></li><li><em>Gunicorn passes the request to our Falcon application for processing.</em></li><li><em>Falcon processes the request, generates a response, and returns it to Gunicorn.</em></li><li><em>Gunicorn sends the response back to Nginx.</em></li><li><em>Nginx, if needed, can perform additional tasks (e.g. SSL termination, load balancing) and then send the response to the client.</em></li></ol><h4>Pre-Requisites</h4><ul><li><strong>Python3 installation</strong></li><li><strong>Nginx installation: </strong>For <em>Ubuntu/debian-based</em> systems nginx can be installed using the following command.</li></ul><pre>sudo apt install nginx</pre><ul><li><strong>Python Virtual Environment</strong>: It’s a good practice to create a <em>virtual</em> <em>environment</em> to isolate <em>project</em> <em>dependencies</em>. It can be installed using the following command.</li></ul><pre>$ python -m venv myenv</pre><p>Here we create a <em>virtual environment</em> named myenv . Next, activate the virtual environment and install the required packages falcon and gunicorn .</p><pre>$ source myenv/bin/activate   # activates the venv myenv<br><br>(myenv)$ pip install falcon   # installs falcon in myenv<br>(myenv)$ pip install gunicorn  # installs gunicorn in myenv</pre><h4>Step 1: Create a Falcon Project</h4><p>We will be creating a bookstorepython package consisting of a BookResource with a simple GET API call at the end-point /books/fetch.</p><p>Let’s have a look at our project directorystructure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*FHlE02JEgMlPKStUUUpwhw.jpeg" /><figcaption>Project structure</figcaption></figure><p>Create a simple <em>resource</em> <em>file</em> BookResource with the following content.</p><pre>import falcon<br>import json<br><br>class BookResource:<br><br>    def on_get(self, req, resp):<br>        data = {<br>              &quot;books&quot;: [<br>                {<br>                  &quot;title&quot;: &quot;The Great Gatsby&quot;,<br>                  &quot;author&quot;: {<br>                    &quot;name&quot;: &quot;F. Scott Fitzgerald&quot;,<br>                    &quot;birth_year&quot;: 1896,<br>                    &quot;nationality&quot;: &quot;American&quot;<br>                  },<br>                  &quot;publication_year&quot;: 1925,<br>                  &quot;genre&quot;: &quot;Fiction&quot;<br>                },<br>                {<br>                  &quot;title&quot;: &quot;To Kill a Mockingbird&quot;,<br>                  &quot;author&quot;: {<br>                    &quot;name&quot;: &quot;Harper Lee&quot;,<br>                    &quot;birth_year&quot;: 1926,<br>                    &quot;nationality&quot;: &quot;American&quot;<br>                  },<br>                  &quot;publication_year&quot;: 1960,<br>                  &quot;genre&quot;: &quot;Fiction&quot;<br>                },<br>                {<br>                  &quot;title&quot;: &quot;The Hobbit&quot;,<br>                  &quot;author&quot;: {<br>                    &quot;name&quot;: &quot;J.R.R. Tolkien&quot;,<br>                    &quot;birth_year&quot;: 1892,<br>                    &quot;nationality&quot;: &quot;British&quot;<br>                  },<br>                  &quot;publication_year&quot;: 1937,<br>                  &quot;genre&quot;: &quot;Fantasy&quot;<br>                },<br>                {<br>                  &quot;title&quot;: &quot;The Catcher in the Rye&quot;,<br>                  &quot;author&quot;: {<br>                    &quot;name&quot;: &quot;J.D. Salinger&quot;,<br>                    &quot;birth_year&quot;: 1919,<br>                    &quot;nationality&quot;: &quot;American&quot;<br>                  },<br>                  &quot;publication_year&quot;: 1951,<br>                  &quot;genre&quot;: &quot;Fiction&quot;<br>                }<br>              ]<br>            }<br><br>        resp.text = json.dumps(data)<br>        resp.status = falcon.HTTP_200</pre><p>Next, create a Python script named app.py inside the bookstoreproject <em>directory</em> with the following content to set up a <em>minimal</em> <em>Falcon</em> <em>application.</em></p><pre>import falcon<br>from resources.book_resource import BookResource<br><br>app = application = falcon.App()<br>app.add_route(&#39;/books/fetch&#39;, BookResource())</pre><h4>Step 2: Test the Falcon application</h4><p>Before moving forward, let’s test our <em>Falcon application</em> to make sure it’s working correctly.</p><pre>$ gunicorn app:app</pre><p>This <em>command</em> tells g<strong><em>unicorn</em></strong> to run the appobject of the <em>Falcon</em> application defined in the app.py file. We will see <strong><em>gunicorn</em></strong> starting and serving the <em>Falcon</em> <em>application</em> on <a href="http://localhost:8000.">http://localhost:8000.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*EEfn2ZQaq5sg1qwfpP8scA.png" /><figcaption>gunicorn running at localhost:8000</figcaption></figure><p>Let’s open our <em>web browser</em> and <em>navigate</em> to <a href="http://localhost:8000/books/fetch.">http://localhost:8000/books/fetch</a> and check the <em>network</em> <em>tab</em> for this webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*qjc4vzSBNTuHX04EoMj5kg.png" /><figcaption>URL: http://localhost:8000/books/fetch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*5qO6FmG0JyYGW2Yznt6U7g.png" /><figcaption>Network Tab</figcaption></figure><p>Here we can see the <em>API call</em> returning a <em>successful</em> <strong><em>HTTP</em></strong> <strong><em>200</em></strong> <em>status</em> <em>code</em> response. We can also see from the <em>API response headers</em> that the webpage is being served by the gunicorn server.</p><h4>Step 3: Configure Nginx</h4><p>Here we will be <em>running</em> <em>nginx</em> on port <em>8081</em>. Hence we will do the following configurations.</p><p>First, we will change the default port to8081at which the <em>nginx server</em> should listen for <em>incoming</em> <em>HTTP</em> requests. Add the following <em>configuration</em> to the serverblock present inside the httpblock of the nginx config file nginx.conf present at the location /etc/nginx.</p><pre>    server {<br>        listen       8081;<br>        server_name  localhost;  # Catch-all server name<br><br>        # Root directory for serving web content<br>        root   /var/www/html;<br><br>        # Location block for handling requests<br>        location / {<br>            # Additional configuration for handling requests<br>        }<br><br>        # Error pages<br>        error_page   500 502 503 504  /50x.html;<br>        location = /50x.html {<br>            root   /usr/share/nginx/html;<br>        }<br>    }</pre><p>Next, create an <em>nginx</em> <em>config</em> file for our Falcon application. It can be created in the /etc/nginx/sites-available/ directory and named as myproject. We also have to symlink it to /etc/nginx/sites-enabled/</p><pre>$ sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/</pre><p>If a separate nginx config file is not opted for, we can also modify the <em>default config file</em> present at /etc/nginx/sites-available/default with the below <em>configuration</em>.</p><pre>server {<br> listen 8081 default_server;<br> listen [::]:8081 default_server;<br><br><br> root /var/www/html;<br><br><br> server_name _;<br><br> location / {<br>            include proxy_params;<br>            proxy_pass http://localhost:8000;  <br><br>        }<br>}</pre><p>The proxy_pass <em>directive</em> in <em>Nginx</em> is used to define a <em>reverse</em> <em>proxy</em> <em>configuration</em>, where <em>Nginx</em> forwards incoming <em>HTTP</em> requests to a backend server, such as <em>Gunicorn</em>. As we already have gunicornserver running at 127.0.0.1 port <em>8000</em>, we will specify the same <em>IP address</em> so that <em>nginx</em> will forward those requests to the <em>actively</em> running <em>gunicorn</em>.</p><p>Once all these configurations are done, we can <em>start</em> the <em>nginx</em> <em>server</em> with the command</p><pre>$sudo systemctl start nginx</pre><p>Now let’s open our <em>web browser</em> and <em>navigate</em> to <a href="http://localhost:8000/books/fetch.">http://localhost:8081/books/fetch</a> and check the <em>network</em> tab for this <em>webpage</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*PDbXO077c9FZTzRGMBfp7g.png" /><figcaption>URL: <a href="http://localhost:8000/books/fetch">http://localhost:8081/books/fetch</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*YgWGixfkD-lio-NI80V_SA.png" /><figcaption>Network Tab</figcaption></figure><p>Here we can see the <em>API call </em>returning a <em>successful</em> <em>HTTP 200 status code</em> response. We can also see from the<em> API response headers</em> that the webpage is being served by the nginx <em>server</em>.</p><p>So we have successfully configured our <em>nginx</em> <em>server</em> to route <em>requests</em> to our <em>Falcon</em> application via the <em>gunicorn</em> <em>WSGI</em> server.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Uegx9BqfqQCCPQRhdya9TA.jpeg" /></figure><p>In conclusion, the <em>combination</em> of <em>Nginx</em>, <em>Gunicorn</em>, and <em>Falcon</em> represents a <em>powerful</em> and <em>efficient</em> stack for <em>building</em> and <em>deploying</em> <em>high-performance</em> web applications and APIs in Python. Each component plays a distinct role in this stack, and together they provide a <em>reliable</em> and <em>scalable</em> solution for handling <em>HTTP</em> <em>requests</em> and serving <em>web</em> <em>content</em>. It enables <em>developers</em> to create highly <em>performant</em> and <em>efficient</em> services while benefiting from the <em>flexibility</em>, <em>security</em>, and <em>scalability</em> provided by these essential components. Whether you are building a<em> small-scale API</em> or a<em> large-scale web application</em>, this stack is well-equipped to meet your requirements for speed, reliability, and security.</p><h4>References</h4><ul><li><strong>Falcon</strong>: <a href="https://falcon.readthedocs.io/en/stable/">https://falcon.readthedocs.io/en/stable/</a></li><li><strong>Gunicorn</strong>: <a href="https://gunicorn.org/#docs">https://gunicorn.org/#docs</a></li><li><strong>How To Serve Flask Applications with Gunicorn and Nginx on Ubuntu 22.04:</strong><a href="https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-22-04"> https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-22-04</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d74000099d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering jq: Advanced Strategies for JSON Data Manipulation]]></title>
            <link>https://medium.com/@samarthgvasist/mastering-jq-advanced-strategies-for-json-data-manipulation-de8b05005d66?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8b05005d66</guid>
            <category><![CDATA[jq]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 07:52:12 GMT</pubDate>
            <atom:updated>2023-09-03T08:53:04.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qf7zIZzeE95fr1fOV9Hkw.png" /></figure><p>When working with <strong>JSON</strong> data in the Linux command line, jq is a <strong><em>powerful</em></strong> and <strong><em>versatile</em></strong> tool. This utility allows us to <em>parse</em>, <em>manipulate</em>, and <em>extract</em> information from JSON documents with ease. In this article, we&#39;ll explore the capabilities of jq and provide a comprehensive guide on how to streamline simple data processing tasks.</p><h3>Overview</h3><h4>What is jq?</h4><p>jq is a <em>lightweight</em> and <em>flexible</em> command-line tool for <em>parsing</em> and <em>manipulating</em> JSON data. It&#39;s designed to work seamlessly with JSON documents, making it an invaluable asset for <em>developers</em>, <em>system</em> <em>administrators</em> and <em>data-analysts</em> working in Linux and other Unix-like operating systems.</p><blockquote>jq is often referred to as the “Swiss Army knife for JSON” due to its versatility and extensive capabilities in working with JSON data.</blockquote><p>jq is widely used for several purposes such as:</p><ol><li><strong>Integration with shell scripts and pipelines</strong>: jqseamlessly integrates with <em>shell scripts</em> and <em>command-line pipelines</em>, making it a versatile tool for <em>data processing</em> in various <em>automation</em> and <em>scripting</em> scenarios.</li><li><strong>Data extraction from APIs</strong>: jqis frequently used in combination with tools like curl to <em>extract</em> and <em>process</em> JSON responses from <em>APIs</em>. It enables us to <em>filter</em> and <em>extract</em> the relevant data from <em>API</em> <em>responses</em> efficiently.</li><li><strong>Log analysis</strong> : jq is valuable for parsing and analyzing log files, particularly when logs are in JSON format. It helps to extract specific fields, filter logs based on certain criteria, and aggregate log data for analysis.</li></ol><p>Before we dive into the functionalities of jq, we have to install it on our system if it&#39;s not already available. We can typically install jq using the system&#39;s package manager. For example, on <em>Ubuntu</em> or <em>Debian</em>-based systems, we can use:</p><pre>sudo apt-get install jq</pre><h3>Usages of jq</h3><h4>1. Pretty-Printing JSON</h4><p>The simplest use of jq is to <em>format</em> <strong><em>JSON</em></strong> data for human readability. This can be easily achieved by piping JSON data into jq with no additional options</p><pre>echo &#39;{&quot;name&quot;:&quot;KGF-2&quot;,&quot;actors&quot;:[&quot;Yash&quot;,&quot;Sanjay Dutt&quot;],&quot;director&quot;:&quot;Prashant Neel&quot;,&quot;language&quot;:&quot;Kannada&quot;,&quot;year&quot;:2022}&#39;| jq</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*QenNR8jc9BCrwq3eM2fz3w.png" /><figcaption>Output</figcaption></figure><h4>2. Selecting Fields</h4><p>jq excels at <strong><em>selecting</em> <em>specific</em> <em>fields</em></strong> from JSON objects.</p><pre>echo &#39;{&quot;name&quot;:&quot;KGF-2&quot;,&quot;actors&quot;:[&quot;Yash&quot;,&quot;Sanjay Dutt&quot;],&quot;director&quot;:&quot;Prashant Neel&quot;,&quot;language&quot;:&quot;Kannada&quot;,&quot;year&quot;:2022}&#39;| jq &#39;.actors&#39; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*p4pQdQjNGzvCOGPuwMmSWw.png" /><figcaption>Output</figcaption></figure><p>It can also be used to <strong><em>select</em></strong> <strong><em>multiple</em></strong> <strong><em>fields</em></strong> as well where each field is specified in a comma-separated format.</p><pre>echo &#39;{&quot;name&quot;:&quot;KGF-2&quot;,&quot;actors&quot;:[&quot;Yash&quot;,&quot;Sanjay Dutt&quot;],&quot;director&quot;:&quot;Prashant Neel&quot;,&quot;language&quot;:&quot;Kannada&quot;,&quot;year&quot;:2022}&#39;| jq &#39;.actors, .director&#39; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*XvKTlORTEVhGnjRhTgyiZA.png" /><figcaption>Output</figcaption></figure><h4>3. Filtering Objects with select</h4><p>jq allows us to <strong><em>filter</em></strong> <strong><em>JSON</em></strong> objects based on specific criteria using the select function.</p><p>We have the following json data in our movies.json file.</p><pre>[<br> {<br>  &quot;name&quot;: &quot;KGF-2&quot;,<br>  &quot;actors&quot;: [&quot;Yash&quot;,<br>       &quot;Sanjay Dutt&quot;],<br>  &quot;director&quot;: &quot;Prashant Neel&quot;,<br>  &quot;language&quot;: &quot;Kannada&quot;,<br>  &quot;year&quot;:2022<br>  },<br>  {<br>  &quot;name&quot;: &quot;RRR&quot;,<br>  &quot;actors&quot;: [&quot;Ramcharan&quot;,<br>     &quot;Jr NTR&quot;],<br>  &quot;director&quot;: &quot;RajMouli&quot;,<br>  &quot;language&quot;: &quot;Telugu&quot;,<br>  &quot;year&quot;:2022<br> },<br> {<br>  &quot;name&quot;: &quot;Kantara&quot;,<br>  &quot;actors&quot;: [&quot;Rishab Shetty&quot;],<br>  &quot;director&quot;: &quot;Rishab Shetty&quot;,<br>  &quot;language&quot;: &quot;Kannada&quot;,<br>  &quot;year&quot;:2022<br> }<br>]</pre><p>Here, let’s write a jq command to <strong><em>filter</em></strong> the <strong><em>movies</em></strong> that belong to the language Kannada .</p><pre>jq &#39;.[] | select(.language == &quot;Kannada&quot;)&#39; movies.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*FR8nU49C0-w8QZIWfpVaNg.png" /><figcaption>Output</figcaption></figure><h4>4. Transforming Objects using map</h4><p>jq supports mapping <em>operations</em>. If we want to <strong><em>transform</em></strong> the JSON data using jq, we can use the map function to apply a <strong><em>transformation</em></strong> to each <strong><em>element</em></strong> in the array.</p><p>Here&#39;s an example of how we can use map to transform the JSON data to return the movie namesand actorsmapping for the movies having Kannada as their <em>language</em>.</p><pre>jq &#39;map(select(.language == &quot;Kannada&quot;) | {(.name): .actors})&#39; movies.json   </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*zDAd3lgfe2GT8CnSoPeITw.png" /><figcaption>Output</figcaption></figure><p>Another simple illustration of the map operation of jqwhere each <em>number</em> in the array is <em>mapped</em> to its corresponding <em>square</em>.</p><pre>echo &#39;[1, 2, 3, 4, 5]&#39; | jq &#39;map(. * .)&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*CLdGv4MA04H4SRIlXUqcvA.png" /><figcaption>Output</figcaption></figure><h4>5. Reduce Operation</h4><p>jq supports reducingoperations, which are powerful for data <em>transformation</em> and <em>aggregation</em>. To calculate the <em>sum</em> of <em>numbers</em> in an <em>array:</em></p><pre>echo &#39;[1, 2, 3, 4, 5]&#39; | jq &#39;reduce .[] as $item (0; . + $item)&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/42/1*kpuvB9VCOfu3fAZ8-6aB5Q.png" /><figcaption>Output</figcaption></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*vZrLicYIT5vBgEQftPBlng.gif" /></figure><p>In conclusion, jq is a <em>versatile</em> and <em>powerful</em> <em>command-line tool</em> for <em>processing</em>, <em>manipulating</em>, and <em>querying JSON data</em>. It <em>simplifies</em> the task of working with <em>JSON structures</em>, making it a valuable asset for <em>engineers</em>, <em>developers</em>, and <em>data professionals</em>. With its ability to extract specific <em>information</em>, <em>transform data</em>, and <em>filter</em> results, jq streamlines tasks involving JSON data, improving <em>efficiency</em> and <em>productivity</em>. Its command-line <em>integration</em>, <em>portability</em>, and <em>simplicity</em> make it a valuable tool for anyone who deals with<em> JSON data </em>regularly. Whether used for parsing <em>API responses</em>, <em>data</em> or <em>log analysis</em>, or <em>automation</em>, jq has proven to be a valuable tool for professionals working with <strong><em>JSON</em></strong> data.</p><h3>References</h3><ul><li><strong>jq manual</strong>: <a href="https://jqlang.github.io/jq/">https://jqlang.github.io/jq/</a></li><li><strong>Hands-On jq playground</strong>: <a href="https://www.devtoolsdaily.com/jq_playground/">https://www.devtoolsdaily.com/jq_playground/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8b05005d66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parameterized Unit Testing in Python]]></title>
            <link>https://medium.com/@samarthgvasist/parameterized-unit-testing-in-python-9be82fa7e17f?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be82fa7e17f</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 13:23:00 GMT</pubDate>
            <atom:updated>2023-06-03T13:23:00.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_nmx61hZ_VYbNARkQtNmQA.png" /></figure><p><strong><em>Unit Tests</em></strong> form an integral part of the <em>development</em> <em>process</em>. Its main objective is to ensure that each <em>individual</em> <em>module</em> is working as expected. <em>Unit testing</em> refers to <em>testing</em> the <em>modules</em> <em>independently</em> and mainly focuses on testing the <strong><em>functional behaviour</em></strong> of each <strong><em>method</em></strong>/<strong><em>function</em></strong>. <strong><em>Unit testing</em></strong> is performed by the <em>software</em> <em>developers</em> themselves, and occasionally independent <em>software</em> <em>testers</em> also perform these tests.</p><h4><strong>Importance of Unit Tests: Test Automation Pyramid</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*jFWUavfhVqYPmMzp4kJn_w.png" /><figcaption>Test Automation Pyramid</figcaption></figure><p>As we can see from the <strong><em>Test Automation Pyramid</em></strong>, <em>unit tests</em> are positioned at the <em>base</em>, forming the <em>foundation</em> of the <em>pyramid</em>.</p><p>Here are some <em>key</em> <em>characteristics</em> of <em>unit tests</em> in the<strong> <em>test</em> <em>automation</em> <em>pyramid</em></strong>:</p><ul><li><strong><em>Independent</em></strong>: <em>Unit tests</em> are designed to be <em>isolated</em> from external dependencies such as <em>databases</em> and <em>third-party libraries</em>. <em>Mocks</em> or <em>stubs</em> are often used to simulate the <em>behaviour</em> of these <em>dependencies</em>, allowing the unit test to focus solely on the specific <em>unit of code</em> being tested.</li><li><strong><em>Fast Execution</em></strong>: The <em>fast execution</em> of <em>unit tests</em> allows for frequent <em>execution</em>, enabling <em>developers</em> to <em>iterate</em> and make <em>changes</em> with <em>confidence</em>.</li><li><strong><em>Method Focus</em></strong>: <em>Unit tests</em> typically have a narrow <em>focus</em>, targeting specific <em>units</em> of <em>code</em>. By <em>isolating</em> the tests into small units, it becomes easier to <em>debug</em> <em>issues</em> when <em>failures</em> occur.</li><li><strong><em>Test Coverage</em></strong>: <em>Unit tests </em>contribute to the <em>overall test coverage</em> of the system. As they verify the behaviour of individual units, they provide a solid foundation for higher-level tests, such as <em>integration</em> or <em>end-to-end</em> <em>tests</em>.</li></ul><h4><strong>Parameterized Unit Tests</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*OW7ux3e0ZBZRTlYf9e880Q.png" /></figure><p><strong><em>Parameterized unit tests</em></strong> in Python are a <em>testing</em> <em>technique</em> that allows us to <em>define</em> and <em>execute</em> <em>test cases</em> with different sets of <em>input test data</em>. It involves <em>creating</em> <em>test methods</em> or <em>functions</em> that <em>accept</em> <em>parameters</em> and then <em>running</em> these <em>tests</em> with various <em>input values</em> to <em>validate</em> the <em>behaviour</em> of the <em>code</em> under test.</p><p>The main idea behind <em>parameterized</em> <em>unit</em> <em>tests</em> is to write a <em>single test method</em> or <em>function</em> that can be executed <em>multiple</em> times with different <em>input</em> <em>values</em> rather than writing <em>separate</em> <em>test</em> <em>cases</em> for each <em>specific</em> <em>input</em> <em>scenario</em>. This approach reduces <strong><em>code duplication </em></strong>and improves <strong><em>test maintainability</em></strong>. Some of the other <em>advantages</em> of <em>parameterized</em> <em>unit</em> <em>tests</em> are:</p><p><strong><em>Increased Test Coverage</em></strong>: By varying the<em> input parameters</em>, we can ensure that different <em>scenarios</em> and <em>edge cases</em> are considered leading to more comprehensive <em>testing</em></p><p><strong><em>Flexible Test Data Generation</em></strong>: If any <em>new test data</em> needs to be added for unit testing, <em>parameterization</em> allows us to just add the new test data in the form of input parameters, <em>eliminating</em> the need for <em>verbose</em> code and facilitating <em>easy</em> <em>test data generation.</em></p><h4>Implementation</h4><p>In this article, we will see how we can perform <em>unit testing</em> in <em>Python</em>, along with learning how<em> parameterized unit tests</em> offer <em>additional</em> <em>advantages</em> for the same.</p><p>As a prerequisite, the required <strong><em>Python libraries</em></strong> to be installed are unittest, pytestand parameterized. These <em>frameworks</em> allow us to define <em>test cases</em> with <em>parameters</em> and provide mechanisms for <em>generating</em> and <em>executing</em> <em>tests</em> with <em>different inputs.</em></p><p>Let’s implement a simple <em>python</em> <em>class</em> named movie_service.pyfor which we will be writing <em>unit tests</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*qyeWZttu7nLaHZK-3aW_xw.png" /></figure><p>Let’s write <em>unit tests</em> using parameterizedfor the above MovieServiceclass.</p><p>Our first case basically involves sending an <em>invalid</em> <em>input</em> for the movie_service_handler <em>method </em>and testing if the Exceptionis raised. As seen from the <em>code</em> <em>above</em> we know that either one of the input parameters <em>year</em> or <em>language</em> input has to be sent for the function. If none of them is sent or if both are sent an Exceptionis raised.</p><pre>@parameterized.expand([<br>        (None, None),<br>        (&#39;2022&#39;, &#39;Kannada&#39;),<br>        (&#39;2021&#39;, &#39;Hindi&#39;),<br>        (&#39;2011&#39;, &#39;English&#39;)<br>    ])<br>  def test_invalid_input(self, year, language):<br>        service = MovieService(self.movie_store)<br>        with self.assertRaises(Exception):<br>            service.movie_service_handler(year, language)</pre><p>Here with the help of parameterizedwe can see that different types of <em>invalid</em> <em>input</em> <em>data</em> are being passed and they are grouped under a single test case named test_invalid_input .</p><p>Next, we have a case where we want to validate that a <em>particular</em> <em>method</em> is <em>called once.</em></p><pre>@parameterized.expand([<br>        (&#39;2022&#39;, None),<br>        (&#39;2021&#39;, None),<br>        (&#39;2011&#39;, None)<br>    ])<br>    @patch(&#39;movie_service.MovieService.get_movies_by_year&#39;)<br>    def test_movie_handler_year_input(self, year, language, mock_movies_getter):<br>        service = MovieService(self.movie_store)<br>        service.movie_service_handler(year, language)<br>        mock_movies_getter.assert_called_once()<br>        <br>    <br>    @parameterized.expand([<br>        (None, &#39;Kannada&#39;),<br>        (None, &#39;Tamil&#39;),<br>        (None, &#39;Hindi&#39;)<br>    ])<br>    @patch(&#39;movie_service.MovieService.get_movies_by_language&#39;)<br>    def test_movie_handler_language_input(self, year, language, mock_movies_getter):<br>        service = MovieService(self.movie_store)<br>        service.movie_service_handler(year, language)<br>        mock_movies_getter.assert_called_once()</pre><p>Here with the help of @patch <em>annotation</em> we are <em>mocking</em> our methods get_movies_by_year and get_movies_by_language .</p><p>Read about @patch annotation <a href="https://docs.python.org/3/library/unittest.mock.html">here</a></p><p>As seen from our mock_service_handler method, when the <em>year</em> parameter is present, the get_movies_by_year <em>method</em> gets called and if the <em>language</em> <em>parameter</em> is present, the get_movies_by_language <em>method</em> is called. Hence this test case is used to <em>assert</em> if the<em> correct methods</em> are being called for the right set of <em>input</em> <em>parameters</em>.</p><p>Let’s have a look at our completeTestMovieService class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAbWQM4xEdbxDrOY5SleUw.png" /></figure><p><strong>Test Case Execution</strong></p><p>For executing the above test case use any one of the following commands</p><pre>$ pytest  ( runs all the test files in the directory )<br>$ python -m unittest test_movie_service.py (runs specified test file )<br>$ pytest test_movie_service.py (runs specified test file )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKuEH8P_uveDFuLoUCwDFQ.png" /></figure><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*q7CguhaoyM8uiPMyrmKIlg.png" /></figure><p><em>Organizations</em> give utmost <em>focus</em> to <em>unit tests</em>, and there are strict rules that the test coverage for a particular <em>code base</em> should always be above a certain threshold (80–90% in most cases). <em>Unit tests</em> are generally run in <em>CI/CD</em> environments during the <strong><em>code build</em></strong>, which gives a <em>detailed report</em> of the lines of code <em>covered</em> and <em>missed</em>. The overall idea should not be just to <em>maximize</em> the <em>test coverage</em> but to add meaningful <em>test cases</em> that focus on <em>testing</em> the <em>core functional behaviour</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*bSd2XkI0xcNwgVT29tId_A.png" /></figure><blockquote>Unit tests directly contribute to the code quality of the organization. Many organizations use code quality tools to continuously measure the code quality and to ensure that coding standards are strictly followed. One of the most widely used Code Quality tools is sonarqube. SonarQube gives a thorough report on the code quality, code smells, test coverage percentage and various potential vulnerabilities which can help in the overall code quality.</blockquote><p>Hence, let’s always make sure that <em>appropriate</em> <em>unit</em> <em>tests</em> are written for every minor code change and contribute to the <em>overall</em> <em>code</em> <em>quality</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be82fa7e17f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building RESTful Web Applications using SpringBoot and MongoDB]]></title>
            <link>https://medium.com/@samarthgvasist/building-restful-web-applications-using-springboot-and-mongodb-98ea2667c95?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ea2667c95</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 16:55:02 GMT</pubDate>
            <atom:updated>2023-04-30T16:55:02.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsgllqdRFQnH0a2yGtWHWw.png" /></figure><blockquote>Springboot, one of the most popular Java frameworks, is widely used to develop web applications. MongoDB, on the other hand, is a popular document-oriented NoSQL database that provides flexible data storage and retrieval capabilities. Spring Boot provides excellent support for building RESTful web services, which can be integrated with MongoDB to create robust, scalable, and maintainable applications. With Spring Boot’s powerful abstraction capabilities, developers can easily build complex queries and retrieve data from MongoDB.</blockquote><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*r_JZ3zC0z2r1iaX8JPCWag.png" /></figure><p><strong>MongoDB</strong> is a popular <em>NoSQL</em> <em>document-oriented database</em> that stores data in flexible, <em>JSON-like documents</em>, making it ideal for handling <em>unstructured</em> or <em>semi-structured</em> data. One of the key features of MongoDB is its ability to scale <em>horizontally</em> by <em>distributing</em> <em>data</em> across <em>multiple</em> <em>servers</em>, making it suitable for handling large amounts of data in high-traffic web applications. It also offers features such as <em>automatic sharding, replication,</em> and <em>load balancing</em> for managing data across <em>distributed</em> <em>clusters</em>.</p><p>In this article, we will see how to build a <strong><em>RESTful</em></strong> web application using <strong>Java SpringBoot</strong> and <strong>MongoDB</strong> as the database. We will be building a <em>web</em> <em>application</em> for a movie <em>database</em> where we will be <em>creating</em> <em>APIs</em> for <em>adding</em> a <em>movie record</em> and <em>fetching</em> the <em>movies</em> by <em>filtering</em> on the <em>year</em> of release and on their <em>genre</em>.</p><p>Our setup involves having a <strong>MongoDB server </strong>running <em>locally</em> on port 27017. In our case, we are running <em>MongoDB</em> as a <em>docker</em> <em>container</em> as it is simpler to manage.</p><ul><li><strong><em>Docker image</em></strong>: docker pull mongo</li><li><strong><em>Docker container</em></strong>: docker run -d --name mongo-on-docker -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin mongo</li></ul><h4>Code Implementation</h4><p>The following is the directory structure of our Springboot project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*WIJStHGzJzaHLyqXWoci0w.png" /><figcaption>Project Structure</figcaption></figure><p><strong>Gradle Build Automation</strong></p><p>We will be using thegradle <em>build automation tool</em> to define and configure the project’s <em>build</em> process. Thebuild.gradle script consists of the build <em>configuration</em>, <em>plugins</em>, <em>tasks</em>, and <em>dependencies</em> required to build the spring-boot project. Let’s add the required <em>plugins</em> and <em>dependencies</em> to the build.gradle script.</p><pre>plugins {<br> id &#39;java&#39;<br> id &#39;org.springframework.boot&#39; version &#39;2.6.1&#39;<br> id &#39;io.spring.dependency-management&#39; version &#39;1.1.0&#39;<br>}<br><br>group = &#39;com.indiancinema&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br>sourceCompatibility = &#39;11&#39;<br><br>configurations {<br> compileOnly {<br>  extendsFrom annotationProcessor<br> }<br>}<br><br>repositories {<br> mavenCentral()<br>}<br><br>dependencies {<br> implementation &#39;org.springframework.boot:spring-boot-starter-data-mongodb&#39;<br> implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br> implementation &#39;org.springframework.boot:spring-boot-starter-validation&#39;<br> compileOnly &#39;org.projectlombok:lombok&#39;<br> annotationProcessor &#39;org.projectlombok:lombok&#39;<br> testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br> useJUnitPlatform()<br>}</pre><p><strong>Models</strong></p><p>The Movie model is the main <em>model</em> class that we will be creating. It will consist of the following attributes:</p><ul><li>id: <em>unique</em> ID for an individual document across the <em>Movie</em> collection using the @Id annotation.</li><li>movieName: <em>name</em> of the movie</li><li>language: <em>language</em> of the movie</li><li>genre: <em>list</em> of <em>genres</em> that the movie comes under</li><li>year: <em>year</em> of release of the movie</li><li>rating: <em>rating</em> given for the movie</li></ul><p>Here we are using the @Data and @AllArgsConstructor annotations of lombok to avoid <em>boilerplate</em> code for generating <em>getters</em>, <em>setters</em>, and <em>constructors</em>. The @Document(collection=”Movie&quot;)specifies that the <em>movie</em> <em>documents</em> will be stored under the <em>collection</em> name Moviein the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cB3l0clOhgLxHkJ1xDubjQ.png" /><figcaption>Movie class</figcaption></figure><p>The GenreRequest model class is used to specify the <em>input</em> <em>request</em> for fetching the movie records that fall under the <em>genres</em> mentioned in the <em>request</em> body of the client. It has a single attribute:</p><ul><li>genre: <em>Specifies</em> the <em>list</em> of <em>genres</em> for which the <em>movies</em> have to be <em>fetched</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypZV_h2jxjJDxfyywR-IFg.png" /><figcaption>GenreRequest class</figcaption></figure><p><strong>MovieRepository</strong></p><p>Next, we come to the <strong><em>Data Access Object (DAO)</em></strong> layer which provides access to the underlying <em>database</em> <strong>MongoDB</strong>. We create a MovieRepositorywhich extends the MongoRepository interface and provides us access to our Movie Collection. Here we specify the necessary <em>Mongo</em> <em>queries</em> that are needed to <em>fetch</em> the required <em>documents</em>. We perform the following queries:</p><ul><li>@Query(&quot;{id: ?0&quot;) : where we fetch an <em>individual</em> <em>movie</em> <em>record</em> by specifying its <em>unique ID.</em></li><li>@Query(&quot;{year: ?0}&quot;) : where we fetch all the <em>movie records</em> released during the specified <em>year</em>.</li><li>@Query(&quot;{genre:{$all: ?0}}&quot;) : where we fetch all the <em>movie records</em> that come under the <em>genres</em> specified in the <em>list</em>.</li></ul><p>The <em>placeholder</em> ?0 lets us substitute the value from the <em>method</em> <em>arguments</em> into the JSON query string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqLlaxLGpiRpvA5Fo-_YVw.png" /><figcaption>MovieRepository Interface</figcaption></figure><p><strong>MovieController</strong></p><p>Next in the <em>controller</em> component, the <strong><em>Rest APIs</em></strong> are specified. Here we have the following RestApi endpoints:</p><ul><li>@PostMapping(&quot;/movies&quot;) : this end-point allows only a POSTcall and is used to <em>send</em> <em>movie data</em> in the <em>API request body</em> from the <em>client</em> side to the <em>server</em> for storing in the <em>database</em>.</li><li>@GetMapping(&quot;/movies/{id}&quot;) : this end-point allows a GETcall and is used to <em>fetch</em> a <em>movie</em> record specified by the id</li><li>@GetMapping(&quot;/movies/fetch&quot;) : this <em>API</em> end-point allows a GETcall and is used to fetch <em>movie records</em> <em>released</em> in a specified <em>year</em> if the year query parameter is supplied. If the query parameter is not specified, it returns all the <em>movie</em> <em>records</em> present in the <em>database</em>.</li><li>@PostMapping(&quot;/movies/fetch&quot;) : this API end-point allows a POSTcall and is used to fetch <em>movies</em> that fall under the <em>genres</em> that are specified in the <em>API request body.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo5jhXUTEsP_A6IxBiywuw.png" /><figcaption>MovieController class</figcaption></figure><p><strong>Configurations</strong></p><p>In <strong>Spring Boot</strong>, the application.properties file is a <em>configuration</em> <em>file</em> that is used to configure the various aspects of the application, such as <em>database</em> <em>settings</em>, <em>server configurations, logging, security</em> and more. Here we have the following configuration changes:</p><ul><li>server.port : specifies that our <em>web application</em> will run on port <em>8081</em>.</li><li>spring.data.mongodb.authentication-database : specifies the <em>authentication</em> <em>database</em> for connecting to the <strong>MongoDB</strong> <em>instance</em>.</li><li>spring.data.mongodb.username : specifies the <em>username</em> for connecting to the <strong>MongoDB</strong> <em>instance</em> that requires <em>authentication</em>.</li><li>spring.data.mongodb.password : specifies the <em>password</em> for connecting to the <strong>MongoDB</strong> <em>instance</em> that requires <em>authentication</em>.</li><li>spring.data.mongodb.database : specifies the <em>database</em> in which we want to store our collection. (here IndiaCinemas)</li><li>server.servlet.context-path : specifies the <em>context path</em> for a <em>web application.</em> ( here /indian-cinemas )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RObz2pIUewxFFDy-MIQiiQ.png" /><figcaption>application.properties</figcaption></figure><p>Finally, let’s run our <em>Springboot</em> <em>application</em> using the below <em>command</em>:</p><pre>$./gradlew bootRun</pre><h4>API Testing using cURL</h4><p>In order to test our <strong><em>Rest API endpoint</em></strong> we use cURL, a <strong><em>command-line tool</em></strong> for sending <em>HTTP</em> <em>requests</em> to a <em>server</em>.</p><p><strong>Register Movie</strong>: http://localhost:8081/indian-cinemas/movies</p><pre>curl --location &#39;http://localhost:8081/indian-cinemas/movies&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;movie_id&quot;: 2,<br>    &quot;movie_name&quot;: &quot;Kantara&quot;,<br>    &quot;language&quot;: &quot;Kannada&quot;,<br>    &quot;genre&quot;: [&quot;Action, Adventure, Drama&quot;],<br>    &quot;year&quot;: 2022,<br>    &quot;rating&quot;: 9<br>}&#39; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9A1daiCVIzVrxNcZhwmF0g.png" /><figcaption>Register Movie API response</figcaption></figure><p><strong>Fetch movies by year</strong>: http://localhost:8081/indian-cinemas/movies/fetch?year=2022</p><pre>curl --location &#39;http://localhost:8081/indian-cinemas/movies/fetch?year=2022&#39; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuRSB1_Qbit_ClyBENA26g.png" /><figcaption>API Response</figcaption></figure><p><strong>Fetch movies by Id</strong>: <a href="http://localhost:8081/indian-cinemas/movies/fetch?year=2022">http://localhost:8081/indian-cinemas/movies/</a>1</p><pre>curl --location &#39;http://localhost:8081/indian-cinemas/movies/1&#39; | jq &#39;.&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brOLfjH3OzCxOqNPEUO0Cg.png" /><figcaption>API Response</figcaption></figure><p><strong>Fetch movies by genre</strong>: <a href="http://localhost:8081/indian-cinemas/movies/fetch?year=2022">http://localhost:8081/indian-cinemas/movies/</a>fetch</p><pre>curl --location &#39;http://localhost:8081/indian-cinemas/movies/fetch&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;movie_genre&quot;: [&quot;Action&quot;]<br>}&#39; | jq &#39;.&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pvp53LzrTKaJqfZpg6X2kw.png" /><figcaption>API Response</figcaption></figure><h4>Mongo Documents</h4><p>Here we can see that ourMovie documents are stored under the Movie Collection of the IndianCinemas database in <strong>MongoDB</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWmMyel52cVF_zzIGHWo-A.png" /><figcaption>MongoDB Compass</figcaption></figure><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*WkTdlTi5SHCul62RcPC6lA.png" /></figure><p>Now we know how to build a <em>restful web application</em> using <strong>SpringBoot</strong> and <strong>MongoDB</strong>. As an extension to the article, you can build several other <em>API</em> <em>endpoints</em>, try out other <em>Mongo queries</em>, and analyze their results. In recent years, <strong>MongoDB</strong> has seen significant growth in popularity as a result of its <em>flexibility</em>, <em>scalability</em>, and <em>ease of use</em>. Its <em>popularity</em> is particularly high in the <em>web</em> and <em>mobile</em> <em>application</em> <em>development</em> communities, where its support for <em>dynamic, semi-structured data models</em> and <em>distributed</em> <em>data</em> <em>architectures</em> is highly valued. In summary, <strong>Spring Boot</strong> with <strong>MongoDB</strong> is an <em>excellent</em> choice for building <em>modern web applications</em> that require <em>fast data access,</em> <em>flexible data storage,</em> and seamless <em>integration</em> with other <em>technologies</em>.</p><blockquote>A major percentage of the web still powered by Java, Springboot dominates the Java ecosystem with about 60% using it for their main applications which makes it a very powerful and popular framework to learn. So if you aspire to be a Java developer and stuck thinking on how to build a career , SpringBoot is definitely a place to start with!!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ea2667c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling in the Cloud: An Introduction to AWS Auto Scaling Groups]]></title>
            <link>https://medium.com/@samarthgvasist/scaling-in-the-cloud-an-introduction-to-aws-auto-scaling-groups-f7bb1ccd8e51?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7bb1ccd8e51</guid>
            <category><![CDATA[aws-auto-scaling]]></category>
            <category><![CDATA[auto-scaling-groups]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 19:25:58 GMT</pubDate>
            <atom:updated>2023-04-06T19:25:58.546Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2F485bf5SUuyqNd8&amp;display_name=SlideShare&amp;url=https%3A%2F%2Fwww.slideshare.net%2FSamarthVashist%2Fnarrativepdf&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fastoryof2friends-230406190614-67945d57-thumbnail.jpg%3Fwidth%3D640%26amp%3Bheight%3D640%26amp%3Bfit%3Dbounds&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fbe2371b366ae2da6135464399b1bea/href">https://medium.com/media/0fbe2371b366ae2da6135464399b1bea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*p3XNrWRv1zryeXVZu0Xa_g.png" /></figure><blockquote>One of the advantages of cloud computing is the ability to scale up the infrastructure quickly to meet dynamically varying requirements. AWS (Amazon Web Services), a renowned cloud service provider is widely used by companies. AutoScaling Groups in AWS is a service that automatically manages the servers or AWS EC2 instances based on a scaling policy that ensures that the application performs optimally as per user demands at the lowest possible price.</blockquote><h4>What is an Auto Scaling Group?</h4><p>An <strong>Auto Scaling Group (ASG)</strong> is a group of <strong>EC2 (Elastic Compute Cloud)</strong> instances that are automatically launched and terminated based on demand. <strong>Auto-Scaling</strong> is a mechanism that ensures that our resources are automatically <em>increased</em> or <em>decreased</em> to meet the requirements based on the defined <em>scaling policies</em>.</p><p>An ASG <em>monitors</em> the <em>health</em> of the <em>instances</em> it manages and automatically adjusts the number of instances in response to changes in requirements. The purpose of an ASG is to ensure that we have a sufficient number of instances running to handle the current level of traffic and also minimise costs by <em>scaling down</em> when <em>traffic</em> <em>decreases</em>. This helps to maintain the right balance between <em>performance</em> and <em>cost</em>.</p><h4>How does an Auto Scaling Group work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*5g9Jh9AI3cAvBkrjt_5wsw.png" /></figure><p><strong><em>Auto Scaling Groups</em></strong> are generally created using a <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-template.html"><em>launch template</em></a>. While creating the launch template we specify the <strong><em>AMI (Amazon Machine Image)</em></strong> as well as the required <a href="https://aws.amazon.com/ec2/instance-types/"><em>instance types</em></a> and their respective configurations.</p><p>After creating a launch template, during the <em>creation</em> of the <em>AutoScaling Group</em>, we have to specify the <em>minimum</em>, <em>desired</em> and a <em>maximum</em> number of <em>instances</em> that are required to run our <em>application</em> at any given instance of time.</p><p><strong>Scaling Policy</strong></p><p><strong><em>Scaling policies</em></strong> determine the <em>parameters</em> or <em>criteria</em> on which the scaling of the <em>instances</em> in the <strong><em>Auto Scaling Group</em></strong> depends. <strong><em>Auto Scaling Groups</em></strong> can be triggered by various events such as scheduled times and metrics like <em>CPU utilization</em> or <em>network traffic</em>. When a scaling event is triggered, the ASG launches or terminates instances as needed to maintain the desired number of running instances.</p><p>The <em>ASG</em> monitors the <em>health</em> of the <em>instances</em> it <em>manages</em>, using either <em>EC2 instance status checks</em> or <em>custom health checks</em> that you define. If an instance fails a health check, the ASG <em>terminates</em> it and launches a new instance in its place. If demand <em>increases</em>, the ASG will launch <em>additional instances</em> up to the <em>maximum number</em> specified. If demand <em>decreases</em>, the <strong><em>ASG</em></strong> will <em>terminate</em> <em>instances</em> down to the <em>minimum</em> number specified.</p><p>One of the widely used <em>dynamic scaling policies</em> is based on <strong><em>CPU Utilization</em></strong>. Here we can specify a particular threshold for the same. For example, if we specify that the CPU Utilization is 60%, whenever this metric gets breached or exceeded, a new healthy instance will be launched bringing down the <strong><em>CPU utilization</em></strong> for the entire ASG. In the same way, once the CPU utilization reduces, it terminates the instance and keeps one healthy instance.</p><p><strong>Best Practices while Using Auto Scaling Groups</strong></p><ol><li><strong><em>Choosing the right instance type</em></strong>: It is important to make sure that we are using instances that are appropriate for your <em>workload</em>. Choosing the right instance type can have a big impact on <em>performance</em> and <em>cost</em>. ASG allows us to use a mix of <em>on-demand</em> as well as <em>on-spot</em> instances thus helping in saving <em>costs</em> as well as ensuring <em>optimal performance</em>.</li><li><strong><em>Monitoring</em></strong>: We need to set up <em>health checks</em> to ensure that our <em>instances</em> are running properly. If an instance fails a health check, it will be <em>terminated</em> and <em>replaced</em> with a new <em>instance</em>. <em>Effective monitoring</em> of metrics via <em>Cloudwatch</em> as well as from the <em>activity history</em> helps to understand the <em>event-driven behaviour</em> of the <em>ASG</em>.</li><li><strong><em>Use scaling policies wisely</em></strong>: It is important to use <em>scaling policies</em> that are <em>appropriate</em> for our workload or use case. For example, one of the use cases may require us to scale up the <em>ASG</em> based on the <em>requests per target</em> metric and another might require us to scale up based on <em>CPU utilization.</em></li></ol><h4><strong>Benefits of AWS ASG</strong></h4><ul><li><strong><em>Reliability</em></strong>: <em>ASGs</em> ensure that your application remains <em>highly available</em> even if one or more instances fail. When an instance fails, the <strong><em>ASG</em></strong> will <em>automatically</em> launch a <em>replacement instance </em>to maintain the <em>desired</em> <em>capacity</em>.</li><li><strong><em>Scalability and Better Cost Management</em></strong>: <em>ASGs</em> can help save costs by automatically scaling down your application during periods of low demand.</li></ul><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*V8zEeu69cjcIuRN0DPsoJQ.png" /></figure><p><strong><em>Auto Scaling Groups </em></strong>in AWS are a powerful tool that can help you quickly and easily scale your infrastructure to meet changing demands. With ASGs, we can easily manage different types of <em>applications</em> and <em>workloads</em>, and <em>integrate</em> with other <em>AWS</em> <em>services</em> to <em>monitor</em> and <em>manage</em> your application’s <em>performance</em>. By following <em>best practices</em> and keeping an eye on <em>performance</em> and <em>cost</em>, we can ensure that we are getting the most out of this tool while <em>minimizing costs</em> and <em>maintaining performance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7bb1ccd8e51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Schedule Tasks with Python CronJob: A Step-by-Step Guide]]></title>
            <link>https://blog.devops.dev/how-to-schedule-tasks-with-python-cronjob-a-step-by-step-guide-c6ceadee7619?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ceadee7619</guid>
            <category><![CDATA[shellscripting]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[cronjob-scheduler]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 10:02:58 GMT</pubDate>
            <atom:updated>2023-03-25T10:02:58.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*364JlpTPeO6j1WVEhHzo0g.png" /></figure><h4>Introduction</h4><p><strong><em>Cron</em></strong> is a <em>time-based job scheduler</em> in <em>Unix</em> and <em>Linux</em> operating systems that allows users to <em>automate</em> the <em>execution</em> of <em>tasks</em> at specific <em>intervals</em>. It is a powerful tool that can save time and effort by eliminating the need for manual intervention in repetitive tasks.</p><p>Using cron we can automate repetitive tasks. When you have a task that needs to be performed on a regular basis, it can be time-consuming to manually execute it every time. A cron scheduler allows you to automate the task, freeing up your time to focus on other important activities.</p><h4>Implementation</h4><p>In this article, we will have a look at how we can set up a simple cron task that will run at a scheduled interval.</p><p>We will be writing a simple <em>python</em> <em>script</em> that will be executed at a fixed interval (at every <em>minute</em> in our case here). For clearer understanding, we will be creating a separate <em>directory</em> called <em>crondir</em> and placing our python script named script.py.</p><pre>$mkdir ~/crondir<br>$vi script.py</pre><pre>from datetime import datetime<br><br>if __name__ == &#39;__main__&#39;:<br> current_time = datetime.now()<br> print(&quot;Execution Time = &quot;, current_time.strftime(&#39;%d-%m-%Y %H:%M:%S&#39;))</pre><p>This is a simple <em>python</em> code that <em>logs</em> the time of <em>execution</em> which basically indicates the <em>time</em> at which the script ran.</p><p>Now let’s set up the <em>cron</em> job to execute the above script every minute and the <em>output</em> of <em>execution</em> which is basically the <em>log line</em> indicating the <em>time</em> of <em>execution</em> will be <em>logged</em> into a log file. This <em>logging</em> onto an <em>output</em> file will be used to <em>validate</em> the correct working of our <em>cron scheduler</em>.</p><p>To set up a <em>cron scheduler</em> we have to specify the required <em>cronjob</em> entry in the <em>crontab</em>. The <em>crontab</em> command is used to <em>create</em>, <em>modify</em>, and <em>list</em> the cron jobs that are scheduled to run. Cron job entries are written in a specific format that specifies when the task should be run. The format is as follows:</p><pre>* * * * * command</pre><p>The five <em>asterisks</em> represent the time and date parameters for the cron job. The <em>first</em> asterisk represents the <em>minute</em>, the <em>second</em> asterisk represents the <em>hour</em>, the <em>third</em> asterisk represents the <em>day of the month</em>, the <em>fourth</em> asterisk represents the <em>month</em>, and the <em>fifth</em> asterisk represents the <em>day of the week.</em> The command that follows the asterisks is the task that will be executed.</p><blockquote><a href="https://crontab.guru/">CronTabGuru</a> is a free online tool that helps users generate cron expressions for scheduling tasks in Unix and Linux operating systems. This can be super useful when you want to generate custom cron expressions based on your use-case or intended time of task scheduling.</blockquote><p>In our case since we intend to run our script every minute we will be going with the cron expression * * * * *. As we want to run the python script, the command which we want to execute in our case will basically involve us to <em>invoke</em> the required <em>Python</em> <em>interpreter</em> or executable by providing its respective path and later providing the path of our python script that needs to be executed.</p><p>This can also be done using a simple Linux command</p><pre>$ which python3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*-DlvhN0tU0Q-icoMMoH-MQ.png" /></figure><p>In our case, the<strong><em> python3 interpreter</em></strong> is present at location <em>/usr/bin/python3</em> which is generally the default location of <em>python3</em> installation, unless installed in a virtual environment.</p><p>So the command we will be executing in the cron will be</p><pre>/usr/bin/python3 ~/crondir/script.py &gt;&gt; ~/crondir/cron_output.log</pre><p>Here as mentioned earlier we will be <em>logging</em> the <em>output</em> of our file to a log file located in the same directory as the python script.</p><p>Now let’s add the above <em>cronjob</em> entry to the <em>crontab</em>. To edit the crontab, we can use the command:</p><pre>$ crontab -e</pre><p>Now let’s add the <em>cronjob</em> in the mentioned format.</p><pre>$ * * * * * /usr/bin/python3 ~/crondir/script.py &gt;&gt; ~/crondir/cron_output.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*LWoZr66qxxoohd3iMkJ_XQ.png" /></figure><p>Let’s wait for a few minutes and look at our output logs i.e cron_output.log file present in the <em>crondir</em> directory.</p><pre>$ tail -f cron_output.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*JujmzuXvjrPPMFJDbABseg.png" /></figure><p>From the above image, we see the <em>logs</em> of <em>execution</em> which are <em>consistent</em> with a <em>one-minute interval</em> between them, in turn validating the <em>correctness</em> of our <em>python</em> <em>script</em> as well as our <em>cron scheduler.</em></p><p>The running cronjob can also be verified from the <em>system logs</em> as well using the command.</p><pre>$ cat /var/log/syslog | grep cron</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUFjuYzRGNd1DeF5y6qP_w.png" /></figure><p>The above exercise was done by having a simple python script in place and can be extended to scheduling more<em> complex workflows</em>.</p><h4>Conclusion</h4><p>In conclusion, using a cron scheduler can save significant time and effort. With a <em>cron scheduler</em>, we can <em>automate</em> tasks, reducing the need for manual intervention. As such, it is an essential tool for users who want to streamline their workflow, increase <em>efficiency</em>, and <em>save time</em> and <em>effort</em>. Although <em>cron</em> is very useful in automating manual tasks by scheduling them, it does have certain pitfalls. It is <em>not</em> very <em>flexible</em> for <em>scheduling too complex workflows</em> requiring multiple operations. It is <em>difficult</em> to debug issues as it requires additional effort to set up logging. It is not <em>scalable</em> as it is generally executed in a single machine causing it to be a <em>single point of failure</em>. In response to the above disadvantages, <em>Apache Airflow</em> is generally used extensively to set up complex workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ceadee7619" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/how-to-schedule-tasks-with-python-cronjob-a-step-by-step-guide-c6ceadee7619">How to Schedule Tasks with Python CronJob: A Step-by-Step Guide</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpringBoot Caching: A Beginner’s Guide]]></title>
            <link>https://medium.com/@samarthgvasist/springboot-caching-a-beginners-guide-4698b55f1469?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4698b55f1469</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 06:43:56 GMT</pubDate>
            <atom:updated>2023-03-19T06:43:56.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*DJQc2jmURGwCEwbASoCUVg.png" /></figure><blockquote>In today’s fast-paced world of software development, performance is often a key concern for developers. One way to improve application performance is through the use of caching. Caching is a technique that involves storing frequently accessed data in memory or other caching technologies, thereby reducing the time it takes to retrieve the data from an external source.</blockquote><p><strong><em>Spring Boot</em></strong>, a popular <em>Java-based framework</em> for building web applications, provides support for <em>caching</em> through the Spring Framework’s caching abstraction.</p><p>In this article, we’ll take a closer look at <strong>Spring Boot caching</strong>, including how it works and how to configure caching in a Spring Boot application.</p><h4>Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*CbVrU8jnkotsSqV0vwpJgA.png" /></figure><p><strong><em>Cache</em></strong> is a <em>temporary storage area</em> that stores frequently accessed data or resources in order to speed up subsequent access to them. It typically stores data in the form of <em>key-value pairs</em>. Each piece of data or resource that is stored in the cache is associated with a <em>unique key</em>, which is used to quickly <em>retrieve</em> the data when it is needed.</p><p><strong><em>Spring Boot caching</em></strong> is a feature provided by the Spring Framework that enables developers to cache frequently accessed data in memory or other caching technologies. <em>Caching</em> can help improve <em>application performance</em> by reducing the time it takes to retrieve data from a <em>database</em> or other <em>external source.</em></p><p><em>Spring Boot caching</em> is based on the <em>concept of annotations</em>. By adding annotations to the methods in your application that need to be cached, you can define the <em>caching behaviour</em>, such as the<em> cache name</em>, the <em>key</em> used to identify the data being <em>cached</em>, and the <em>caching strategy</em>.</p><p>The caching annotations in Spring Boot include:</p><ul><li>@Cacheable: Indicates that the <em>result</em> of <em>invoking</em> a <em>method</em> should be <em>cached</em>. If the same method is called again with the same arguments, the <em>cached value</em> is returned instead of invoking the method again.</li><li>@CachePut: Indicates that the result of invoking a method should be cached, but the method should always be <em>invoked</em>. Here the <em>Cache Value</em> for a <em>particular key</em> will be <em>updated</em> with the <em>new value</em> returned from the <em>invoked method</em>.</li><li>@CacheEvict: Indicates that the <em>cache entries</em> associated with the method should be <em>removed</em> from the <em>cache</em>.</li></ul><h4>Implementation</h4><p>Let’s have a look at a <em>simple cache implementation</em> in our <em>Springboot application.</em></p><p>The demo project will consist of <strong><em>2 REST APIs</em></strong>, one with a <strong>POST</strong> method to <em>register</em> an <em>employee</em> (which we store in the<strong><em> in-memory h2 database</em></strong>) and another with a <strong>GET</strong> method to fetch the <em>employee</em> with a specific <em>id</em>.</p><p>The idea is to record the <em>response times</em> of the <strong>GET API</strong> call before and after implementing the cache to <em>compare</em> their <em>performances</em>.</p><p>The following is the <em>directory structure</em> of the springboot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*HvA37FoCE1_PQwJr2vbkuQ.png" /><figcaption>directory structure</figcaption></figure><p>First, let’s add the required <em>dependency</em> needed for enabling Cache in our spring-boot application through the <em>pom.xml</em> file.</p><p><strong>POM Dependency</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;<br>    &lt;version&gt;2.4.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Let’s have a look at our <em>Employee class.</em></p><p><strong>Employee Model</strong></p><pre>import javax.persistence.Entity;<br><br>import javax.persistence.GeneratedValue;<br>import javax.persistence.Id;<br>import javax.persistence.Lob;<br><br>import org.hibernate.annotations.GenericGenerator;<br><br>@Entity<br>public class Employee {<br>   <br>   @Id<br>   private String id;<br><br>   private String name;<br><br>   private String company;<br>   <br>   private Integer salary;<br><br>  //constructors<br>  //getters<br>  //setters<br>}<br></pre><p>Next, we have the <em>EmployeeRepository</em> and <em>EmployeeService</em> classes which are basically our <strong><em>DAO</em></strong> (data access object) layer and <strong><em>service</em></strong> layers respectively.</p><p><strong>Employee Repository</strong></p><pre>@Repository<br>public interface EmployeeRepository extends CrudRepository&lt;Employee, String&gt;{<br> ArrayList&lt;Employee&gt; findAll();<br>}</pre><p><strong>Employee Service</strong></p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.cache.annotation.Cacheable;<br>import org.springframework.stereotype.Service;<br><br>import com.example.springboot.dao.EmployeeRepository;<br>import com.example.springboot.models.Employee;<br><br>@Service<br>public class EmployeeService {<br><br> @Autowired<br> EmployeeRepository employeeRepository;<br> <br> public Employee registerEmployee(Employee employee) {<br>  return employeeRepository.save(employee);<br> }<br> <br> @Cacheable(value=&quot;Employee&quot;, key=&quot;#id&quot;)<br> public Employee getEmployeeById(String id) {<br>  return employeeRepository.findById(id).get();<br> } <br> <br>}</pre><p>Here in our <em>service</em> class, we can see that we have used the @Cacheable <em>annotation</em> with id as key for the method getEmployeeById. This indicates that when the first time the getEmployeeById method is called, the code inside the method gets <em>executed</em> which <em>internally</em> does a <strong><em>DB</em></strong> call to the <em>h2 database</em> to retrieve the <em>details</em> of the <em>employee</em> whose id is passed as the function argument. After the execution is done, the <em>value</em> returned from that function gets stored in the <em>cache</em>. The id (employeeId passed in function argument ) is the <em>key</em> of the <em>cache</em> and the <em>value</em> returned by the getEmployeeById will be the corresponding <em>value</em>.</p><p>Subsequently, when the function is again called with the same employeeId as passed earlier, the <em>method</em> does <em>not</em> get <em>invoked</em> as that particular <em>key</em> is already <em>present</em> in the <em>cache</em> and the <em>value</em> corresponding to that key will be directly <em>returned</em> by the <em>cache</em> itself.</p><p>Next, let’s have a look at our <em>Controller class</em></p><p><strong>Employee Controller</strong></p><pre>@RestController<br>public class EmployeeController {<br> <br> @Autowired<br> EmployeeService employeeService;<br> <br> <br> @PostMapping(&quot;/employee&quot;)<br> public Employee saveBook(@RequestBody Employee employee) {<br>  return employeeService.registerEmployee(employee);<br> }<br> <br> @GetMapping(&quot;/employee/{id}&quot;)<br> public Employee getBook(@PathVariable(&quot;id&quot;) String id) {<br>  return employeeService.getEmployeeById(id);<br> }<br> <br>}</pre><p>Here we can see that we have exposed <strong><em>2 REST</em></strong> endpoints. One for registering an employee in the h2 database at endpoint /employee and another to retrieve a particular employee by their <em>id</em> at endpoint /employee/{id}. <em>Caching</em> is implemented on the <strong><em>GET</em></strong> call that <em>retrieves</em> the <em>employee details</em>.</p><p>Finally, for the <em>Cache implementation</em> to work, we need to add the @EnableCaching <em>annotation</em> at the <strong><em>Springboot Application </em></strong>level.</p><pre>@SpringBootApplication<br>@EnableCaching<br>public class SpringbootApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(SpringbootApplication.class, args);<br> }</pre><p>Now let’s run the above <em>spring boot application</em> with the command.</p><pre>mvn springboot: run</pre><p><strong>Testing</strong></p><p>Once the <em>spring-boot application</em> is <em>running</em>, let’s test our <em>cache implementation.</em></p><p>First, let’s perform a <strong><em>POST</em></strong> call to our <em>end-point</em> to <em>register</em> an <em>employee</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*4e_JFibr2-yOMRhABTeKfw.png" /></figure><p>Next, let’s fetch the <em>employee</em> using the <em>id</em> via curl call. Refer <a href="https://discuss.devopscube.com/t/how-to-find-response-time-using-curl-request/436">here</a> for recording the <em>curl call stats</em>.</p><pre>curl -v -w &quot;@curl-format.txt&quot;  --location --request GET &#39;http://localhost:8080/employee/001&#39; | jq &#39;.&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*eIIdhWFcwja7jiqfj8tzZw.png" /><figcaption>Initial GET call Response stats</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*6UCw2G2GKLJ_ZhBNL2yH5w.png" /><figcaption>Subsequent GET call response stats</figcaption></figure><p>When the <strong><em>GET API</em></strong> call is done for the first time, we can see that the <em>response time</em> was 0.046 seconds (refer to field time_total) as the method getEmployeeById was called since the Cache didn’t have the respective <em>key</em> (employeeId) that was called. But when the call was done the <em>second</em> time we can see that the <em>response time</em> was 0.007 seconds. This makes us understand that the first time when the API call was made, there was a <strong><em>DB</em></strong> call to the <em>H2 database</em> which took more <em>amount</em> of <em>time</em> compared to the subsequent <em>API</em> call whose <em>response time</em> was <em>negligible</em> as the respective <em>key</em> was <em>found</em> from the <em>cache</em> and the corresponding <em>value</em> was returned from the <em>cache</em>.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*vK_rmyfatYCkCAW-Qkl7wg.png" /></figure><p>In conclusion, <em>caching</em> is an <em>important technique</em> for <em>improving</em> the <em>performance</em> and <em>scalability</em> of <em>software applications</em>. By storing frequently accessed data in memory or other caching technologies, <em>caching</em> can reduce the time required to <em>access</em> <em>data</em> and improve the <em>overall</em> <em>speed</em> of an <em>application</em>. As an extension to this article, you can try the <em>implementation</em> of <em>annotations</em> @CachePut and@CacheEvict and understand their use cases.</p><p>Overall, <strong><em>Spring Boot caching</em></strong> is a valuable tool for any <em>developer</em> looking to <em>improve</em> the <em>performance</em> of their <em>Java-based web application</em>. By using <em>caching</em> effectively, developers can provide <em>faster</em>, more <em>responsive</em> <em>applications</em> that meet the needs of their users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4698b55f1469" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[cURL Response Parsing using jq]]></title>
            <link>https://medium.com/@samarthgvasist/curl-response-parsing-using-jq-b75eb2bf282a?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b75eb2bf282a</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[jq]]></category>
            <category><![CDATA[parse]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[curl]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 08:36:34 GMT</pubDate>
            <atom:updated>2023-01-29T08:36:34.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*MyE9KapAY1hJOMskXvL4MA.png" /></figure><p>This article will be a simple, short one with the intention to know how we can <em>parse </em>a <em>JSON response</em> rendered by a<em> cURL call.</em></p><h4>Overview</h4><p><strong>cURL</strong> stands for <strong>client URL </strong>and it is the most popular tool used by software engineers to send or receive data from a server. It is highly used for sending <em>API requests</em> by specifying the r<em>equest URL, HTTP method, request headers </em>and an optional <em>request body</em>.</p><p>cURL commands become <em>inevitable</em> to use when one needs to make <em>API calls</em> from <em>remote machines</em>, where API tools such as <em>Postman</em> will not be available. Since mainly it is used for the purpose of making REST API calls, the returned HTTP response is generally a JSON and as cURL is a command line tool, the returned response is not <em>structured</em>. As a result of this, generally, we try to copy the returned JSON from the command line and then use an online JSON tool to format it for understanding the response clearly.</p><p>Let’s have a look at an example cURL command. We will be using the free APIs provided by<em> </em><a href="https://reqres.in/"><em>reqres</em></a><em> </em>for the illustration.</p><pre>$ curl --location --request GET &#39;https://reqres.in/api/users?page=2&#39;</pre><p>This cURL call returns the below response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2kbAsQ_RwtOTVN78quPlw.png" /><figcaption>Response</figcaption></figure><p>We can see that the response returned is not <em>structured/formatted</em> making it difficult to <em>read</em> and <em>understand</em>.</p><h4>jq command</h4><p>jq<em> </em>helps to clearly <em>format </em>and <em>pretty print</em> the JSON returned by the cURL command. The main idea behind this command-line utility is that it can transform the components of a JSON file and present it in a <em>standard structured format.</em></p><p>Let’s make the above same API call but this time using jq.</p><pre>curl --location --request GET &#39;https://reqres.in/api/users?page=2&#39; | jq &#39;.&#39;</pre><p>The returned response looks as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCy96qCva2Nnl2oqt_xHpA.png" /></figure><p>Here we can see that the response is <em>well-structured</em> and <em>formatted</em>. It becomes very easy to read and understand the above HTTP response as it is pretty printed using jq.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*tWROymED9qQTu8G4AgLs4Q.jpeg" /></figure><p><strong><em>Productivity</em></strong> is the most important thing everyone should focus on during their work and it should always be maintained. Try to identify the potential places in your work where productivity is getting compromised and see if there are approaches that can be taken to improve them in a better way. We should try to avoid workarounds as much as possible unless there is no way out and using appropriate hacks and tools for this definitely makes life much easier!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b75eb2bf282a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Periodic Weather Alerting Using Apache Airflow]]></title>
            <link>https://medium.com/@samarthgvasist/periodic-weather-alerting-using-apache-airflow-d6fc5f9c3a41?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6fc5f9c3a41</guid>
            <category><![CDATA[workflow-orchestration]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 13:13:12 GMT</pubDate>
            <atom:updated>2023-01-02T04:35:38.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*tkA2AUDDeQN19inYnBVuEA.png" /></figure><blockquote>With enormous amount of real-time data getting generated from multiple sources at a very fast pace, there is a need to ingest this data on time and further process the stored data based on the use-case or requirement. As a result, there will be multiple workflows that need to be executed at the right intervals of time to automate this process of running end-to-end data pipelines for data ingestion or consumption as well as for orchestrating complex ML-based or cloud-based workflows which consist of several ETL operations. This is very much needed for getting insights generated from this real-time data to drive better decision-making and customer engagement.</blockquote><h4>Overview</h4><p><strong><em>Apache Airflow</em></strong> is an <em>open-source task automation tool</em> developed by <em>Airbnb</em> for <em>orchestrating workflows</em>. It is a <em>batch-oriented tool </em>used to develop and monitor <em>data pipelines</em> scheduled at a particular interval. It is mainly used for solving <em>data ingestion/consumption</em> problems and for <em>orchestrating</em> complex <em>ML flows</em> as a result of which it is extensively used by <em>Data Engineers</em> and <em>Data Scientists.</em></p><p><em>Airflow</em> is fairly simple to learn as it uses <em>Python</em> for <em>programming</em> and it has <em>integrations</em> with a variety of <em>cloud services</em> such as <em>AWS </em>and <em>Azure</em> in the form of <em>Operators</em> which makes it highly popular for building complex <em>data pipelines</em> or <em>workflows.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZkFdkyOL8w6ASKoU2JA1Q.png" /><figcaption>Airflow web</figcaption></figure><p>Let’s have a look at the <em>key terminologies</em> of Airflow before we start building our workflow</p><ul><li><strong><em>DAG</em></strong>: <em>DAG</em> stands for <em>Directed Acyclic Graph</em>. Airflow orchestrates workflows in the form of DAGs. <em>DAG </em>is a <em>collection of tasks</em> that needs to be performed in a <em>specific order</em> based on the <em>dependencies</em> between the <em>tasks</em>. The <em>order of execution</em> of the <em>tasks</em> is clearly defined in the DAG structure and it is represented in the form of a <em>graph</em>.</li><li><strong><em>Task</em></strong>: A <em>task</em> is the <em>simplest unit</em> of <em>work</em> in the <em>DAG</em>. It is represented as an <em>individual node</em> in the Directed Acyclic Graph.</li><li><strong><em>Operator</em></strong>: An <em>operator</em> is used to execute a <em>single independent task</em>. All the <em>tasks</em> are <em>implemented</em> in the form of <em>different operators</em>. For example, if we want to execute a python function as a task, Airflow provides an operator called <em>PythonOperator</em> using which we can execute the python method.</li></ul><pre>task_1 = PythonOperator(task_id = &#39;task_1&#39;, python_callable = my_fun)</pre><ul><li><strong><em>Variables</em></strong>: <em>Variables</em> are <em>simple key-value</em> store in <em>Airflow</em>. Using the name of the key, the value of the variable can be fetched from Airflow.</li></ul><pre>city = Variable.get(&quot;city&quot;)</pre><ul><li><strong><em>xcoms</em></strong>: <em>Xcoms</em> are mainly used for<em> data exchange or communication</em> between the<em> tasks/operators</em> that constitute the DAG. A particular message that is sent from one task instance using <strong>xcom_push()</strong> can be fetched by another task instance of the DAG using the <strong>xcom_pull()</strong> method.</li></ul><pre>ti.xcom_push(key = &#39;city&#39;, value = &#39;Bostom&#39;)  # task_1 pushing value to xcom<br>ti.xcom_pull(task_ids = &#39;task_1&#39;, key = &#39;city&#39;) # task_2 pulling value from xcom</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*92D0Zyoi5odaxQ60AsVQ6Q.png" /><figcaption>Sample DAG ( Tasks: extract, transform, load )</figcaption></figure><h4>Implementation</h4><p>In this article, we will see how to build a <em>simple periodic weather alerting system</em> using <em>Apache Airflow</em>. With the <em>open-source API</em> provided by <strong><em>OpenWeatherMap</em></strong>, the <em>weather data</em> for a <em>particular city</em> will be fetched and using<strong><em> Twilio</em></strong>, the respective <em>weather details</em> will be sent to the individual through an <em>SMS alert</em>. This workflow will be executed on a <em>daily basis</em> to give <em>day-to-day</em> weather updates with the help of an <em>airflow scheduler</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*950v8vV2_lYI8F9RLkkwUw.png" /></figure><p>The <em>setup</em> involves the <em>installation</em> of <em>airflow</em> on a <em>local machine</em>. The official <strong><em>Apache Airflow documentation</em></strong> provides the required steps/version for the <a href="https://airflow.apache.org/docs/apache-airflow/stable/installation/index.html"><em>download</em></a>. Here we will be using <em>airflow 2.5.0</em>. We also require accounts created on <em>OpenWeatherMap</em> and <em>Twilio </em>for utilizing their <em>services.</em></p><p>We will be using the following main <em>python package</em>s for our <em>implementation</em>:</p><ul><li><strong><em>apache-airflow</em></strong>: to <em>build</em> our <em>workflow</em></li><li><strong><em>twilio</em></strong>: to send <em>SMS alerts</em></li><li><strong><em>requests</em></strong>: to send <em>HTTP requests</em> for fetching the <em>weather data</em></li><li><strong><em>logging</em></strong>: for <em>application logging</em></li></ul><pre>import json<br>import requests<br>import logging<br>from datetime import datetime<br><br>from twilio.rest import Client<br><br>from airflow.models import DAG, Variable<br>from airflow.operators.python_operator import PythonOperator</pre><p>Next, we instantiate an object of the <em>logging class</em> for <em>effective application logging </em>and <em>debugging</em> throughout the <em>workflow</em>.</p><pre>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)</pre><p>Our DAG consists of 2 main tasks:</p><ul><li><strong><em>fetch_weather_data</em></strong>: this <em>task </em>is <em>implemented</em> as a <strong><em>PythonOperator</em></strong> and is used to <em>fetch</em> the <em>weather details</em> using the <em>OpenWeatherMap API</em> call.</li><li><strong><em>send_alert</em></strong><em>:</em> this <em>task</em> is also <em>implemented</em> as a <strong><em>PythonOperator</em></strong> and is used to send <em>SMS alerts</em> to the respective individual/end-user giving insights about the current weather.</li></ul><p>Let’s code our DAG :</p><pre>with DAG(dag_id=&quot;weather_alert&quot;,<br>         default_args={},<br>         schedule_interval=&quot;0 10 * * *&quot;,<br>         start_date=datetime(2022, 12, 28, 10),<br>         catchup=False<br>         ) as dag:</pre><p>Here we <em>instantiate</em> an object of the <em>DAG class</em> through a <em>parameterized constructor.</em> It takes the following main <em>parameters</em>:</p><ul><li><strong><em>dag_id</em></strong>: the<em> id </em>of the <em>dag</em>.</li><li><strong><em>default_args</em></strong>: A <em>dictionary</em> of <em>default parameters</em> used as <em>keyword parameters</em> during <em>DAG initialization</em>.</li><li><strong><em>scheduled_interval</em></strong>: A <em>cron expression</em> that indicates the <em>periodicity</em> of the <em>DAG scheduling.</em> Here the cron expression being<strong> 0 10 * * * </strong>shows that the DAG will execute daily at 10 am UTC which can be verified from <a href="https://crontab.guru/">crontab</a>.</li><li><strong><em>start_date</em></strong>: the<em> date </em>from which the <em>airflow starts</em> <em>periodic scheduling</em> of the <em>DAG</em></li></ul><pre>    fetch_weather_data = PythonOperator(<br>        task_id = &quot;fetch_weather_data&quot;,<br>        python_callable = fetch_weather_details,<br>        retries=3<br>    )<br>    <br>    send_alert = PythonOperator(<br>        task_id = &quot;send_alert&quot;,<br>        python_callable = send_alert,<br>        retries=3<br>    )</pre><p>Here we define the <em>2 tasks</em> that constitute our DAG. Both the tasks being implemented as <em>PythonOperators</em> take the following <em>main parameters:</em></p><ul><li><strong><em>task_id</em></strong>: the <em>id</em> of the <em>task</em></li><li><strong><em>python_callable</em></strong>: the <em>python module/function</em> that needs to be <em>executed </em>in that <em>PythonOperator</em></li><li><strong><em>retries</em></strong>: the <em>number of retries</em> that should be <em>performed </em>before <em>failing</em> the <em>task</em></li><li><strong><em>op_kwargs</em></strong>: an <em>optional dictionary of keyword arguments</em> passed to the respective <em>callable python function</em></li></ul><pre>fetch_weather_data &gt;&gt; send_alert</pre><p>Next, we define the <em>order of execution of tasks</em> in the workflow DAG. Here we set <em>send_alert</em> as the <em>downstream task </em>for the <em>fetch_weather_data</em> task which basically means the <em>send_alert task </em>will be executed<em> </em>after the <em>fetch_weather_data</em> task has been executed.</p><p>Now let’s look at the main python functions getting<em> </em>executed from the <em>PythonOperator</em></p><pre>def fetch_weather_details(ti):<br>    app_id = &quot;Your API key from openweathermap&quot;<br>    city = &quot;Your city name&quot;<br>    url = Variable.get(&#39;OPEN_WEATHER_MAP_PATH&#39;) + &quot;?q=&quot; + city + &quot;&amp;appid=&quot; + app_id<br><br>    try:<br>        logger.info(f&quot;Doing an API call to end-point {url}&quot;)<br>        response_text = requests.request(&quot;GET&quot;, url).text<br>        logger.info(f&quot;Fetched API response {response_text}&quot;)<br>        response_dict = json.loads(response_text)<br>        weather_details = response_dict[&#39;main&#39;]<br>        logger.info(f&quot;Pushing data to airflow xcom {weather_details}&quot;)<br>        ti.xcom_push(key = &#39;weather_data&#39;, value = weather_details)<br>        logger.info(f&quot;Data successfully pushed to airflow xcom {weather_details}&quot;)<br>    except Exception as ex:<br>        logger.info(f&quot;Error while fetching weather details with Exception {ex}&quot;)</pre><p>In this function, we fetch the <em>weather details</em> from the <em>open-source API</em>. We first fetch the <em>API end-point</em> from the <em>Airflow Variable</em>. This is done in order to <em>loosely couple</em> the <em>airflow code</em> from its <em>run-time configuration parameters</em>.</p><p>The API call takes 2 query parameters :</p><ul><li><strong><em>city</em></strong>: the <em>city</em> for which we need the <em>weather details</em></li><li><strong><em>app_id</em></strong>: the <em>unique app_key </em>provided by <em>OpenWeatherMap</em></li></ul><p>With the help of the <em>requests module</em> of python, the <em>HTTP request</em> is sent and the fetched <em>weather data</em> is pushed to the <em>airflow xcom</em> using the <strong>xcom_push()</strong> method.</p><pre>ti.xcom_push(key = &#39;weather_data&#39;, value = weather_details)</pre><p>In the next function, we send the<em> SMS alert </em>using the third-party <em>Twilio library</em>. First, we retrieve the <em>weather details </em>from the <em>xcom</em> which was sent from the previous task using the <strong>xcom_pull()</strong> method.</p><pre>weather_details = ti.xcom_pull(task_ids = &#39;fetch_weather_data&#39;, key = &#39;weather_data&#39;)</pre><p>Next, we use <em>twilio</em> library to send <em>SMS alerts</em>. The <em>Twilio Client</em> takes 4 main parameters for making an API call to send the SMS alert:</p><ul><li><strong><em>account_sid</em></strong>: the <em>account_sid </em>for the created <em>twilio account</em></li><li><strong><em>auth_token</em></strong>: token from<em> twilio</em></li><li><strong><em>from_</em></strong>:<em> twilio phone number</em> which will send the <em>SMS</em></li><li><strong><em>to</em></strong>: the <em>individual phone number</em> to which <em>SMS</em> needs to be sent</li></ul><p>Upon passing the respective parameters, a <em>successful API call </em>will be initiated by the <em>Twilio Client.</em></p><pre>def send_alert(ti):<br>    <br>    logger.info(f&quot;Pulling airflow xcom&quot;)<br>    weather_details = ti.xcom_pull(task_ids = &#39;fetch_weather_data&#39;, key = &#39;weather_data&#39;)<br>    logger.info(f&quot;Successfully pulled airflow xcom {weather_details}&quot;)<br>    custom_message = f&quot;Today&#39;s temperature is {int(weather_details[&#39;temp&#39;]-273)} \n Minimum temperature is {int(weather_details[&#39;temp_min&#39;]-273)} \n Maximum temperature is {int(weather_details[&#39;temp_max&#39;]-273)}&quot;    <br>    account_sid = &quot;Your account sid from twilio&quot;<br>    auth_token = &quot;Your auth token from twilio&quot;<br>   <br>    try:<br>        <br>        logger.info(f&quot;Doing twilio API call with custom message {custom_message}&quot;)<br>        client = Client(account_sid, auth_token)   <br>        message = client.messages.create(<br>        body=custom_message,<br>        from_=&quot;Twilio Phone Number&quot;,<br>        to=&quot;Your Phone Number&quot;<br>        )<br>        logger.info(f&quot;Successfully made API call&quot;)<br>        <br>    except Exception as ex:<br>        logger.info(f&quot;Failed to send weather alert&quot;)</pre><h4>Starting Airflow Services</h4><p>In order for our <em>DAG</em> to<em> run</em>, we need to start the <em>airflow infra services</em>. First, let’s start the <em>airflow webserver</em>.</p><pre>$ airflow webserver</pre><p>The <strong><em>Airflow Webserver</em></strong> is the <em>User Interface of Airflow</em> used for an overall <em>health check</em> of the various <em>DAGs</em>. It helps in <em>monitoring</em> and <em>visualizing</em> the <em>DAGs</em> as well as provides an <em>interface</em> for <em>manual intervention</em> for different purposes like <em>log debugging, airflow variable/connection</em> setting and <em>re-triggering DAGs.</em></p><p>Next, we have to start the <em>airflow scheduler service</em>. The <strong><em>Airflow Scheduler</em> </strong>keeps track of <em>different DAGs</em> and <em>triggers </em>the <em>task instances </em>whose <em>dependencies</em> have been met.</p><pre>$ airflow scheduler</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqRUvref_xcJLjH4qQjXpQ.png" /><figcaption>Airflow webserver and scheduler</figcaption></figure><p>Upon <em>successful execution</em> of the above commands, our <em>airflow webserver</em> will be hosted on<em> localhost </em>at <em>port 8080</em> and we can view the list of all the <em>existing DAGs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rQrzYvFwNpElid9AmQYsg.png" /></figure><p>Here we can see our <em>weather_alert</em> DAG as specified by the <em>dag_id </em>in our code. Next, we have to set our <em>Airflow Variable</em> <strong>OPEN_WEATHER_MAP_PATH</strong> under the <em>Variables</em> section of the <em>Admin</em> Tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkW_HmYxiiiGbLggExHNOQ.png" /></figure><p><em>Dags</em> can be executed by a <em>manual trigger</em> from the <em>airflow webserver user interface</em> or they can be <em>triggered automatically</em> at their <em>scheduled time. </em>Upon manually triggering the <em>weather_alert DAG</em>, we can see that the <em>DAG run </em>was <em>successful</em> as shown from the <em>airflow webserver User-Interface.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jktnNpu_-rBjcXKHXf_0HA.png" /><figcaption>Successful DAG runs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3x0Bv6WbH8Cx8azRZJTLA.jpeg" /><figcaption>SMS from phone</figcaption></figure><p>From the above image, we can see that the <em>SMS alert </em>has been <em>successfully</em> received by the<em> end user</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iyj1cMXkEp-Bt_RasFNRRA.png" /><figcaption>Graph view of DAG ( Tasks: fetch_weather_data, send_alert )</figcaption></figure><p>Upon <em>successful run</em> of our <em>weather_alert DAG</em>, we can see that the 2 respective tasks constituting the DAG have been <em>successfully completed</em> as indicated in the <em>graph view</em> of the <em>DAG</em>. <em>Airflow</em> provides us with various other insights about the DAGs such as <em>Lists of Xcoms, Variables, Connections</em> and <em>task logs</em> which help in <em>effective monitoring</em> and <em>debugging</em> when there is a <em>DAG</em> <em>failure</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InX5M3aKT56xdsJD7QuNnw.png" /><figcaption>List of XComs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkd0nim0x53LT5d-eNf3bA.png" /><figcaption>List of Airflow Variables</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vhAoEpfMKSPtxFm1VdgUg.png" /><figcaption>Task Logs: fetch_weather_data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csrL2c0vkK0_3CbngJpplg.png" /><figcaption>Task Logs: send_alert</figcaption></figure><h4>Conclusion</h4><p>Now we have a <em>basic understanding</em> of <em>Apache Airflow</em> and how we can <em>orchestrate workflows </em>using <em>airflow</em>. Several companies including <em>MNCs, tech giants</em> and <em>early-stage startups</em> are using <em>Airflow </em>to <em>schedule</em> and <em>monitor</em> <em>workflows</em> as a result of which the <em>Airflow community</em> is very <em>strong</em> and <em>popular</em>. In reality, <em>airflow</em> will generally be managed by <em>Kubernetes</em> on <em>high-powered cloud resources </em>such as <em>AWS EC2 instances</em>. The objective of <em>this article </em>is to get started with a <em>bare minimalistic set-up</em> to understand the concept of <em>workflow orchestration</em>. Most importantly, the <em>idea</em> is for aspiring <em>data engineering</em> enthusiasts to get started with <em>designing workflows</em> using <em>apache-airflow.</em></p><h4>References</h4><ul><li><a href="https://airflow.apache.org/docs/apache-airflow/stable/index.html">Apache-Airflow</a></li><li><a href="https://openweathermap.org/weather-conditions">OpenWeatherMap</a></li><li><a href="https://www.twilio.com/">Twilio</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6fc5f9c3a41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Data Pipeline with Apache Kafka]]></title>
            <link>https://medium.com/@samarthgvasist/building-a-simple-data-pipeline-with-apache-kafka-2459aea2d2bd?source=rss-2998cf14ab0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2459aea2d2bd</guid>
            <category><![CDATA[messaging-queue]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Samarth G Vasist]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 11:23:06 GMT</pubDate>
            <atom:updated>2022-12-14T11:23:06.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*agA0JFToyg6EafQrtnzoEA.png" /></figure><p>With an enormous volume of <em>data</em> getting generated from various sources every second, it becomes very important to process this <em>big data</em> in <em>real-time</em> to drive better <em>decision-making</em> in <em>business</em> as well as to <em>enhance</em> the <em>customer experience</em>. As a result, <em>designing data-pipelines</em> are vital for moving data from different <em>sources</em> to <em>destinations</em> between various services in a <em>micro-service</em> architecture.</p><h4>Overview</h4><p><strong><em>Apache Kafka</em></strong> is an <em>open-source Distributed Publish-Subscribe Messaging System</em>. It is mainly used for building <em>real-time data pipelines</em> which require data to be transferred from one point to another point. It is highly <em>reliable, scalable</em> and offers <em>excellent throughput</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*94gS6wsLb9TnECSevlkAng.png" /><figcaption>Source: <a href="https://www.tutorialspoint.com/apache_kafka/apache_kafka_cluster_architecture.htm">Tutorialspoint</a></figcaption></figure><p>In this article, we will get started with the <em>basics</em> of <strong><em>Apache Kafka</em></strong> and see how we can build a very <em>simple data-pipeline </em>using a <em>single-node Kafka cluster.</em> The idea is to extract <em>data</em> from a<em> dataset </em>stored on disk and send it to <em>Kafka</em> by a <strong><em>Python KafkaProducer</em></strong>. With the help of a <strong><em>Python KafkaConsumer</em></strong>, we will retrieve the data sent by the producer and ingest it into a <em>Mongo Collection</em>.</p><p>This involves setting up a <em>single-node Kafka cluster</em> on a <em>local machine</em>. It can be downloaded from the <a href="https://kafka.apache.org/downloads"><em>Downloads</em></a> section of the official <em>apache-kafka</em> page. We will be using the <em>kafka-python</em> package of the <em>python</em> distribution to <em>produce</em> and <em>consume</em> data from <em>Kafka</em>. <em>MongoDB </em>server running on port 27017 is used to <em>ingest</em> the incoming <em>data</em> fetched from the <em>Kafka Consumer</em>. We will be using the <em>Indian-cities</em> dataset that is publicly available on <a href="https://www.kaggle.com/datasets/parulpandey/indian-cities-database"><em>Kaggle</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*-q8KPIgahDmOs-LogkFPQA.png" /><figcaption>Dataset Preview Source: <a href="https://www.kaggle.com/datasets/parulpandey/indian-cities-database">Kaggle</a></figcaption></figure><p>Let’s have a look at the <em>high-level diagram</em> of our <em>data pipeline.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*mq32CVdcEinmee4y17VIdg.png" /><figcaption>High-Level Diagram</figcaption></figure><p>Here the <em>source</em> of our data is the<em> dataset</em> stored on disk, <em>MongoDB</em> is the <em>destination</em> or <em>sink</em> and <em>Apache Kafka</em> is used as the intermediate <em>Messaging Queue.</em></p><h4>Starting the ZooKeeper and Kafka Broker</h4><p>The <em>zookeeper</em> is used to maintain the <em>meta-data</em> information of the <em>Kafka cluster</em> and helps in the <em>smooth coordination</em> of the <em>cluster</em>. Let’s navigate to the root directory of <em>kafka</em> and start the <em>zookeeper </em>with the command.</p><pre>$ bin/zookeeper-server-start.sh config/zookeeper.properties</pre><p><em>Kafka brokers</em> refer to the <em>servers</em> present in the <em>distributed Kafka cluster.</em> Here in our case, since we are using a <em>single-node cluster</em>, there is only <em>one server</em> or <em>broker</em>. Here we start the <em>kafka-server </em>with the command:</p><pre>$ bin/kafka-server-start.sh config/server.properties</pre><p>By <em>default</em>,<em> zookeeper</em> runs on port <em>2181</em> and the <em>Kafka broker </em>runs on port <em>9091</em>.</p><h4>Creating a Kafka Topic</h4><p>A <em>topic</em> refers to <em>messages</em> belonging to a <em>particular category</em> or <em>type</em>. <em>Producers</em> <em>publish</em> <em>messages</em> by specifying their respective <em>topics</em> and <em>consumers</em> read <em>topic-specific</em> messages by <em>subscribing</em> to a particular <em>topic</em>. A single<em> topic</em> can contain <em>multiple</em> <em>partitions</em> across the <em>Kafka brokers</em>.</p><pre>$ bin/kafka-topics.sh --create --topic indian-cities --bootstrap-server <br>localhost:9092 --replication-factor 1 --partitions 1</pre><p>In this step, we create a<em> topic</em> for <em>sending</em> and <em>receiving messages</em>. Here, the topic name is <em>indian-cities</em> having a <em>single partition</em> in the Kafka cluster with a <em>replication factor</em> of <em>1</em>. The <em>bootstrap-server</em> flag refers to the <em>host-address</em> of the <em>Kafka server/broker</em> to connect to, for creating the topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-LCp91338pywC0U7nuaDA.png" /><figcaption>Created topic indian-cities</figcaption></figure><h4>Starting the Producer and Consumer</h4><p>In the context of a <em>publish-subscribe messaging system</em>, a <strong><em>producer</em></strong> is the one that <em>publishes</em> or <em>sends messages</em> belonging to <em>different topics</em> to the <em>Messaging Queue</em>. A <strong><em>consumer</em></strong> is a <em>program</em> or <em>service</em> that <em>consumes </em>or <em>reads</em> <em>topic-specific messages</em> from the <em>Messaging Queue</em>.</p><p>In our case, the producer is a python program that uses the <strong><em>KafkaProducer</em></strong> client from the <em>kafka-python</em> <em>package</em> to send <em>records</em> into the <em>Kafka cluster</em>.</p><pre>kafka_producer = KafkaProducer(bootstrap_servers = [&#39;localhost:9092&#39;],  \<br>                value_serializer = lambda x:json.dumps(x).encode(&#39;utf-8&#39;))</pre><p>The<strong><em> KafkaProducer client</em></strong> in our program takes 2 <em>keyword arguments</em>:</p><ul><li><strong><em>bootstrap_servers</em></strong>: it specifies the <em>Kafka server</em> to connect to for publishing records</li><li><strong><em>value_serializer</em></strong>: a <em>function</em> that <em>instructs</em> how to <em>convert</em> the format of the <em>message</em> sent from the <em>producer</em> to<em> bytes.</em></li></ul><pre>kafka_producer.send(&#39;indian-cities&#39;, value = city)</pre><p>The<em> send </em>method of the <strong><em>KafkaProducer client</em></strong> is used to <em>publish </em>a <em>message</em> to a specified <em>topic.</em> It takes <em>2 main arguments</em> in our <em>implementation</em>:</p><ul><li><strong><em>topic</em></strong>: the <em>name</em> of the<em> topic</em> where the message will be published</li><li><strong><em>value</em></strong>: the <em>value</em> of the published message</li></ul><p>Here is the complete python code for our <strong><em>producer</em></strong> program: <em>producer.py</em></p><pre>import json<br>import pandas as pd<br>from time import sleep<br>from kafka import KafkaProducer<br><br>#initialise the kafka producer object<br>kafka_producer = KafkaProducer(bootstrap_servers = [&#39;localhost:9092&#39;],  \<br>                value_serializer = lambda x:json.dumps(x).encode(&#39;utf-8&#39;))<br><br>#read the data from csv file and convert to list of dictionaries<br>city_dataframe = pd.read_csv(&#39;Indian Cities Database.csv&#39;)<br>cities = city_dataframe.to_json(orient = &#39;records&#39;)<br>city_records=json.loads(cities)<br><br>#iterating over list of dictionaries and sending each record to Kafka Cluster <br>for city in city_records:<br>    print(city)<br>    kafka_producer.send(&#39;indian-cities&#39;, value = city)<br>    sleep(1)</pre><p>Upon running the <em>producer.py</em> program, we can see the following <em>terminal logs</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVXwQvIdf-rINvcPKvvL0g.png" /><figcaption>Producer Logs</figcaption></figure><p>The <em>consumer</em> is also a <em>python program</em> that uses the <strong><em>KafkaConsumer</em></strong> client of the <em>kafka-python </em>package to consume records from the <em>Kafka cluster</em>.</p><pre>kafka_consumer = KafkaConsumer(&#39;indian-cities&#39;, bootstrap_servers = [&#39;localhost : 9092&#39;],auto_offset_reset = &#39;earliest&#39;, <br>                 value_deserializer = lambda x : loads(x.decode(&#39;utf-8&#39;)))</pre><p>The <strong><em>KafkaConsumer</em></strong> <em>client</em> in our program takes the following arguments:</p><ul><li><strong><em>topics</em></strong>: the <em>name</em> of the <em>topic</em> from which the messages are consumed</li><li><strong><em>bootstrap_servers</em></strong>: it specifies the <em>Kafka server</em> to connect to for retrieving messages</li><li><strong><em>auto_offset_reset</em></strong>: <em>policy </em>for consuming messages by <em>offset</em> reset</li><li><strong><em>value_serializer</em></strong>: a <em>function</em> that instructs how to convert the message <em>bytes</em> received to the <em>required format</em>.</li></ul><p>The <em>kafka consumer</em> object is a <em>python iterable</em> that consists of the <em>data</em> read from the <em>Kafka cluster</em>.</p><p>Here is the complete python code for our <strong><em>consumer</em></strong> program: <em>consumer.py</em></p><pre>from json import loads<br>from pymongo import MongoClient<br>from kafka import KafkaConsumer<br><br># generating the Kafka Consumer  <br>kafka_consumer = KafkaConsumer(&#39;indian-cities&#39;, bootstrap_servers = [&#39;localhost : 9092&#39;],auto_offset_reset = &#39;earliest&#39;, enable_auto_commit = True, <br>                 value_deserializer = lambda x : loads(x.decode(&#39;utf-8&#39;)))  <br> <br>#initializing the mongo client <br>mongoclient = MongoClient(&quot;mongodb://localhost:27017/&quot;)<br>#pointing the mongo client to the collection<br>collection = mongoclient[&quot;TESTData&quot;][&quot;City&quot;]<br>print(kafka_consumer)<br>for message in kafka_consumer:<br>    #inserting the messages to the mongo collection<br>    collection.insert_one(message.value)<br>    print(message.value)</pre><p>A <strong><em>MongoClient</em></strong> object from the<em> pymongo</em> python package is initialised by specifying the <em>host-address</em> of the locally installed <em>MongoDB server</em> and as and when the <em>messages</em> are <em>read</em> from the <em>consumer program</em>, they are <em>ingested</em> into the corresponding <em>mongo collection</em> as individual <em>documents.</em></p><p>Upon running the <em>consumer.py</em> program, we see the following <em>terminal logs</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6JHCueT3j5Qvez8MWAFQw.png" /><figcaption>Consumer Logs</figcaption></figure><p>After checking the corresponding <em>Mongo Collection</em>, we find the newly inserted documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*AODLn7hNEAw8rwQkOGufbw.png" /><figcaption>Mongodb Compass</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*FII0Q01N6DEeyZEfCzonug.png" /><figcaption>mongosh</figcaption></figure><h4>Conclusion</h4><p>Now we have a basic understanding of <strong><em>Apache Kafka </em></strong>and how a <em>simple data pipeline</em> looks like. In actual use cases, <em>data pipelines</em> are very <em>complex</em> consisting of several<em> data-sources</em>, <em>ETL (Extract Transform Load) operations</em> and <em>data-warehouses</em>. The <em>objective</em> of this article was to introduce the concept of <em>Apache Kafka</em>. It is highly<em> unrealistic </em>for <em>data-pipelines</em> to be run on<em> single-node clusters</em> as they are generally run in a <em>distributed</em> fashion on <em>multi-node </em>high-powered <em>cloud resources</em>, but the reason for having this setup is that <em>cloud resources</em> in general are not <em>open-sourced</em>. Most importantly, the idea is for aspiring <em>data engineering</em> enthusiasts to get started with understanding the concept and design of <em>data-pipelines</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*mkA5FGpotuig9hm-kUDckA.png" /><figcaption><a href="https://www.freepik.com/free-vector/big-data-source-data-center-cloud-computing-cloud-storage-isometric-concept-server-room-rack_4102872.htm#query=big%20data&amp;position=29&amp;from_view=search&amp;track=sph">Image by fullvector </a>on Freepik</figcaption></figure><h4>References</h4><ul><li><a href="https://kafka-python.readthedocs.io/en/master/#"><strong>kafka-python</strong></a></li><li><a href="https://www.tutorialspoint.com/apache_kafka/index.htm"><strong>Apache-Kafka Tutorialspoint</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2459aea2d2bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>