<?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 Santhosh Krishnamoorthy on Medium]]></title>
        <description><![CDATA[Stories by Santhosh Krishnamoorthy on Medium]]></description>
        <link>https://medium.com/@santhoshkris?source=rss-3232a696f5da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PhIVyEZ1HnhfLAK_yzk4Kg.jpeg</url>
            <title>Stories by Santhosh Krishnamoorthy on Medium</title>
            <link>https://medium.com/@santhoshkris?source=rss-3232a696f5da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:41:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@santhoshkris/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[Personal Finance Management using Ledger CLI]]></title>
            <link>https://santhoshkris.medium.com/personal-finance-management-ledger-cli-c98dd37e786e?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98dd37e786e</guid>
            <category><![CDATA[ledger]]></category>
            <category><![CDATA[money-management]]></category>
            <category><![CDATA[lifehacks]]></category>
            <category><![CDATA[personal-finance-tips]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 05:36:15 GMT</pubDate>
            <atom:updated>2022-12-04T05:36:15.933Z</atom:updated>
            <content:encoded><![CDATA[<p>Personal Finance Management using Ledger CLI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px8bgF85KR0rFEaV01lzlg.png" /></figure><p>Where does my money go? — am sure this is a question that most of us ask, if not always, probably by the end of the first week of every month 😃 Maintaining a personal finance tracking mechanism is quite important to get an outlook on what’s happening with your money and feed data into some system you can build to help with savings.</p><p>I am a sucker for CLIs ( Command Line Tools ) and also prefer plain text mechanisms for storing and processing data. This helps me to have control over my data, keep it on any cloud drive of my choosing and also have the data portable if I decide to move to a different system.</p><p>I went with <a href="https://www.ledger-cli.org/">Ledger</a>, a very powerful command-line-oriented tool which follows the `double-entry` based accounting system.</p><p>Double-entry bookkeeping means that all transactions should have two accounts, one from which the money goes out and the other into which the money goes in. A debit account (one which receives money) and a credit account (from which money is deducted). At any point in time, the accounts should balance to zero.</p><p>To start using `ledger`, all you need is an empty text file.</p><p>Create a file in any folder of your choice. Let us call it `ledger.txt`. Will refer to this as the `ledger` file in the rest of this article.</p><p>The typical structure of an entry in the ledger file would look like this.</p><pre>2022–01–04 Airtel mobile payment<br> Expenses:Utilities:Mobile ₹470.82<br> Liabilities:CC:Manhattan</pre><p>- This records an entry for `4th of Jan 2022` with a brief description of the payment. <br>- Indicates that I spent 470.82 on this. The amount moved from the Liabilities:CC:Manhattan account to the Expenses:Utilities:Mobile account. As I mentioned before, the double-entry system needs two accounts to tally an entry.</p><p>The accounts above are the ones that I use in my `ledger` files. These can be multi-level as you notice, like Expenses:Utilities which would be an account under theExpensesand Expenses:Utilities:Mobile is an account under Expenses:Utilities and so on.</p><p>I usually follow the below methodology to name my accounts.</p><p>- Assets like `bank` accounts etc — Assets:Savings:{bankname}<br>- Credit Cards — Liabilities:CC:{cardname}<br>- Any Income (incoming money) — Income:{type}<br>- Any kind of expense — Expenses:{subcategories}</p><p>I have been consistently following this for the last 3 years and have found it to be very useful.</p><p>Let us take some example scenarios to understand how one adds entries to the ledger file.</p><p>To start with, one needs to set an initial balance on the different accounts we will be interacting with. You do that like below:</p><p>Open the `ledger` file and put this at the top of the file</p><pre>;Ledger — Year 2023<br>2023–01–01 * Opening balance<br> Assets:Savings:Kotak ₹10000.00<br> Liabilities:CC:Manhattan ₹-10726.76<br> Equity:Opening Balances</pre><p>The above indicates:<br>- Starting on Jan 2023 with the mentioned balances in the Savings account<br>- Also, starting with a due amount on my credit card</p><p>That&#39;s all it takes. Post this, it is all about being prudent about adding entries to keep track of things.</p><p>Say, the month beginning, I received an income from my salary, I make an entry like below:</p><pre>2023–01–05 * Paycheck<br> Income:Paycheck ₹-24000.00<br> Assets:Savings:Kotak</pre><p>Notice here that I have mentioned a ‘-ve’ sign to indicate that the money is going from the Income:Paycheckaccount to my Savings account.</p><p>Then, say, I ended up paying the electricity bill. I add it like so:</p><pre>2023–01–05 BESCOM Bill Payment<br> Expenses:Utilities:BESCOM ₹1990.00<br> Liabilities:CC:Manhattan</pre><ul><li>first line — date of expense followed by a brief description of what the entry is for.</li><li>second line — the hierarchical account to which this amount is being credited to</li><li>the third line — from which account of yours is the money going out</li></ul><p>Then, let us say that I get a message saying that my Audible subscription was due for renewal and was charged to my card. I make an entry in my ledger file:</p><pre>2023–01–12 Audible<br> Expenses:Subscriptions:Audible ₹199.00<br> Liabilities:CC:Manhattan</pre><p>As before:<br>- first line — date and description<br>- second line — Category of expense (expense account) and amount<br>- third line — Source of the money or the account from which the expense was made</p><p>As one last example, say I went and bought some groceries and paid using GooglePay or something using my Savings account, I make an entry like the below:</p><pre>2023–01–15 * Groceries<br> Expenses:Shopping:Groceries ₹820.00<br> Assets:Savings:Kotak</pre><p>Similarly, over the days and months, you will add entries to the ledger file.</p><p>Here’s a sample ledger file. (this will be saved as `ledger.txt` as mentioned before)</p><pre>;Ledger - Year 2023<br>2023-01-01 * Opening balance<br>    Assets:Savings:Kotak                  ₹10730.88<br>    Liabilities:CC:Manhattan              ₹-10726.76<br>    Equity:Opening Balances<br><br>2023-01-04  Airtel mobile payment<br>    Expenses:Utilities:Mobile                ₹470.82<br>    Liabilities:CC:Manhattan<br><br>2023-01-05 * Paycheck<br>    Income:Paycheck                      ₹-24000.00<br>    Assets:Savings:Kotak<br><br>2023-01-05 BESCOM<br>    Expenses:Utilities:BESCOM               ₹1990.00<br>    Liabilities:CC:Manhattan<br><br>2023-01-05 * Card payment<br>    Liabilities:CC:Manhattan               ₹10000.00<br>    Assets:Savings:Kotak<br><br>2023-01-08 * BSNL<br>    Expenses:Utilities:BSNL                  ₹395.00<br>    Assets:Savings:Kotak<br><br>2023-01-14 Netflix<br>    Expenses:Subscriptions:Netflix           ₹199.00<br>    Liabilities:CC:Manhattan<br><br>2023-01-21  Adobe Photography Pack<br>    Expenses:Subscriptions:Adobe             ₹807.09<br>    Liabilities:CC:Manhattan<br><br>2023-02-02 BESCOM<br>    Expenses:Utilities:BESCOM               ₹2033.94<br>    Liabilities:CC:Manhattan<br><br>2023-02-03 * Food - Chaat<br>    Expenses:EatOut                          ₹120.00<br>    Assets:Savings:Kotak<br><br>2023-02-03 * Indane Gas<br>    Expenses:Utilities:Gas                   ₹902.50<br>    Assets:Savings:Kotak<br><br>2023-02-04 Jetpens - Stationery<br>    Expenses:Shopping:Stationery            ₹7813.63<br>    Liabilities:CC:Manhattan<br><br>2023-02-05 * Paycheck<br>    Income:Paycheck                      ₹-24000.00<br>    Assets:Savings:Kotak<br><br>2023-02-06 * Groceries<br>    Expenses:Shopping:Groceries             ₹1793.00<br>    Assets:Savings:Kotak<br><br>2023-02-12 * BWSSB Water bill<br>    Expenses:Utilities:BWSSB                 ₹996.00<br>    Assets:Savings:Kotak<br><br>2023-02-12 * BSNL Landline<br>    Expenses:Utilities:BSNL                  ₹388.00<br>    Assets:Savings:Kotak<br><br>2023-02-12 * Card payment<br>    Liabilities:CC:Manhattan               ₹30000.00<br>    Assets:Savings:Kotak<br><br>2023-02-12 Amazon - Monitor Arm<br>    Expenses:Shopping:Gadgets               ₹1989.00<br>    Liabilities:CC:Manhattan<br><br>2023-02-12 Amazon BenQ Monitor<br>    Expenses:Shopping:Gadgets              ₹15000.00<br>    Liabilities:CC:Manhattan<br><br>2023-02-14 Netflix<br>    Expenses:Subscriptions:Netflix           ₹199.00<br>    Liabilities:CC:Manhattan<br><br>2023-02-15 * Groceries<br>    Expenses:Shopping:Groceries             ₹1180.00<br>    Assets:Savings:Kotak<br><br>2023-02-19 ACT Cable<br>    Expenses:Utilities:Cable                 ₹334.39<br>    Liabilities:CC:Manhattan</pre><p>Now that we know how to update and manage the ledger file, just data stored in a file is not much use. The use comes from being able to analyse and draw reports out of it right.</p><p>This is where ledger shines.</p><p>Let us get ledger installed on our system.</p><p>If you are on macOS, use brew to install:</p><p>`brew install ledger`</p><p>For other OSes, you will find pre-built binaries on the ledger website here - <a href="https://www.ledger-cli.org/download.html">Download Ledger</a></p><p>The `ledger` cli provides a lot of options to query your ledger file and gather data as reports for you to analyse. Some simple examples are below.</p><p>Switch to a terminal and try these out:</p><p>To know the current balance of your accounts (assets and liabilities), run:</p><pre>ledger -w -f ledger.txt bal ^assets ^liabilities</pre><p>This should give an output like the below:</p><pre>           ₹12956.38  Assets:Savings:Kotak<br>           ₹-1563.63  Liabilities:CC:Manhattan<br>--------------------<br>           ₹11392.75<br>-------------------------------------------------------------------------------------------------------------------</pre><p>Finding out the balance is going to be the most commonly used command.</p><p>Let us do a query to find out the `Expenses` grouped by month.</p><pre>ledger r -M -f ledger.txt -- period-sort total expenses</pre><p>you should see an output like this:</p><pre>23-Jan-01 - 23-Jan-31                     Expenses:Subscriptions:Adobe                    ₹807.09            ₹807.09<br>                                          Expenses:Subscriptions:Netflix                  ₹199.00           ₹1006.09<br>                                          Expenses:Utilities:BESCOM                      ₹1990.00           ₹2996.09<br>                                          Expenses:Utilities:BSNL                         ₹395.00           ₹3391.09<br>                                          Expenses:Utilities:Mobile                       ₹470.82           ₹3861.91<br>23-Feb-01 - 23-Feb-28                     Expenses:EatOut                                 ₹120.00           ₹3981.91<br>                                          Expenses:Shopping:Gadgets                     ₹16989.00          ₹20970.91<br>                                          Expenses:Shopping:Groceries                    ₹2973.00          ₹23943.91<br>                                          Expenses:Shopping:Stationery                   ₹7813.63          ₹31757.54<br>                                          Expenses:Subscriptions:Netflix                  ₹199.00          ₹31956.54<br>                                          Expenses:Utilities:BESCOM                      ₹2033.94          ₹33990.48<br>                                          Expenses:Utilities:BSNL                         ₹388.00          ₹34378.48<br>                                          Expenses:Utilities:BWSSB                        ₹996.00          ₹35374.48<br>                                          Expenses:Utilities:Cable                        ₹334.39          ₹35708.87<br>                                          Expenses:Utilities:Gas                          ₹902.50          ₹36611.37             ₹2973.00          ₹23943.91</pre><p>Gives a nice view of all the expenses grouped by the month. You can restrict the report to a particular expense to see how much is spent on that type of expense. For example, if I need to know how much I spent on my Electricity bill (BESCOM, here), I run this:</p><pre>ledger r -M -f ledger.txt -- period-sort total expenses:utilities:bescom</pre><p>with an output like this:</p><pre>23-Jan-01 - 23-Jan-31   Expenses:Utilities:BESCOM   ₹1990.00        ₹1990.00<br>23-Feb-01 - 23-Feb-28   Expenses:Utilities:BESCOM   ₹2033.94        ₹4023.94</pre><p>or to know how much was spent on all the subscriptions, I run this command:</p><pre>ledger r -M -f ledger.txt -- period-sort total expenses:subscriptions</pre><p>to see an output like this:</p><pre>23-Jan-01 - 23-Jan-31  Expenses:Subscriptions:Adobe       ₹807.09      ₹807.09<br>                       Expenses:Subscriptions:Netflix     ₹199.00      ₹1006.09<br>23-Feb-01 - 23-Feb-28  Expenses:Subscriptions:Netflix     ₹199.00      ₹1205.09</pre><p>A great way to quickly get an idea of truly where the money is going 😃</p><p>`ledger` is very powerful and has lots of advanced usages too. You can read through the manual here - <a href="https://www.ledger-cli.org/docs.html">Ledger Docs</a> to get to know more.</p><p>I would highly recommend that you give `ledger` a try to better understand and manage your finances.</p><p>In the next article, I will cover my workflow for simplifying the process of adding entries to the ledger file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98dd37e786e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diagram As Code using Mermaid]]></title>
            <link>https://santhoshkris.medium.com/diagram-as-code-using-mermaid-f2dbfacaeac1?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2dbfacaeac1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mermaid]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[diagram-as-code]]></category>
            <category><![CDATA[documentation-tool]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 15:30:10 GMT</pubDate>
            <atom:updated>2022-11-29T15:30:10.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndJsI2JRmCv-WiGIdbAbRQ.png" /></figure><p>Documenting in general requires working with some kinds of diagrams, be it application architecture, user flow depictions or any reporting representations like Pie charts and Gantt charts.</p><p>The heretofore mechanism has been to include the diagrams as images after creating them on tools like draw.io and such. The biggest drawback with this mechanism is that the workflow for a change to any of the created diagrams is a very arduous one. This leads to a lack of interest in keeping the diagrams up to date further leading to gaps in the overall consistency of the documentation.</p><p>This is where Mermaid comes in. True to its beautiful name, `Mermaid` makes the process of creating beautiful diagrams and charts and their further modifications super easy. The word `modifying` becomes crucial here since that is the area we as developers struggle to keep up with.</p><p>Like `Infrastructure As Code or IAC`, I would say this is `Diagram As Code or DAC`. Mermaid lets you create diagrams declaratively in Markdown-like syntax. The details lie in plain text and can be easily modified at any point in time and also shared and incorporated into documentation quite easily.</p><p>To start creating them, we can work with any `editor` of choice say VS Code or Sublime Text or VIM with the appropriate `mermaid` plugin packages installed.</p><p>Mermaid comes with integrations for a whole lot of them. You can find more details on the page here — <a href="https://mermaid-js.github.io/mermaid/#/./integrations">Mermaid — Integrations</a></p><p>I will be working with VS Code. If you do so too, install this extension `Markdown Preview Mermaid Support` and you will be all set.</p><p>Let us look at a few simple examples:</p><p>Create a new file in VS Code and select the `language` as `Markdown`.</p><p>Let us create a diagram:</p><p>In the file that you have created, type in the code below ( as is, including the `tick` marks)</p><pre>```mermaid<br>graph TD;<br>A --&gt; B<br>```</pre><p>Now, open up the Preview tab and you should see a simple graph with 2 nodes, connecting from A to B, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*9aAws7tZ3-GTcnRxrfYySg.png" /></figure><p>There you have it! You have created your first diagram using just textual declarations!</p><p>graph — defines the type of diagram that you want to be created.</p><p>`TD` indicates a `Top Down` graph. This can be altered to whatever you see fit, like `LR for Left Right` as below</p><pre>```mermaid<br>graph LR;<br>A --&gt; B<br>```</pre><p>Should give something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*e8iaJq5QQn2kdodgjoTRXw.png" /></figure><p>Let us now provide some shape to our nodes.</p><pre>```mermaid<br>graph LR;<br>1[A] --&gt; 2{B}<br>```</pre><p>square brackets around a node give a `rectangle` shape and `curly` braces result in a `diamond` shape. When specifying nodes with shapes, you will also need to specify an `identifier` which is just a `name` for nodes like `1` and `2` in this case. This can be anything `alphanumeric`</p><p>Shapes of the nodes, the types of arrows ( solid, dotted etc ), labels for arrows and so much more can be created using `Mermaid` quite efficiently. For all the details, you can refer here — <a href="https://mermaid-js.github.io/mermaid/#/flowchart">Mermaid — Diagram Syntax</a></p><p>We can extend the graph further to indicate some kind of a flow, a flow chart per see.</p><p>Below, am trying to depict a simple User login flow :</p><pre>```mermaid<br>graph TD<br>a((User)) --&gt; b[[Login]]<br>b --&gt; c{Has &lt;br&gt;account?} --&gt; |Yes| d{Credentials Valid?} --&gt; |No| b<br>c --&gt;|No| e[[Sign Up]] --&gt; b<br>d --&gt;|Yes| f([Login successful])<br>```</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*2uLuWR-bxI7ftbB4GqCilw.png" /></figure><p>As you can see, the entire flowchart is depicted in a simple textual format. This is where comes the power.</p><p>Not just flow charts, Mermaid can be used for creating more advanced diagrams too.</p><p>Here’s an example of a simple Pie chart:</p><p>All you need to do is mention a `title` for the chart along with the `label` and `value` for the individual pieces of the pie.</p><pre>```mermaid<br>pie title Incident Distribution by Priority<br>“Priority 2”: 5<br>“Priority 3”: 10<br>“Priority 4”: 15<br>```</pre><p>And you should get something like this in the preview pane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*J__07skns8_N0acEtafV8Q.png" /></figure><p>Isn’t that wonderful and simple?</p><p>A `Sequence Diagram` is also something that we come across very frequently which is quite simple to create in `Mermaid` as well.</p><p>Here’s one example that depicts a sequence of interactions between two people in a Coffee Shop.</p><pre>```mermaid<br>sequenceDiagram<br>Shyam -&gt;&gt; +Maya: Hello Maya, how are you?<br>Shyam -&gt;&gt; +Maya: Maya, can you hear me?<br>Maya -&gt;&gt; +CoffeeDay: One Latte for me<br>Maya -&gt;&gt; -Shyam: Hi Shyam, I can hear you!<br>Maya -&gt;&gt; -Shyam: I feel great!<br>Shyam -&gt;&gt; CoffeeDay: One for me too!<br>```</pre><p>Gives you this nice diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*yM6cjdx8vJyZKTA-NZw0FQ.png" /></figure><p>All this from a simple markdown data. This is truly awesome!</p><p>Mermaid is very powerful and is a great way to incorporate diagrams into any documentation. The cycle time to make the changes and get them reflected is very short and therein lies the use case. Give it a go.</p><p>Happy exploring. Until next time, adios!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2dbfacaeac1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading Macros in Clojure]]></title>
            <link>https://santhoshkris.medium.com/threading-macros-in-clojure-eb08faf85f80?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb08faf85f80</guid>
            <category><![CDATA[threading-macros]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 12:45:04 GMT</pubDate>
            <atom:updated>2022-11-11T12:45:04.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Boo_C3wETWWUxQzHdCQXfg.png" /></figure><p>Threading macro in Clojure is a powerful construct which aids in improving the readability of code multi-fold. It kind of aligns with the way our brains think about and understand a process or a data flow. These macros, at a basic level, are syntactic sugar. They, however are very useful and enjoyable to use.</p><p>Threading macros convert nested function calls into a linear flow enabling one to visualise and easily understand as to how the data is flowing from one call to the other.</p><p>Two fundamental types of Threading macros in Clojure are as below :</p><p>a. Thread first — (-&gt; x &amp; forms)</p><p>b. Thread last — (-&gt;&gt; x &amp; forms)</p><p>The difference is basically in the way input data is positioned as it flows from one function call to the other.</p><p>Let us work through some examples to understand better.</p><p>In a Lisp based language like Clojure, the code is kind of evaluated from the inside out as you may be aware. The innermost form is evaluated first and the result is combined with the immediate outer form and the process continues till a final result is obtained. Let us look at contrived example below :</p><pre>(reduce + (map #(* % %) (filter odd? (range 10))))<br><br>;; 165</pre><p>What the above does, in plain english, is this :</p><ol><li>first, get the list of numbers from 0 to 9</li><li>pick out only the ones that are ‘odd’</li><li>square them all</li><li>finally, sum the resulting values</li></ol><p>However, the code represented isn’t very readable, right ? It isn’t tuned to the way we would understand and describe it. This is where threading macros come into play.</p><p>The above code written using a threading macro would look like this :</p><pre>(-&gt;&gt;<br>  (range 10)<br>  (filter odd?)<br>  (map #(* % % ))<br>  (reduce +))<br><br>;; 165</pre><p>Looking at the above code line by line, it is pretty clear as to what is going on. The result at each step is fed into the next as input. This is the simplicity and power of threading macros.</p><p>The example above is what is known as the Thread last macro. In Thread last , the result of every line is passed to the subsequent line as the last parameter. The ‘commas’ in the code below indicate the position at which the input data is inserted (the commas are ignored by the Clojure compiler).</p><pre>(-&gt;&gt;<br>  (range 10)<br>  (filter odd? ,,,)<br>  (map #(* % % ) ,,,)<br>  (reduce + ,,,))<br><br>;; 165</pre><p>In Thread first however, the input data is positioned between the function name and the first argument ( so, effectively as the first parameter in every subsequent step)</p><p>Let us look at an example</p><pre>(-&gt;<br>  &quot;HeLLo&quot;<br>  (clojure.string/lower-case)<br>  (clojure.string/index-of &quot;e&quot;))<br><br>;; 1</pre><p>Here, the third line (which tries to find the ‘index’ of the character ‘e’ in the string) needs the input string as the first parameter ( between the function name and the parameter ‘e’). This is ‘Thread first’</p><p>Once again, the ‘commas’ below indicate the position of the input data.</p><pre>(-&gt;<br>  &quot;HeLLo&quot;<br>  (clojure.string/lower-case <strong>,,,</strong>)<br>  (clojure.string/index-of <strong>,,,</strong> &quot;e&quot;))<br><br>;; 1</pre><p>Now, let us look at some examples where we intersperse thread first and thread last</p><p>Let us try and fetch a file named common-english-words.txt (which contains, as the name suggests, the most commonly found words in the english language) from the internet and work with it.</p><p>Below, we use thread first to :</p><ol><li>download the file and read the contents into memory as a string</li><li>split the string on , as the separator, resulting in a vector of all the words</li></ol><pre> (-&gt; (slurp &quot;https://www.textfixer.com/tutorials/common-english-words.txt&quot;)<br>     (clojure.string/split ,,, #&quot;,&quot;))<br><br>;; [&quot;a&quot; &quot;able&quot; &quot;about&quot; &quot;across&quot; &quot;after&quot; &quot;all&quot; &quot;almost&quot; &quot;also&quot; &quot;am&quot; &quot;among&quot; &quot;an&quot; &quot;and&quot; &quot;any&quot; &quot;are&quot; &quot;as&quot; &quot;at&quot; &quot;be&quot; &quot;because&quot; &quot;been&quot; &quot;but&quot; &quot;by&quot; &quot;can&quot; &quot;cannot&quot; &quot;could&quot; &quot;dear&quot; &quot;did&quot; &quot;do&quot; &quot;does&quot; &quot;either&quot; &quot;else&quot; &quot;ever&quot; &quot;every&quot; &quot;for&quot; &quot;from&quot; &quot;get&quot; &quot;got&quot; &quot;had&quot; &quot;has&quot; &quot;have&quot; &quot;he&quot; &quot;her&quot; &quot;hers&quot; &quot;him&quot; &quot;his&quot; &quot;how&quot; &quot;however&quot; &quot;i&quot; &quot;if&quot; &quot;in&quot; &quot;into&quot; &quot;is&quot; &quot;it&quot; &quot;its&quot; &quot;just&quot; &quot;least&quot; &quot;let&quot; &quot;like&quot; &quot;likely&quot; &quot;may&quot; &quot;me&quot; &quot;might&quot; &quot;most&quot; &quot;must&quot; &quot;my&quot; &quot;neither&quot; &quot;no&quot; &quot;nor&quot; &quot;not&quot; &quot;of&quot; &quot;off&quot; &quot;often&quot; &quot;on&quot; &quot;only&quot; &quot;or&quot; &quot;other&quot; &quot;our&quot; &quot;own&quot; &quot;rather&quot; &quot;said&quot; &quot;say&quot; &quot;says&quot; &quot;she&quot; &quot;should&quot; &quot;since&quot; &quot;so&quot; &quot;some&quot; &quot;than&quot; &quot;that&quot; &quot;the&quot; &quot;their&quot; &quot;them&quot; &quot;then&quot; &quot;there&quot; &quot;these&quot; &quot;they&quot; &quot;this&quot; &quot;tis&quot; &quot;to&quot; &quot;too&quot; &quot;twas&quot; &quot;us&quot; &quot;wants&quot; &quot;was&quot; &quot;we&quot; &quot;were&quot; &quot;what&quot; &quot;when&quot; &quot;where&quot; &quot;which&quot; &quot;while&quot; &quot;who&quot; &quot;whom&quot; &quot;why&quot; &quot;will&quot; &quot;with&quot; &quot;would&quot; &quot;yet&quot; &quot;you&quot; &quot;your&quot;]</pre><p>again the commas here ,,, indicate the position for the input at that step.</p><p>If, say, in the above scenario, you would want to convert all the words to uppercase for some strange reason, the code will be something like this</p><pre> (-&gt; (slurp &quot;https://www.textfixer.com/tutorials/common-english-words.txt&quot;)<br>     (clojure.string/split ,,, #&quot;,&quot;)<br>     (map #(clojure.string/upper-case %)))</pre><p>post splitting based on , we would need to map the method upper-case from the clojure.string library onto each of the element in the vector. However, there is a slight problem we run into.</p><pre>(-&gt; (slurp &quot;https://www.textfixer.com/tutorials/common-english-words.txt&quot;)<br>     (clojure.string/split ,,, #&quot;,&quot;)<br>     (map <strong>,,,</strong> #(clojure.string/upper-case %)))<br><br>;; <strong>Error</strong> printing return value (IllegalArgumentException) at <br>   clojure.lang.RT/seqFrom (RT.java:557).<br>   Don&#39;t know how to create ISeq from: user$eval2164$fn__2165</pre><p>this is because, at the last step in the process, the vector created is inserted in-between map and #(clojure.string/upper-case %) as we are working with thread first</p><p>This doesn’t work for us in this scenario. We need the parameter to be placed last, that would be thread last right.</p><p>So, we can jump into a thread last context just for that statement alone like this :</p><pre>(-&gt; (slurp &quot;https://www.textfixer.com/tutorials/common-english-words.txt&quot;)<br>    (clojure.string/split ,,, #&quot;,&quot;)<br>    <strong>(-&gt;&gt; (map #(clojure.string/upper-case %)))</strong>)<br><br>;; (&quot;A&quot; &quot;ABLE&quot; &quot;ABOUT&quot; &quot;ACROSS&quot; &quot;AFTER&quot; &quot;ALL&quot; &quot;ALMOST&quot; &quot;ALSO&quot; &quot;AM&quot; &quot;AMONG&quot; &quot;AN&quot; &quot;AND&quot; &quot;ANY&quot; &quot;ARE&quot; &quot;AS&quot; &quot;AT&quot; &quot;BE&quot; &quot;BECAUSE&quot; &quot;BEEN&quot; &quot;BUT&quot; &quot;BY&quot; &quot;CAN&quot; &quot;CANNOT&quot; &quot;COULD&quot; &quot;DEAR&quot; &quot;DID&quot; &quot;DO&quot; &quot;DOES&quot; &quot;EITHER&quot; &quot;ELSE&quot; &quot;EVER&quot; &quot;EVERY&quot; &quot;FOR&quot; &quot;FROM&quot; &quot;GET&quot; &quot;GOT&quot; &quot;HAD&quot; &quot;HAS&quot; &quot;HAVE&quot; &quot;HE&quot; &quot;HER&quot; &quot;HERS&quot; &quot;HIM&quot; &quot;HIS&quot; &quot;HOW&quot; &quot;HOWEVER&quot; &quot;I&quot; &quot;IF&quot; &quot;IN&quot; &quot;INTO&quot; &quot;IS&quot; &quot;IT&quot; &quot;ITS&quot; &quot;JUST&quot; &quot;LEAST&quot; &quot;LET&quot; &quot;LIKE&quot; &quot;LIKELY&quot; &quot;MAY&quot; &quot;ME&quot; &quot;MIGHT&quot; &quot;MOST&quot; &quot;MUST&quot; &quot;MY&quot; &quot;NEITHER&quot; &quot;NO&quot; &quot;NOR&quot; &quot;NOT&quot; &quot;OF&quot; &quot;OFF&quot; &quot;OFTEN&quot; &quot;ON&quot; &quot;ONLY&quot; &quot;OR&quot; &quot;OTHER&quot; &quot;OUR&quot; &quot;OWN&quot; &quot;RATHER&quot; &quot;SAID&quot; &quot;SAY&quot; &quot;SAYS&quot; &quot;SHE&quot; &quot;SHOULD&quot; &quot;SINCE&quot; &quot;SO&quot; &quot;SOME&quot; &quot;THAN&quot; &quot;THAT&quot; &quot;THE&quot; &quot;THEIR&quot; &quot;THEM&quot; &quot;THEN&quot; &quot;THERE&quot; &quot;THESE&quot; &quot;THEY&quot; &quot;THIS&quot; &quot;TIS&quot; &quot;TO&quot; &quot;TOO&quot; &quot;TWAS&quot; &quot;US&quot; &quot;WANTS&quot; &quot;WAS&quot; &quot;WE&quot; &quot;WERE&quot; &quot;WHAT&quot; &quot;WHEN&quot; &quot;WHERE&quot; &quot;WHICH&quot; &quot;WHILE&quot; &quot;WHO&quot; &quot;WHOM&quot; &quot;WHY&quot; &quot;WILL&quot; &quot;WITH&quot; &quot;WOULD&quot; &quot;YET&quot; &quot;YOU&quot; &quot;YOUR&quot;)</pre><p>So, jumping from thread first to thread last and back is quite straightforward and very useful.</p><p>The same thing, if needed in the reverse, like starting with thread last and jumping into thread first in the middle and back is also possible, but needs a small trick to achieve.</p><p>Let us look at one such example :</p><p>In the above scenario with the list of common words, the first thing we did was to read the file and split it into a vector of individual words. The split method actually needs the input string to be passed as the first parameter. This is a good case for us to explore.</p><p>We start with thread last then, to execute the split we switch to thread first by just creating an anonymous function which helps us to specify the position of the input parameter with a %. We then switch back to thread last for counting the number of words. This is more of a stealthy way of working by tricking the compiler. As you might notice, we are not explicitly using the thread first macro -&gt; here.</p><pre>(-&gt;&gt; (slurp &quot;https://www.textfixer.com/tutorials/common-english-words.txt&quot;)<br>     <strong>(#(clojure.string/split % #&quot;,&quot;))<br>      </strong>count <strong>,,,</strong>)<br><br>;; 119</pre><p>threading macros are not only very enjoyable to work with but also are very powerful and improve the overall readability of the code.</p><p>Hope that gave a decent primer to these constructs.</p><p>There are other more specialised threading macros in Clojure as well, namely some-&gt; some-&gt;&gt; and cond-&gt;. May be a topic for another article. Until then, adios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb08faf85f80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL with Clojure and HoneySQL]]></title>
            <link>https://santhoshkris.medium.com/postgres-with-clojure-and-honeysql-cb666a28d803?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb666a28d803</guid>
            <category><![CDATA[jdbc]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 11:57:11 GMT</pubDate>
            <atom:updated>2022-10-15T11:57:11.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="PostgreSQL with Clojure" src="https://cdn-images-1.medium.com/max/1024/1*k1xzsioUrUKF3YQx9BPeXA.png" /></figure><p>In this article, we will be looking at something very interesting that I came across while working with database queries in Clojure. I will be taking you step by step through the process of integrating and interacting with a PostgreSQL database in Clojure and run SQL queries on the same, first, the regular way and then move to a nicer way of getting the same job accomplished.</p><p>Ok, that was too much of convoluted talk. Let us see what I meant :-)</p><h4>Pre-requisites</h4><ol><li>Install PostgreSQL — You can follow the installation instructions for your specific OS, there are many tutorials online, just Google it!</li><li>Install Leiningen — instructions here — <a href="https://leiningen.org/#install">https://leiningen.org/#install</a></li><li>Some familiarity of working with Clojure code</li></ol><h4>Preparing PostgreSQL database</h4><p>As a first step, let us create a PostgreSQL database for us to work with.</p><p>Note: I will be working with a local instance of PostgreSQL</p><p>Open a terminal and type in :</p><pre>psql -U &lt;username&gt;</pre><p>Most PostgreSQL installations come with a default user postgres I will be working with that user through this article.</p><p>So typing in</p><pre>psql -U postgres</pre><p>will bring you to the prompt</p><pre>psql (13.3)<br>Type &quot;help&quot; for help.</pre><pre>postgres=#</pre><p>At the prompt, type in :</p><pre>create database ecomdb;</pre><p>check that the database is created</p><pre>\l</pre><pre>;;                       List of databases<br>            Name            |     Owner     | Encoding<br>----------------------------+---------------+----------<br> ecomdb                     | postgres      | UTF8    </pre><p>The database is created. Let us connect to the database ecomdb and create the tables needed</p><pre>\c ecomdb</pre><pre>;; You are now connected to database &quot;ecomdb&quot; as user &quot;postgres&quot;</pre><p>Type in :</p><pre>create table if not exists customer (<br>id SERIAL PRIMARY KEY NOT NULL,<br>name VARCHAR(100),<br>email VARCHAR(100),<br>mobile BIGINT);</pre><p>Let us check if the table has been created :</p><pre>\dt</pre><pre>;;           List of relations<br> Schema |   Name   | Type  |  Owner<br>--------+----------+-------+----------<br> public | customer | table | postgres<br>(1 row)</pre><h4>Clojure Project</h4><p>As always, let us begin by creating a project</p><pre>lein new app psql-demo</pre><p>configure the required Clojure libraries as dependencies. Open up the project.clj file in the created project folder and replace its contents with the one below</p><pre>(defproject postgres-demo &quot;0.1.0-SNAPSHOT&quot;<br>  :description &quot;FIXME: write description&quot;<br>  :url &quot;<a href="http://example.com/FIXME">http://example.com/FIXME</a>&quot;<br>  :license {:name &quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&quot;<br>            :url &quot;<a href="https://www.eclipse.org/legal/epl-2.0/">https://www.eclipse.org/legal/epl-2.0/</a>&quot;}<br>  :dependencies [[org.clojure/clojure &quot;1.10.3&quot;]<br>                 <strong>[com.github.seancorfield/next.jdbc &quot;1.3.834&quot;]<br>                 [org.postgresql/postgresql &quot;42.2.10&quot;]<br>                 [com.github.seancorfield/honeysql &quot;2.3.928&quot;]</strong>]<br>  :main ^:skip-aot postgres-demo.core<br>  :target-path &quot;target/%s&quot;<br>  :profiles {:uberjar {:aot :all<br>                       :jvm-opts [&quot;-Dclojure.compiler.direct-linking=true&quot;]}})</pre><p>Highlighted in <strong>bold </strong>above are the libraries that we will be working with</p><ol><li><strong>com.github.seancorfield/next.jdbc</strong> — As you might have guessed, this is the library that provides the jdbc interface to talk to variety of databases.</li><li><strong>org.postgresql/postgresql</strong> — This dependency provides the JDBC Driver that enables communication with PostgreSQL</li><li><strong>com.github.seancorfield/honeysql</strong> — This library provides a beautiful way to describe SQL queries as Clojure data structures and enables to build queries programmatically</li></ol><p>Now, let us download the dependencies, run :</p><pre>lein deps</pre><p>We are all set to fire up the REPL and explore.</p><h4>REPL</h4><p>Fire up the repl :</p><pre>lein repl</pre><p>Note: the above command is to be run under the project folder i.e postgres-demo</p><h4>Interacting with the PostgreSQL database</h4><p>Let us begin with the next.jdbc library and then bring in the honeysql</p><pre>(require &#39;[next.jdbc :as jdbc])</pre><p>First, we need to create a datasource For that we need to specify the database connection details in the form of a map like so:</p><pre>(def db-config<br>  {:dbtype &quot;postgresql&quot;<br>   :dbname &quot;ecomdb&quot;<br>   :host &quot;localhost&quot;<br>   :user &quot;postgres&quot;<br>   :password &quot;postgres&quot;})</pre><p>we specify :</p><p>the dbtype — will be postgresql in our case,</p><p>the host where the database server is running, localhost in our case</p><p>the dbname — the database name to connect to, ecomdb here and</p><p>the user/password details.</p><p>Using the above specification, we create a datasource , which I name as db</p><pre>(def <strong>db</strong> (<strong>jdbc/get-datasource</strong> db-config))</pre><p>With the datasource created, we can now start interacting with the PostgreSQL database</p><p>Let us do a simple SQL query to fetch all the rows in the table customer</p><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>;; []</pre><p>jdbc/execute! — method from the next.jdbc library</p><p>db — the datasource that we just created</p><p>followed by a vector with the SQL query in the form of a string.</p><p>As expected, returns an empty vector, nothing yet in our table.</p><p>Let us insert a row in the table</p><pre>(jdbc/execute! db [&quot;<br> insert into customer (name,email,mobile)<br>  values(&#39;<a href="/service/mailto:Sandy&#39;,&#39;sandy@sandy.org">john&#39;,&#39;john@doe.org</a>&#39;, 9898989898)&quot;])</pre><pre>;; [#:next.jdbc{:update-count 1}]</pre><p>The result indicates that a row was added in. Let us verify the same</p><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>;; [#:customer{:id 1, :name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;, :mobile 9898989898}]</pre><p>Great! the row has indeed been inserted.</p><p>Let us insert a few more rows</p><pre>(jdbc/execute! db [&quot;<br> insert into customer (name,email,mobile)<br>  values (&#39;<a href="/service/mailto:sandy&#39;,&#39;sandy@hello.com">sandy&#39;,&#39;sandy@hello.com</a>&#39;, 6666689898),<br>         (&#39;san&#39;, &#39;<a href="/service/mailto:san@san.com">san@san.com</a>&#39;, 8787878787)&quot;])</pre><pre>;; [#:next.jdbc{:update-count 2}]</pre><p>Verifying again</p><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>;; [#:customer{:id 1, :name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;, :mobile 9898989898} <br>   #:customer{:id 2, :name &quot;sandy&quot;, :email &quot;<a href="/service/mailto:sandy@hello.com">sandy@hello.com</a>&quot;, :mobile 6666689898} <br>   #:customer{:id 3, :name &quot;san&quot;, :email &quot;<a href="/service/mailto:san@san.com">san@san.com</a>&quot;, :mobile 8787878787}]</pre><p>All good so far. Now, comes the interesting part. All this while, we have been working with plain SQL queries, represented as strings right. We will now try to represent the queries in a more data-oriented manner.</p><h4>With HoneySQL</h4><p>HoneySQL brings in some amazing syntactic sugar to the process of structuring the SQL queries. It allows us to describe the queries in the form of a map data structure, a much more eloquent and neater way of doing it in my opinion.</p><p>Let us use honeysql to create the same queries we were working with earlier. First up, do a require of the library</p><pre>(refer-clojure :exclude &#39;[filter for group-by into partition-by set update])<br>(require &#39;[honey.sql :as sql]<br>         &#39;[honey.sql.helpers :refer :all :as h]<br>         &#39;[clojure.core :as c])</pre><p>Fetching all rows in the table customer, this is how you define the query</p><pre>(def sql-map {:<strong>select</strong> [:<strong>*</strong>]<br>               :<strong>from</strong> [:customer]})</pre><p>The pieces that make up the SQL statement are defined as key/value pairs of a map. In the simple example above, the sql-map has two entries</p><ol><li>key — <strong>select</strong> clause with the value of [:*] which is nothing but *</li><li>key — <strong>from</strong> that has a value of the table name <strong>customer</strong></li></ol><p>To convert this to the standard SQL query string that we were working with earlier, we need to user the format method from honeysql like so:</p><pre>(-&gt; sql-map<br>    (sql/format))</pre><pre>;; [&quot;SELECT * FROM customer&quot;]</pre><p>You see that it returns the string representation of the query.</p><p>Let us try one more example :</p><pre>(def sql-map <strong>{:select [:*]<br>              :from [:customer]<br>              :where [:= :id 1]})</strong></pre><pre>(-&gt; sql-map<br>    (sql/format))</pre><pre>;; [&quot;SELECT * FROM customer WHERE id = ?&quot; 1]</pre><p>As you see, the nicely represented query as a Clojure map is converted into the string representation with the appropriate parameterised values.</p><p>As I said, honeysql adds some nice syntactic sugar to the sql queries being built, hence the honey in its name, perhaps :-)</p><p>To execute the above query you follow the same mechanics like so :</p><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>;; [#:customer{<strong>:id 1</strong>, :name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;, :mobile 9898989898}]</pre><p>we get back the row with id=1</p><p>We can even list the specific columns that you want to be fetched like so:</p><pre>(def sql-map {:select [<strong>:name :email</strong>]<br>              :from [:customer]<br>              :where [:= :id 1]})</pre><pre>(jdbc/execute! db (sql/format sql-map)</pre><pre>;; [#:customer{:name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;}]</pre><p>Let us insert a few more rows using honeysql . Let us define a map</p><pre>(def sql-map {:<strong>insert-into</strong> [:customer]<br>              :<strong>columns</strong> [:name :email :mobile]<br>              :<strong>values</strong> [[&quot;hello&quot; &quot;<a href="/service/mailto:hello@hello.com">hello@hello.com</a>&quot; 8787878787]<br>                       [&quot;whatis&quot; &quot;<a href="/service/mailto:what@whatis.org">what@whatis.org</a>&quot; 1234567890]]})</pre><p><strong>:insert-into</strong> — specifies the table to insert the values into</p><p><strong>:columns</strong> — specifies the columns the values are being associated with</p><p><strong>:values</strong> — specifies the actual values to be inserted. Notice that this is a collection of rows ( vector of vectors )</p><p>Now, we can execute the query</p><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>;; [#:next.jdbc{:update-count 2}]</pre><p>We get a return message saying that 2 rows have been inserted. Let us verify the same.</p><pre>(def sql-map {:<strong>select</strong> [:<strong>*</strong>]<br>               :<strong>from</strong> [:customer]})</pre><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>;; [#:customer{:id 1, :name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;, :mobile 9898989898} <br>    #:customer{:id 2, :name &quot;sandy&quot;, :email &quot;<a href="/service/mailto:sandy@hello.com">sandy@hello.com</a>&quot;, :mobile 6666689898} <br>    #:customer{:id 3, :name &quot;san&quot;, :email &quot;<a href="/service/mailto:san@san.com">san@san.com</a>&quot;, :mobile 8787878787} <br>   <strong>#:customer{:id 4, :name &quot;hello&quot;, :email &quot;</strong><a href="/service/mailto:hello@hello.com"><strong>hello@hello.com</strong></a><strong>&quot;, :mobile 8787878787} <br>   #:customer{:id 5, :name &quot;whatis&quot;, :email &quot;</strong><a href="/service/mailto:what@whatis.org"><strong>what@whatis.org</strong></a><strong>&quot;, :mobile 1234567890}<br>   </strong>]</pre><p>We see that the rows have been inserted.</p><p>Let us now try another query :</p><pre>(def sql-map {:select [:*]<br>              :from [:customer]<br>              <strong>:where [:and [:&gt; :id 2][:&lt; :id 5]]</strong>})</pre><p>In this case, we are using an AND to combine multiple where clauses.</p><p>Let us execute this sql query</p><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>;; [#:customer{:id 3, :name &quot;san&quot;, :email &quot;<a href="/service/mailto:san@san.com">san@san.com</a>&quot;, :mobile 8787878787} #:customer{:id 4, :name &quot;hello&quot;, :email &quot;<a href="/service/mailto:hello@hello.com">hello@hello.com</a>&quot;, :mobile 8787878787}]</pre><p>As expected, it returns the rows with id between 2 &amp; 5 which would be rows with id=3 and id=4Great!</p><p>Let us try an update query. Let us update the email of the customer with id=2 with a new one. First, we have to define the query map</p><pre>(def sql-map {<strong>:update</strong> :customer<br>              <strong>:set</strong> {:email &quot;<a href="/service/mailto:sandy@sandy.com">sandy@sandy.com</a>&quot;}<br>              <strong>:where</strong> [:= :id 2]})</pre><p>Let us execute this :</p><pre>(jdbc/execute! db (sql/format sql-map ))</pre><pre>;; [#:next.jdbc{:update-count 1}]</pre><p>Return message says that a row has been updated. Let us quickly verify</p><pre>(def sql-map {:select [:name :email]<br>              :from [:customer]<br>              :where [:= :id 2]})</pre><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>;; [#:customer{:name &quot;sandy&quot;, :email &quot;<a href="/service/mailto:sandy@sandy.com">sandy@sandy.com</a>&quot;}]</pre><p>So, we see that the email has been updated to the new one, awesome!</p><p>As one last example, let us try a delete query</p><p>Let us delete the last row ( with id=5 )</p><pre>(def sql-map {<strong>:delete-from</strong> :customer<br>              <strong>:where</strong> [:= :id 5]})</pre><pre>(jdbc/execute! db (sql/format sql-map ))</pre><pre>;; [#:next.jdbc{:update-count 1}]</pre><p>Let us verify ( using the Clojure threaded macros here )</p><pre>(-&gt;&gt; {:select :*<br>              :from :customer}<br>     (sql/format)<br>     (jdbc/execute! db))</pre><pre>;; [#:customer{:id 1, :name &quot;john&quot;, :email &quot;<a href="/service/mailto:john@doe.org">john@doe.org</a>&quot;, :mobile 9898989898} #:customer{:id 3, :name &quot;san&quot;, :email &quot;<a href="/service/mailto:san@san.com">san@san.com</a>&quot;, :mobile 8787878787} #:customer{:id 4, :name &quot;hello&quot;, :email &quot;<a href="/service/mailto:hello@hello.com">hello@hello.com</a>&quot;, :mobile 8787878787} #:customer{:id 2, :name &quot;sandy&quot;, :email &quot;<a href="/service/mailto:sandy@sandy.com">sandy@sandy.com</a>&quot;, :mobile 6666689898}]</pre><p>We see that the customer with id=5 has been removed.</p><p>There are of-course may more advanced SQL queries that can be built with honeysql using purely data. That is the power of honeysql. It is an interesting take and definitely more easier to structure and modify the clauses in the queries since they are all maps</p><p>Let me give an example before closing.</p><p>Say, we start with a query like this, which picks up all the columns in the rows :</p><pre>(def sql-map {:select [:<strong>*</strong>]<br>               :from [:customer]})</pre><p>But, later realise that you need just the name and email and not the mobile, we can modify this sql-map during execution since it is just a map. This is done like so :</p><pre>(-&gt; sql-map<br>    (dissoc :select)<br>    (select :name :email)<br>    (sql/format))</pre><pre>;; [&quot;SELECT name, email FROM customer&quot;]</pre><p>We use the map&#39;s dissoc method to disassociate the currently assigned value to :select and reassign it with a new value on the next line. You see the result of the sql/format method. The updated query is seen reflected there. This is the power of using a data-oriented approach.</p><p>Let us run this :</p><pre>(-&gt; sql-map<br>    (<strong>dissoc :select</strong>)<br>    (:<strong>select :name :email</strong>)<br>    (sql/format)<br>    (-&gt;&gt; (jdbc/execute! db)))</pre><p>As you see, we are replacing the select clause with a different one and execute the new query to get the desired result, thats fabulous, isn&#39;t it!</p><p>Putting together all the code pieces that we worked on through this article here, just for your reference :</p><p>PSQL :</p><pre>;; Setup the PSQL database needed to work with</pre><pre>psql -U &lt;username&gt;</pre><pre>psql -U postgres</pre><pre>create database ecomdb;</pre><pre>\l</pre><pre>\c ecomdb</pre><pre>create table if not exists customer (<br>id SERIAL PRIMARY KEY NOT NULL,<br>name VARCHAR(100),<br>email VARCHAR(100),<br>mobile BIGINT);</pre><pre>\dt</pre><p>Clojure :</p><pre>;; Create a new Clojure project</pre><pre>lein new app psql-demo</pre><pre>;; Configure all the dependencies</pre><pre>(defproject postgres-demo &quot;0.1.0-SNAPSHOT&quot;<br>  :description &quot;FIXME: write description&quot;<br>  :url &quot;<a href="http://example.com/FIXME">http://example.com/FIXME</a>&quot;<br>  :license {:name &quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&quot;<br>            :url &quot;<a href="https://www.eclipse.org/legal/epl-2.0/">https://www.eclipse.org/legal/epl-2.0/</a>&quot;}<br>  :dependencies [[org.clojure/clojure &quot;1.10.3&quot;]<br>                 [com.github.seancorfield/next.jdbc &quot;1.3.834&quot;]<br>                 [org.postgresql/postgresql &quot;42.2.10&quot;]<br>                 [com.github.seancorfield/honeysql &quot;2.3.928&quot;]]<br>  :main ^:skip-aot postgres-demo.core<br>  :target-path &quot;target/%s&quot;<br>  :profiles {:uberjar {:aot :all<br>                       :jvm-opts [&quot;-Dclojure.compiler.direct-linking=true&quot;]}})</pre><pre>;; Download and setup the dependent Clojure libraries</pre><pre>lein deps</pre><pre>;; Get into the REPL to explore!</pre><pre>lein repl</pre><pre>;; Start ...</pre><pre>(require &#39;[next.jdbc :as jdbc])</pre><pre>(def db-config<br>  {:dbtype &quot;postgresql&quot;<br>   :dbname &quot;ecomdb&quot;<br>   :host &quot;localhost&quot;<br>   :user &quot;postgres&quot;<br>   :password &quot;postgres&quot;})</pre><pre>(def db (jdbc/get-datasource db-config))</pre><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>(jdbc/execute! db [&quot;<br> insert into customer (name,email,mobile)<br>  values(&#39;<a href="/service/mailto:john&#39;,&#39;john@doe.org">john&#39;,&#39;john@doe.org</a>&#39;, 9898989898)&quot;])</pre><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>(jdbc/execute! db [&quot;<br> insert into customer (name,email,mobile)<br>  values (&#39;<a href="/service/mailto:sandy&#39;,&#39;sandy@hello.com">sandy&#39;,&#39;sandy@hello.com</a>&#39;, 6666689898),<br>         (&#39;san&#39;, &#39;<a href="/service/mailto:san@san.com">san@san.com</a>&#39;, 8787878787)&quot;])</pre><pre>(jdbc/execute! db [&quot;select * from customer&quot;])</pre><pre>(refer-clojure :exclude &#39;[filter for group-by into partition-by set update])<br>(require &#39;[honey.sql :as sql]<br>         &#39;[honey.sql.helpers :refer :all :as h]<br>         &#39;[clojure.core :as c])</pre><pre>(def sql-map {:select [:*]<br>               :from [:customer]})</pre><pre>(-&gt; sql-map<br>    (sql/format))</pre><pre>(def sql-map {:select [:*]<br>              :from [:customer]<br>              :where [:= :id 1]})</pre><pre>(-&gt; sql-map<br>    (sql/format))</pre><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>(def sql-map {:select [:name :email]<br>              :from [:customer]<br>              :where [:= :id 1]})<br>(jdbc/execute! db (sql/format sql-map)</pre><pre>(def sql-map {:insert-into [:customer]<br>              :columns [:name :email :mobile]<br>              :values [[&quot;hello&quot; &quot;<a href="/service/mailto:hello@hello.com">hello@hello.com</a>&quot; 8787878787]<br>                       [&quot;whatis&quot; &quot;<a href="/service/mailto:what@whatis.org">what@whatis.org</a>&quot; 1234567890]]})</pre><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>(def sql-map {:select [:*]<br>               :from [:customer]})<br>(jdbc/execute! db (sql/format sql-map))</pre><pre>(def sql-map {:select [:*]<br>              :from [:customer]<br>              :where [:and [:&gt; :id 2][:&lt; :id 5]]})</pre><pre>(jdbc/execute! db (sql/format sql-map))</pre><pre>(def sql-map {:update :customer<br>              :set {:email &quot;<a href="/service/mailto:sandy@sandy.com">sandy@sandy.com</a>&quot;}<br>              :where [:= :id 2]})</pre><pre>(jdbc/execute! db (sql/format sql-map ))</pre><pre>(def sql-map {:select [:name :email]<br>              :from [:customer]<br>              :where [:= :id 2]})<br>(jdbc/execute! db (sql/format sql-map))</pre><pre>(def sql-map {:delete-from :customer<br>              :where [:= :id 5]})<br>(jdbc/execute! db (sql/format sql-map ))</pre><pre>(-&gt;&gt; {:select :*<br>              :from :customer}<br>     (sql/format)<br>     (jdbc/execute! db))</pre><pre>(def sql-map {:select [:*]<br>               :from [:customer]})</pre><pre>(-&gt; sql-map<br>    (dissoc :select)<br>    (select :name :email)<br>    (sql/format))</pre><pre>(-&gt; sql-map<br>    (dissoc :select)<br>    (:select :name :email)<br>    (sql/format)<br>    (-&gt;&gt; (jdbc/execute! db)))</pre><p>Ok, that does it for this article. Hope that gave you a good intro to the way you interact with PostgreSQL using Clojure and also on working with the powerful honeysql library to construct your SQL queries.</p><p>More later, see you until then.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb666a28d803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS S3 with Clojure]]></title>
            <link>https://awstip.com/aws-s3-clojure-a42573786eb1?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/a42573786eb1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 14:06:26 GMT</pubDate>
            <atom:updated>2022-10-17T11:20:25.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYVcrdBerIQ_4_e9OGYsTw.png" /></figure><p>In this article, I will take a slight detour from my previous one to take a step by step look at the aspect of interacting with AWS S3 using Clojure.</p><p>AWS S3 doesn’t need any introduction I presume. Just in case, here’s a quick brief on what S3 is all about from Amazon itself :</p><blockquote>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance. You can use Amazon S3 to store and retrieve any amount of data at any time, from anywhere.</blockquote><p>AWS S3 is probably the most commonly used, go-to storage service for AWS users with use cases ranging from the likes of mobile/web applications to big data, machine learning and more.</p><h4>Pre-requisites</h4><ol><li>Leiningen — Ensure that this is installed and is in PATH. Needed to work with projects in Clojure, making it easier to create &amp; configure them with the required dependencies. Also needed to fire up the Clojure REPL. If you do not have it, you can follow the quick installation process here — <a href="https://leiningen.org/#install">https://leiningen.org/#install</a></li><li>AWS account — Create a user in IAM with Programmatic Access and with the AmazonS3FullAccess Permission Policy applied. Make a note of Access Key ID and Secret Access Key for the user. If you need help in getting this done, you can refer to the steps detailed here — <a href="https://codingsight.com/upload-files-to-aws-s3-with-the-aws-cli/#:~:text=a%20quick%20setup.-,Create,-an%20IAM%20user">Create an AWS IAM user</a></li></ol><p>3. Finally, some familiarity in understanding Clojure code would help</p><p>Let us get going.</p><p>In Clojure, there are two powerful libraries that help us interact with AWS S3.</p><p>a. <a href="https://github.com/mcohen01/amazonica">Amazonica</a></p><p>b. <a href="https://github.com/cognitect-labs/aws-api">aws-api</a></p><p>Here, I will be working with the aws-api library through the code examples. Will discuss the amazonica library in another article.</p><h4>Clojure Project</h4><p>As always, let us begin by creating a Clojure project to work with.</p><p>Open up a Terminal and type as below :</p><pre>lein new app aws-s3-demo</pre><p>This will create a folder named aws-s3-demo in the directory where you ran the above command from. Move into the aws-s3-demo directory and see the listing of its content. Should result in a folder structure like below :</p><pre>.<br>├── CHANGELOG.md<br>├── LICENSE<br>├── README.md<br>├── doc<br>│   └── intro.md<br>├── <strong>project.clj</strong><br>├── resources<br>├── src<br>│   └── aws_s3_demo<br>│       └── core.clj<br>└── test<br>    └── aws_s3_demo<br>        └── core_test.clj</pre><p>Let us now configure the dependencies. Open the project.clj file located under aws-s3-demo (the root project directory) and update the dependencies section. The final project.clj file should look like below :</p><pre>(defproject aws-s3-demo &quot;0.1.0-SNAPSHOT&quot;<br>  :description &quot;FIXME: write description&quot;<br>  :url &quot;<a href="http://example.com/FIXME">http://example.com/FIXME</a>&quot;<br>  :license {:name &quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&quot;<br>            :url &quot;<a href="https://www.eclipse.org/legal/epl-2.0/">https://www.eclipse.org/legal/epl-2.0/</a>&quot;}<br>  :dependencies [[org.clojure/clojure &quot;1.10.3&quot;]<br>                 <strong>[com.cognitect.aws/api &quot;0.8.596&quot;]<br>                 [com.cognitect.aws/endpoints &quot;1.1.12.307&quot;]<br>                 [com.cognitect.aws/s3 &quot;822.2.1145.0&quot;]</strong>]<br>  :main ^:skip-aot aws-s3-demo.core<br>  :target-path &quot;target/%s&quot;<br>  :profiles {:uberjar {:aot :all<br>                       :jvm-opts [&quot;-Dclojure.compiler.direct-linking=true&quot;]}})</pre><p>The ones highlighted in <strong>bold </strong>above are the Clojure AWS libraries (<strong>aws-api</strong>). To ensure that the dependencies are downloaded, let us run :</p><pre>lein deps</pre><p>With the project and its dependencies setup, let us start exploring.</p><h4>Working with the aws-api library</h4><p>Ensure that you are at the root directory of the project ( aws-s3-demo ) and fire up a REPL using the command below :</p><pre>lein repl</pre><p>A prompt like this should show up :</p><pre>nREPL server started on port 60598 on host 127.0.0.1 - nrepl://127.0.0.1:60598<br>REPL-y 0.5.1, nREPL 0.8.3<br>Clojure 1.10.3<br>Java HotSpot(TM) 64-Bit Server VM 16.0.2+7-67<br>    Docs: (doc function-name-here)<br>          (find-doc &quot;part-of-name-here&quot;)<br>  Source: (source function-name-here)<br> Javadoc: (javadoc java-object-or-class-here)<br>    Exit: Control+D or (exit) or (quit)<br> Results: Stored in vars *1, *2, *3, an exception in *e</pre><pre>aws-s3-demo.core=&gt;</pre><p>At the prompt, let us do a require of the libraries to begin with :</p><pre>(require &#39;[cognitect.aws.client.api :as aws]<br>         &#39;[cognitect.aws.credentials :as credentials])</pre><p>The workflow that one needs to follow is quite simple :</p><p>Create a <strong>client</strong> for a specific AWS service → <strong>invoke</strong> an Operation on the service ( with optional request parameters )</p><p>Let us go ahead and create a client for the s3 service on AWS</p><pre>(def <strong>s3-client</strong> (aws/client <strong>{</strong>:<strong>api</strong>                  :<strong>s3</strong><br>                     :<strong>region</strong>               <strong>&quot;us-east-1&quot;</strong><br>                     :credentials-provider (credentials/basic-credentials-provider<br>                     {:<strong>access-key-id</strong>     <strong>&lt;your_access_key_id&gt;</strong><br>                      :<strong>secret-access-key</strong> <strong>&lt;your_secret_access_key&gt;</strong>})<strong>}</strong>))</pre><pre>;; create a s3 client<br>(def s3-client (aws/client {<strong>:api</strong>           <strong>:s3</strong><br>                            <strong>:region</strong>               <strong>&quot;us-east-1&quot;</strong><br>                            :credentials-provider    <br>                            (credentials/basic-credentials-provider<br>                            {<strong>:access-key-id</strong> &quot;<strong>&lt;your_access_key_id&gt;</strong>&quot;<br>                             <strong>:secret-access-key</strong> &quot;<strong>&lt;your_secret_access_key&gt;</strong>&quot;})}))</pre><p>Let us break it down :</p><ol><li>We look to create a s3-client object which is returned by a call to the aws/client method in the library. To that method, you pass a map of information.</li><li>This map contains information about which AWS service you want to create the client for, specified by the :api key ( says s3 here )</li><li>:region key specifies the AWS endpoint/region where you want the client operations to reflect in</li><li>:credentials-provider uses a method from the library to specify the access-key and the secret-key <strong>( Ensure that you replace the text </strong><strong>&lt;your_access_key_id&gt; and </strong><strong>&lt;your_secret_access_key&gt; with the appropriate values for your AWS user )</strong></li></ol><p>We have the S3 client ready. Let us use it.</p><p><strong><em>Note: Just to clarify, the text shown after </em></strong><strong><em>;; is the output and not part of the code to be typed on the REPL</em></strong></p><p>Let us try to list the current S3 buckets. Type the below in the REPL :</p><pre>(-&gt; s3-client<br>      (aws/invoke {:op :ListBuckets})<br>      (:Buckets))</pre><pre>;; []</pre><p>Here, am using the thread-first macro in Clojure to better represent the flow. ( thread-first and thread-last macros are very powerful constructs in Clojure that lead to code which are lucid and idiomatic )</p><p>What we are doing above is :</p><ol><li>take the s3-client that we created</li><li>use the aws/invoke method to perform an operation specified by a map on the client. The map here specifies an operation ( :op ) called :ListBuckets as that is what we want</li><li>from the result returned by aws/invoke ( which is again a map ), we retrieve the value associated with the key :Buckets</li></ol><p>This returns an empty vector [] as is the case now, since we haven’t created any S3 buckets yet ( If the AWS user that you are working with has a few buckets already, they will show up )</p><p>Let us now create a S3 bucket. Type in the below :</p><pre>(def bucket-name &quot;clojures3demo&quot;)<br>(-&gt; s3-client<br>      (aws/invoke {:op :CreateBucket :request {:Bucket bucket-name}}))</pre><pre>;; {:Location &quot;/clojures3demo&quot;}</pre><p>Here again, like earlier, we :</p><ol><li>define a name for the bucket — bucket-name</li><li>use the s3-client we created</li><li>pass a map to aws/invoke indicating the operation :CreateBucket on it with an additional parameter of a :request map specifying the bucket name that we defined</li><li>On success, this returns back a map</li></ol><p>let us check if the bucket has indeed been created by listing the buckets like before.</p><pre>(-&gt; s3-client<br>      (aws/invoke {:op :ListBuckets})<br>      (:Buckets))</pre><pre>;; [{:Name &quot;clojures3demo&quot;, :CreationDate #inst &quot;2022-10-06T06:59:43.000-00:00&quot;}]</pre><p>We see that it returns the details of the bucket that we just created, awesome!!</p><p>Empty buckets are of not much use :-) Let us upload some content to it.</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :PutObject :request {:Bucket bucket-name <br>            :Key &quot;hello.txt&quot;<br>            :Body (.getBytes &quot;Hello, World&quot;)}}))</pre><pre>;; {:ETag &quot;\&quot;82bb413746aee42f89dea2b59614f9ef\&quot;&quot;}</pre><p>Here, again, we :</p><ol><li>invoke the :PutObject operation on the s3-client passing in a request map</li><li>the request map contains information about the bucket-name where you want the object to be created, the Key which is basically the fully qualified path to the object/file on the S3 bucket that you want created and</li><li>then, the actual content of the object, :Body which is nothing but a stream of bytes representing the string Hello, World</li></ol><p>The object is now created and can be verified like so:</p><pre>(-&gt; s3-client<br>    (aws/invoke {<strong>:op :ListObjectsV2</strong> :request {:Bucket bucket-name}}))</pre><pre>;; {:Prefix &quot;&quot;, :Contents [{<strong>:Key &quot;hello.txt&quot;</strong>, :LastModified #inst &quot;2022-10-06T07:41:34.000-00:00&quot;, :ETag &quot;\&quot;82bb413746aee42f89dea2b59614f9ef\&quot;&quot;, :Size 12, :StorageClass &quot;STANDARD&quot;}], :MaxKeys 1000, :IsTruncated false, <strong>:Name &quot;clojures3demo&quot;</strong>, <strong>:KeyCount 1</strong>}</pre><p>→ invoking the ListObjectsV2 operation on the client tells that there is a file with the Key — hello.txt present in the bucket and also gives a :KeyCount of 1, as that is the only file in the bucket as of now, fantastic!!</p><p>Just to confirm that things are fine, let us create another file/object in the S3 bucket.</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :PutObject :request {:Bucket bucket-name <br>            :Key &quot;wonderful.txt&quot;<br>            :Body (.getBytes &quot;What a wonderful day!!&quot;)}}))</pre><pre>;; {:ETag &quot;\&quot;7e7634f1a88c50de19060fec6d4fefdc\&quot;&quot;}</pre><p>Let’s verify that it worked :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :ListObjectsV2 :request {:Bucket bucket-name}}))</pre><pre>;; {:Prefix &quot;&quot;, :Contents [{<strong>:Key &quot;hello.txt&quot;</strong>, :LastModified #inst &quot;2022-10-06T07:41:34.000-00:00&quot;, :ETag &quot;\&quot;82bb413746aee42f89dea2b59614f9ef\&quot;&quot;, :Size 12, :StorageClass &quot;STANDARD&quot;} {<strong>:Key &quot;wonderful.txt&quot;</strong>, :LastModified #inst &quot;2022-10-06T08:23:48.000-00:00&quot;, :ETag &quot;\&quot;7e7634f1a88c50de19060fec6d4fefdc\&quot;&quot;, :Size 22, :StorageClass &quot;STANDARD&quot;}], :MaxKeys 1000, :IsTruncated false, :Name &quot;clojures3demo&quot;, <strong>:KeyCount 2</strong>}</pre><p>All looks great!</p><p>Now, let us get back the contents of hello.txt file that we created.</p><p>On the REPL, type in :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}}))</pre><pre>;; {:LastModified #inst &quot;2022-10-06T07:41:34.000-00:00&quot;, :ETag &quot;\&quot;82bb413746aee42f89dea2b59614f9ef\&quot;&quot;, :Metadata {}, :ContentLength 12, :ContentType &quot;application/octet-stream&quot;, :AcceptRanges &quot;bytes&quot;, <strong>:Body #object[java.io.BufferedInputStream 0x131cadc1 &quot;java.io.BufferedInputStream@131cadc1&quot;]</strong>}</pre><p>We invoke the GetObject operation on the client specifying the bucket name and the object Key to be fetched.</p><p>But, something very interesting happened here. Instead of getting the contents of the file/object specified by the :Key hello.txt we get something cryptic. By default, the response Body is a stream which contains the text that is waiting to be read.</p><p>We can fetch the contents like so :</p><pre>(slurp (:Body *1))</pre><pre>;; &quot;Hello, World&quot;</pre><p>combing these two together would give something like this :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}})<br>    (:Body)<br>    (slurp))</pre><pre>;; &quot;Hello, World&quot;</pre><p>Let us try this on the second file that we created as well :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;wonderful.txt&quot;}})<br>    (:Body)<br>    (slurp))</pre><pre>;; &quot;What a wonderful day!!&quot;</pre><p>Hurray! it works great.</p><p>With that we have been able to successfully create an S3 bucket, upload content to it and fetch back the uploaded content.</p><p>Now, let us clean up the house.</p><p>To remove the files/objects uploaded to the S3 bucket, type the below in the REPL :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}}))</pre><pre>;; {}</pre><p>Let us verify that the file/object has indeed been removed :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :ListObjectsV2 :request {:Bucket bucket-name}}))</pre><pre>;; {:Prefix &quot;&quot;, :Contents [{<strong>:Key &quot;wonderful.txt&quot;</strong>, :LastModified #inst &quot;2022-10-06T08:23:48.000-00:00&quot;, :ETag &quot;\&quot;7e7634f1a88c50de19060fec6d4fefdc\&quot;&quot;, :Size 22, :StorageClass &quot;STANDARD&quot;}], :MaxKeys 1000, :IsTruncated false, :Name &quot;clojures3demo&quot;, <strong>:KeyCount 1</strong>}</pre><p>hello.txt has been removed.</p><p>Let us delete the wonderful.txt file as well.</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteObject :request {:Bucket bucket-name :Key &quot;wonderful.txt&quot;}}))</pre><pre>;; {}</pre><p>and verify the same too :</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op :ListObjectsV2 :request {:Bucket bucket-name}}))</pre><pre>;; {:Prefix &quot;&quot;, :MaxKeys 1000, :IsTruncated false, :Name &quot;clojures3demo&quot;, <strong>:KeyCount 0</strong>}</pre><p>Objects are deleted. Let us delete the S3 bucket too and finish our cleanup.</p><pre>(-&gt; s3-client<br>    (aws/invoke {:op <strong>:DeleteBucket</strong> :request {<strong>:Bucket bucket-name</strong>}}))</pre><pre>;; {}</pre><p>verifying :</p><pre>(-&gt; s3-client<br>      (aws/invoke {:op :ListBuckets})<br>      (:Buckets))</pre><pre>;; []</pre><p>The bucket is gone!</p><p>Bringing the entire flow of code pieces we worked with, together :</p><pre><strong>;; require the aws-api library</strong><br>(require &#39;[cognitect.aws.client.api :as aws]<br>         &#39;[cognitect.aws.credentials :as credentials])</pre><pre><strong>;; create a s3 client</strong><br>(def s3-client (aws/client {:api           :s3<br>                            :region               &quot;us-east-1&quot;<br>                            :credentials-provider    <br>                            (credentials/basic-credentials-provider<br>                            {:access-key-id &quot;<strong>&lt;your_access_key_id&gt;</strong>&quot;<br>                             :secret-access-key &quot;<strong>&lt;your_secret_access_key&gt;</strong>&quot;})}))</pre><pre><strong>;; list the S3 buckets</strong><br>(-&gt; s3-client<br>      (aws/invoke {:op :ListBuckets})<br>      (:Buckets))</pre><pre><strong>;; create a bucket</strong><br>(def bucket-name &quot;clojures3demo&quot;)<br>(-&gt; s3-client<br>      (aws/invoke {:op :CreateBucket :request {:Bucket bucket-name}}))</pre><pre><strong>;; Create a file/object with some string content on the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :PutObject :request {:Bucket bucket-name <br>            :Key &quot;hello.txt&quot;<br>            :Body (.getBytes &quot;Hello, World&quot;)}}))</pre><pre>;; List the objects/files in the bucket<br>(-&gt; s3-client<br>    (aws/invoke {:op :ListObjectsV2 :request {:Bucket bucket-name}}))</pre><pre><strong>;; Create a file/object with some string content on the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :PutObject :request {:Bucket bucket-name <br>            :Key &quot;wonderful.txt&quot;<br>            :Body (.getBytes &quot;What a wonderful day!!&quot;)}}))</pre><pre><strong>;; Fetch the contents of an object/file in the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}})<br>    (--&gt; (slurp :Body)))</pre><pre><strong>;; Fetch the contents of an object/file in the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}})<br>    (:Body)<br>    (slurp))</pre><pre><strong>;; Fetch the contents of an object/file in the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :GetObject :request {:Bucket bucket-name :Key &quot;wonderful.txt&quot;}})<br>    (:Body)<br>    (slurp))</pre><pre><strong>;; Delete the object/file specified by :Key</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteObject :request {:Bucket bucket-name :Key &quot;hello.txt&quot;}}))</pre><pre><strong>;; Delete the object/file specified by :Key</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteObject :request {:Bucket bucket-name :Key &quot;wonderful.txt&quot;}}))</pre><pre><strong>;; Delete the bucket</strong><br>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteBucket :request {:Bucket bucket-name}}))</pre><pre>;; Delete the bucket<br>(-&gt; s3-client<br>    (aws/invoke {:op :DeleteBucket :request {:Bucket bucket-name}}))</pre><p>Awesome! this should have given you a touch on how to work with AWS S3 in Clojure. Hope that was helpful.</p><p>In the next article, let us look at how to use the other Clojure library amazonica for interacting with AWS services, by taking may be another AWS service as an example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a42573786eb1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-s3-clojure-a42573786eb1">AWS S3 with Clojure</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST APIs with Clojure — Part I — Working with the APIs]]></title>
            <link>https://santhoshkris.medium.com/rest-apis-with-clojure-part-i-working-with-the-apis-1b045e00114c?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b045e00114c</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[clojure]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 17:03:55 GMT</pubDate>
            <atom:updated>2022-09-27T17:03:55.395Z</atom:updated>
            <content:encoded><![CDATA[<h3>REST APIs with Clojure — Part I — Working with the APIs</h3><p>Welcome to the first of a 2-part series covering various aspects on working with REST APIs in Clojure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*to7SQvfW3sKbTBIB8CubtA.png" /></figure><p>Through the series, I intend to cover the following topics :</p><blockquote><strong>Part-1</strong> — Setup the Clojure project management tool. Experiment with the REPL. Create a Clojure project and configure it with the required dependencies. Finally, setup code to invoke a few REST endpoints, gather and work with the data</blockquote><blockquote><strong>Part- 2</strong> — Building our own CRUD APIs that interact with a PostgreSQL database. We will build a small application that supports this use case</blockquote><p>With that clarified and without further ado, let’s get started.</p><p><strong>Prerequisites</strong>:</p><blockquote>Ensure that a version of JDK is installed on your system. A recommended option is — <a href="https://adoptium.net/">https://adoptium.net/</a></blockquote><blockquote>Some basic familiarity with Clojure would help. You can always refer to the wonderful Clojure docs —<a href="https://clojure.github.io/clojure/api-index.html">https://clojure.github.io/clojure/api-index.html</a> in case of any clarifications.</blockquote><blockquote>You don’t need to have anything related to Clojure installed on your system. We will get all that setup here.</blockquote><h4><strong>Setup the Clojure Project Management Tool</strong></h4><p><a href="https://leiningen.org/">Leiningen</a> is the de-facto tool for working with Clojure projects. It focuses on project automation and declarative configurations making it easy for developers to focus on the code rather on the nitty gritties of setting things up like dependencies etc. Let us get it installed.</p><h4><strong>Install Leiningen</strong></h4><p>You can follow the instructions here — <a href="https://leiningen.org/#install">https://leiningen.org/#install</a></p><p>On MAC run this :</p><pre>&gt; brew install lein</pre><p>On other platforms this should work :</p><pre>&gt; bash -c “cd ~ &amp;&amp; curl -O <a href="https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein">https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein</a> &amp;&amp; chmod +x lein”</pre><pre>&gt; cd /usr/local/bin</pre><pre>&gt; ./lein</pre><p>This should download the self-installing package and install it for you.</p><p>With lein installed, let’s try it out.</p><h4><strong>Fire up the REPL</strong> :</h4><p>Open up a terminal and run :</p><pre>&gt; lein repl</pre><p>It might ask you if you want to run it in a context without a project, type in ‘y’ and go ahead. You should see something like this.</p><pre>nREPL server started on port 56657 on host 127.0.0.1 — nrepl://127.0.0.1:56657</pre><pre>REPL-y 0.5.1, nREPL 0.8.3</pre><pre>Clojure 1.10.3</pre><pre>Java HotSpot(TM) 64-Bit Server VM 16.0.2+7–67</pre><pre>Docs: (doc function-name-here)</pre><pre>(find-doc “part-of-name-here”)</pre><pre>Source: (source function-name-here)</pre><pre>Javadoc: (javadoc java-object-or-class-here)</pre><pre>Exit: Control+D or (exit) or (quit)</pre><pre>Results: Stored in vars *1, *2, *3, an exception in *e</pre><pre><strong>user=&gt;</strong></pre><p>Let’s try out a few things here :</p><p>At the REPL prompt, type what’s below and press Return</p><pre>(* 2 3)</pre><p>This should be evaluated to 6</p><pre>6</pre><p>Type the below and press Return</p><pre>(println “Hello World”)</pre><p>You should see this result</p><pre>Hello World</pre><pre>nil</pre><p>Try the below like before on the REPL.</p><pre>(clojure.string/upper-case “what a wonderful day!”)</pre><p>You will see a result like below :</p><pre>“WHAT A BEAUTIFUL DAY!”</pre><p>Now that we have quickly verified that the basic things are working fine with Clojure, let us move ahead and create the project that we will be using for the rest of the article.</p><h4><strong>Create a Project</strong></h4><p>We will use the amazing lein tool for this</p><p>On a terminal, head to a directory where you want the Clojure project to be created and execute the below command</p><pre>lein new app rest-api-tutorial</pre><p>you should see an output like so:</p><pre>Generating a project called rest-api-tutorial based on the ‘app’ template.</pre><p>Change into the project directory</p><pre>cd rest-api-tutorial</pre><p>and you should have a folder structure created like below:</p><pre>.<br>├── CHANGELOG.md<br>├── LICENSE<br>├── README.md<br>├── doc<br>│   └── intro.md<br>├── <strong>project.clj</strong><br>├── resources<br>├── src<br>│   └── rest_api_tutorial<br>│       └── <strong>core.clj</strong><br>├── target<br>│   └── default<br>│       ├── classes<br>│       │   └── META-INF<br>│       │       └── maven<br>│       │           └── rest-api-tutorial<br>│       │               └── rest-api-tutorial<br>│       │                   └── pom.properties<br>│       ├── repl-port<br>│       └── stale<br>│           └── leiningen.core.classpath.extract-native-dependencies<br>└── test<br>    └── rest_api_tutorial<br>        └── core_test.clj</pre><p>Have highlighted the core files that we will be working with.</p><p>Now, Execute</p><pre>lein run</pre><p>You should see this on the terminal</p><pre>Hello, World!</pre><p>As you see, lein has created the boiler plate needed for a quick ‘Hello World’ application in Clojure. Thats cool!</p><p>We have a running application. Let us now get to understanding how to work with REST APIs in Clojure.</p><p>Before diving into the Clojure libraries, let us understand the REST API that we will be working with.</p><p>The REST API end points that I will be using in this instalment of the tutorial would be <strong>The One API — </strong><a href="https://the-one-api.dev/"><strong>https://the-one-api.dev</strong></a><strong>/</strong></p><p>This set of end points exposes a variety of data around the J.R.R. Tolkien’s masterpiece, The Lord of the Rings series — the books, the chapters, the movies, the characters, some interesting quotes and so on. For all the non-LOTR fans out there, please bear with me :-)</p><p>Before jumping into the Coljure REPL, let us quickly try out a few of the end points on a terminal.</p><h4><strong>Trying out the REST APIs :</strong></h4><p>Open up a terminal and type the below ( ensure you have ‘curl’ present in your path )</p><pre>curl -X GET <a href="https://the-one-api.dev/v2/book">https://the-one-api.dev/v2/book</a></pre><p>you should see something like this printed out :</p><pre>{&quot;docs&quot;:[{&quot;_id&quot;:&quot;5cf5805fb53e011a64671582&quot;,&quot;name&quot;:&quot;The Fellowship Of The Ring&quot;},{&quot;_id&quot;:&quot;5cf58077b53e011a64671583&quot;,&quot;name&quot;:&quot;The Two Towers&quot;},{&quot;_id&quot;:&quot;5cf58080b53e011a64671584&quot;,&quot;name&quot;:&quot;The Return Of The King&quot;}],&quot;total&quot;:3,&quot;limit&quot;:1000,&quot;offset&quot;:0,&quot;page&quot;:1,&quot;pages&quot;:1}</pre><p>It returns some details about the 3 books in the series.</p><p>Let us try a few more examples :</p><p>Get details of a specific book ( with the book id which is the _id field from the previous response) :</p><pre>curl -X GET <a href="https://the-one-api.dev/v2/book/5cf5805fb53e011a64671582">https://the-one-api.dev/v2/book/5cf5805fb53e011a64671582</a></pre><p>returns this :</p><pre>{“docs”:[{“_id”:”5cf5805fb53e011a64671582&quot;,”name”:”The Fellowship Of The Ring”}],”total”:1,”limit”:1000,”offset”:0,”page”:1,”pages”:1}</pre><p>Get the chapter listings of a particular book</p><pre>curl -X GET <a href="https://the-one-api.dev/v2/book/5cf5805fb53e011a64671582/chapter">https://the-one-api.dev/v2/book/5cf5805fb53e011a64671582/chapter</a></pre><p>returns the response like below :</p><pre>{&quot;docs&quot;:[{&quot;_id&quot;:&quot;6091b6d6d58360f988133b8b&quot;,&quot;chapterName&quot;:&quot;A Long-expected Party&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b8c&quot;,&quot;chapterName&quot;:&quot;The Shadow of the Past&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b8d&quot;,&quot;chapterName&quot;:&quot;Three is Company&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b8e&quot;,&quot;chapterName&quot;:&quot;A Short Cut to Mushrooms&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b8f&quot;,&quot;chapterName&quot;:&quot;A Conspiracy Unmasked&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b90&quot;,&quot;chapterName&quot;:&quot;The Old Forest&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b91&quot;,&quot;chapterName&quot;:&quot;In the House of Tom Bombadil&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b92&quot;,&quot;chapterName&quot;:&quot;Fog on the Barrow-Downs&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b93&quot;,&quot;chapterName&quot;:&quot;At the Sign of The Prancing Pony&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b94&quot;,&quot;chapterName&quot;:&quot;Strider&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b95&quot;,&quot;chapterName&quot;:&quot;A Knife in the Dark&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b96&quot;,&quot;chapterName&quot;:&quot;Flight to the Ford&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b97&quot;,&quot;chapterName&quot;:&quot;Many Meetings&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b98&quot;,&quot;chapterName&quot;:&quot;The Council of Elrond&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b99&quot;,&quot;chapterName&quot;:&quot;The Ring Goes South&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9a&quot;,&quot;chapterName&quot;:&quot;A Journey in the Dark&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9b&quot;,&quot;chapterName&quot;:&quot;The Bridge of Khazad-dûm&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9c&quot;,&quot;chapterName&quot;:&quot;Lothlórien&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9d&quot;,&quot;chapterName&quot;:&quot;The Mirror of Galadriel&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9e&quot;,&quot;chapterName&quot;:&quot;Farewell to Lórien&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133b9f&quot;,&quot;chapterName&quot;:&quot;The Great River&quot;},{&quot;_id&quot;:&quot;6091b6d6d58360f988133ba0&quot;,&quot;chapterName&quot;:&quot;The Breaking of the Fellowship&quot;}],&quot;total&quot;:22,&quot;limit&quot;:1000,&quot;offset&quot;:0,&quot;page&quot;:1,&quot;pages&quot;:1}</pre><p>Now that we have verified that the REST endpoints are ready and working, let us dive into accessing them from Clojure and try to play around with the results.</p><h4><strong>Configure the Project Dependencies :</strong></h4><p>For interacting with REST APIs in Clojure, we would need to add couple of libraries as dependencies to our project.</p><p>Open up the project.clj file in an editor (you should find the file under the rest-api-tutorial folder that we created before)</p><p>Update the :dependencies section in the file with the one shown below</p><pre>:dependencies [[org.clojure/clojure &quot;1.10.3&quot;]<br>               [clj-http &quot;3.12.3&quot;]<br>               [cheshire &quot;5.10.0&quot;]]</pre><p>Your final project.clj file would look like below :</p><pre>(defproject rest-api-tutorial &quot;0.1.0-SNAPSHOT&quot;<br>  :description &quot;FIXME: write description&quot;<br>  :url &quot;<a href="http://example.com/FIXME">http://example.com/FIXME</a>&quot;<br>  :license {:name &quot;EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0&quot;<br>            :url &quot;<a href="https://www.eclipse.org/legal/epl-2.0/">https://www.eclipse.org/legal/epl-2.0/</a>&quot;}<br><strong>  :dependencies [[org.clojure/clojure &quot;1.10.3&quot;]<br>                 [clj-http &quot;3.12.3&quot;]<br>                 [cheshire &quot;5.10.0&quot;]]</strong><br>  :main ^:skip-aot rest-api-tutorial.core<br>  :target-path &quot;target/%s&quot;<br>  :profiles {:uberjar {:aot :all<br>                       :jvm-opts [&quot;-Dclojure.compiler.direct-linking=true&quot;]}})</pre><p>Here, we are adding two dependencies.</p><p>a. <strong>clj-http</strong> — is a http client library, a Clojure wrapper on the Java’s Apache HttpComponents client.</p><p>b. <strong>cheshire</strong> — a popular library for working JSON data</p><p>With the projects.clj file updated, lein should automatically download your dependencies. Just to ensure that it does, you can also run this :</p><pre>lein deps</pre><p>This should download and setup all the dependencies that we have mentioned in the project.clj file</p><p>Ok, with the REST API end points working and our project configured with all the required dependencies, let us now jump into invoking the API end points from Clojure.</p><h4>Invoking the REST APIs from Clojure</h4><p>Head to the project directory that we created</p><pre>cd rest-api-tutorial</pre><p>Then, fire up the REPL</p><pre>lein repl</pre><p>Firstly, we will have to do a <strong>require</strong> of the dependencies, the libraries that we have configured for the project.</p><p>At the REPL prompt, type in</p><pre>(require ‘[clj-http.client :as client])</pre><p>Here, we are importing the clj-http.client namespace and giving it an alias of client</p><p>We now make a request to the book endpoint. Type the below in the REPL and press Enter :</p><pre>(client/get “https://the-one-api.dev/v2/book&quot;)</pre><p>You see the HTTP response</p><p>Let us store the response in a variable and play with it :</p><pre>(def resp (client/get “https://the-one-api.dev/v2/book&quot;))</pre><p>This associates the symbol resp with the data returned by the HTTP request.</p><p>Let us check what type the resp var is</p><pre>(class resp)</pre><p>Indicates that it is <strong>clojure.lang.PersistentHashMap</strong></p><p>Let us gather some keys from the map like so:</p><pre>(keys resp)</pre><pre>(:status resp)</pre><pre>(:headers resp)</pre><pre>(:body resp)</pre><p>We are interested in the body value. Let us capture that in a different var</p><pre>(def body (:body resp))</pre><p>Let us check the type of ‘body’</p><pre>(class body)</pre><p>It indicates that it is a String. Now, that’s interesting! It is a JSON structure captured as a String. Would be good to be able to parse it back into a JSON data structure right. Let us do that.</p><p>For that we need to require the second library that we added as a dependency.</p><pre>(require ‘[cheshire.core :as json])</pre><p>Same as before, we are importing the cheshire.core namespace and giving it an alias of json</p><p>Then, let us use a method from the library to parse the string output into a JSON</p><pre>(def body-parsed (json/parse-string body))</pre><pre>(class body-parsed)</pre><p>Now, the parsed body value indicates that it is a <strong>clojure.lang.PersistentArrayMap</strong></p><pre>(keys body-parsed)</pre><pre>;; (“docs” “total” “limit” “offset” “page” “pages”)</pre><p>However, if we try to access the individual key’s value as before like this:</p><pre>(:docs body-parsed)</pre><pre>nil</pre><p>It doesn’t work. Because, the keys are not symbols, they are strings. To get their values, you need to query a bit differently like so:</p><pre>(get body-parsed “docs”)</pre><pre>;; [{“_id” “5cf5805fb53e011a64671582”, “name” “The Fellowship Of The Ring”} {“_id” “5cf58077b53e011a64671583”, “name” “The Two Towers”} {“_id” “5cf58080b53e011a64671584”, “name” “The Return Of The King”}]</pre><p>To make things more standardised and simpler, let us convert the keys to symbols. This needs to be done at the time of parsing of the response body by passing a value of true to the parse-string method like so :</p><pre>(def body-parsed (json/parse-string body <strong>true</strong>))</pre><pre>(body-parsed)</pre><pre>(keys body-parsed)</pre><pre>;; (:docs :total :limit :offset :page :pages)</pre><p>Now, you see that the keys are symbols. Let us fetch the value associated with the ‘docs’ key</p><pre>(:docs body-parsed)</pre><pre>;; [{:_id “5cf5805fb53e011a64671582”, :name “The Fellowship Of The Ring”} {:_id “5cf58077b53e011a64671583”, :name “The Two Towers”} {:_id “5cf58080b53e011a64671584”, :name “The Return Of The King”}]</pre><p>The result as we see is a vector of maps. Each map is a book with its id and name details.</p><p>To print out the names of the books, we can do something like below:</p><pre>(map #(:name %) (:docs body-parsed))</pre><pre>;; (“The Fellowship Of The Ring” “The Two Towers” “The Return Of The King”)</pre><p>Here, we map an anonymous function over the vector of maps that we got earlier. The anonymous function as you can see picks out the value associated with the :name key from each element of the vector which is a map.</p><p>With the above we have seen how to send a GET request to a REST end point, fetch the data and process it. In this case though, the API end point didn’t need any authorization. However, that is not usually the case.</p><p>With The One API, other than a few end points which are open, the rest need authorization in the form of Bearer tokens.</p><p>To get a token, you need to signup here — <a href="https://the-one-api.dev/sign-up">https://the-one-api.dev/sign-up</a> . Once you have the token, save it some place as you will be needing to work with rest of the endpoints.</p><h4><strong>With Authorization :</strong></h4><p>Let us try some of the REST endpoints that need authorization. Jump back into the REPL, type :</p><pre>(def resp (client/get “https://the-one-api.dev/v2/movie&quot; {:headers {:Authorization “Bearer <strong>&lt;your_token_here&gt;</strong>”}}))</pre><p><strong>Do replace </strong><strong>&lt;your_token_here&gt; with your API token</strong>. Here, as you notice, we are passing the ‘Authorization’ token that is needed, as a part of the request header.</p><p>The result is something like this ( here, I am using pprint to do a pretty print of the JSON on to the terminal )</p><pre>{:cached nil,</pre><pre>:request-time 850,</pre><pre>:repeatable? false,</pre><pre>:protocol-version {:name “HTTP”, :major 1, :minor 1},</pre><pre>:streaming? true,</pre><pre>:http-client</pre><pre>#object[org.apache.http.impl.client.InternalHttpClient 0x6f7dfcbc “org.apache.http.impl.client.InternalHttpClient@6f7dfcbc”],</pre><pre>:chunked? false,<br>.....<br>.....</pre><pre>:body</pre><pre>“{\”docs\”:[{\”_id\”:\”5cd95395de30eff6ebccde56\”,\”name\”:\”The Lord of the Rings Series\”,\”runtimeInMinutes\”:558,\”budgetInMillions\”:281,\”boxOfficeRevenueInMillions\”:2917,\”academyAwardNominations\”:30,\”academyAwardWins\”:17,\”rottenTomatoesScore\”:94},{\”_id\”:\”5cd95395de30eff6ebccde57\”,\”name\”:\”The Hobbit Series\”,\”runtimeInMinutes\”:462,\”budgetInMillions\”:675,\”boxOfficeRevenueInMillions\”:2932,\”academyAwardNominations\”:7,\”academyAwardWins\”:1,\”rottenTomatoesScore\”:66.33333333},{\”_id\”:\”5cd95395de30eff6ebccde58\”,\”name\”:\”The Unexpected Journey\”,\”runtimeInMinutes\”:169,\”budgetInMillions\”:200,\”boxOfficeRevenueInMillions\”:1021,\”academyAwardNominations\”:3,\”academyAwardWins\”:1,\”rottenTomatoesScore\”:64},{\”_id\”:\”5cd95395de30eff6ebccde59\”,\”name\”:\”The Desolation of Smaug\”,\”runtimeInMinutes\”:161,\”budgetInMillions\”:217,\”boxOfficeRevenueInMillions\”:958.4,\”academyAwardNominations\”:3,\”academyAwardWins\”:0,\”rottenTomatoesScore\”:75},{\”_id\”:\”5cd95395de30eff6ebccde5a\”,\”name\”:\”The Battle of the Five Armies\”,\”runtimeInMinutes\”:144,\”budgetInMillions\”:250,\”boxOfficeRevenueInMillions\”:956,\”academyAwardNominations\”:1,\”academyAwardWins\”:0,\”rottenTomatoesScore\”:60},{\”_id\”:\”5cd95395de30eff6ebccde5b\”,\”name\”:\”The Two Towers \”,\”runtimeInMinutes\”:179,\”budgetInMillions\”:94,\”boxOfficeRevenueInMillions\”:926,\”academyAwardNominations\”:6,\”academyAwardWins\”:2,\”rottenTomatoesScore\”:96},{\”_id\”:\”5cd95395de30eff6ebccde5c\”,\”name\”:\”The Fellowship of the Ring\”,\”runtimeInMinutes\”:178,\”budgetInMillions\”:93,\”boxOfficeRevenueInMillions\”:871.5,\”academyAwardNominations\”:13,\”academyAwardWins\”:4,\”rottenTomatoesScore\”:91},{\”_id\”:\”5cd95395de30eff6ebccde5d\”,\”name\”:\”The Return of the King\”,\”runtimeInMinutes\”:201,\”budgetInMillions\”:94,\”boxOfficeRevenueInMillions\”:1120,\”academyAwardNominations\”:11,\”academyAwardWins\”:11,\”rottenTomatoesScore\”:95}],\”total\”:8,\”limit\”:1000,\”offset\”:0,\”page\”:1,\”pages\”:1}”,</pre><pre>:trace-redirects []}</pre><p>As always, the ‘body’ part is what we are interested in and that needs to be symbolized too. Type in</p><pre>(def body-parsed (json/parse-string (:body resp) <strong>true</strong>))</pre><pre>(pprint body-parsed)</pre><p>This the result you see :</p><pre>{:docs</pre><pre>[{:_id “5cd95395de30eff6ebccde56”,</pre><pre>:name “The Lord of the Rings Series”,</pre><pre>:runtimeInMinutes 558,</pre><pre>:budgetInMillions 281,</pre><pre>:boxOfficeRevenueInMillions 2917,</pre><pre>:academyAwardNominations 30,</pre><pre>:academyAwardWins 17,</pre><pre>:rottenTomatoesScore 94}<br>.......<br>.......</pre><pre>{:_id “5cd95395de30eff6ebccde5d”,</pre><pre>:name “The Return of the King”,</pre><pre>:runtimeInMinutes 201,</pre><pre>:budgetInMillions 94,</pre><pre>:boxOfficeRevenueInMillions 1120,</pre><pre>:academyAwardNominations 11,</pre><pre>:academyAwardWins 11,</pre><pre>:rottenTomatoesScore 95}],</pre><pre>:total 8,</pre><pre>:limit 1000,</pre><pre>:offset 0,</pre><pre>:page 1,</pre><pre>:pages 1}</pre><p>Now, let us process this to get the names of the movies</p><pre>(map #(:name %) (:docs body-parsed))</pre><p>This lists the series’ names as well. We are interested only in the movies. Let us discard the series names like so:</p><pre>(drop 2 (map #(:name %) (:docs body-parsed)))</pre><p>and let us pretty print it too</p><pre>(pprint (drop 2 (map #(:name %) (:docs body-parsed))))</pre><pre>;; (“The Unexpected Journey”</pre><pre>“The Desolation of Smaug”</pre><pre>“The Battle of the Five Armies”</pre><pre>“The Two Towers “</pre><pre>“The Fellowship of the Ring”</pre><pre>“The Return of the King”)</pre><p>There we have it, the list of movies neatly processed.</p><p>As a final set of examples, let us gather some information regarding the various characters in the Lord of the Ring series.</p><pre>(def resp (client/get “https://the-one-api.dev/v2/character<strong>?limit=50</strong>&quot; {:headers {:Authorization “Bearer <strong>&lt;your_token_here&gt;</strong>”}}))</pre><p>Again, <strong>do not forget to replace </strong><strong>&lt;your_token_here&gt; with your API token</strong>. Notice that we are limiting the result set to ’50’ characters as LOTR has thousands of characters by passing in a query param. And as before, let us parse the body by symbolizing the results.</p><pre>(def body-parsed (json/parse-string (:body resp) true))</pre><p>Some part of the parsed result is as below :</p><pre>{:docs<br> [{:_id “5cd99d4bde30eff6ebccfbbe”,<br> :race “Human”,<br> :name “Adanel”,<br> :realm “”,<br> :spouse “Belemir”,<br> :hair “”,<br> :gender “Female”,<br> :death “”,<br> :wikiUrl “<a href="http://lotr.wikia.com//wiki/Adanel">http://lotr.wikia.com//wiki/Adanel</a>&quot;,<br> :birth “”,<br> :height “”}<br> {:_id “5cd99d4bde30eff6ebccfbbf”,<br> :race “Human”,<br> :name “Adrahil I”,<br> :realm “”,<br> :spouse “”,<br> :hair “”,<br> :gender “Male”,<br> :death “Late ,Third Age”,<br> :wikiUrl “<a href="http://lotr.wikia.com//wiki/Adrahil_I">http://lotr.wikia.com//wiki/Adrahil_I</a>&quot;,<br> :birth “Before ,TA 1944”,<br> :height “”}<br>......<br>......<br>  {:_id &quot;5cd99d4bde30eff6ebccfbc6&quot;,<br>   :race &quot;Human&quot;,<br>   :name &quot;Almiel&quot;,<br>   :realm &quot;&quot;,<br>   :spouse &quot;&quot;,<br>   :hair &quot;&quot;,<br>   :gender &quot;Female&quot;,<br>   :death &quot;Early ,Second Age&quot;,<br>   :wikiUrl &quot;<a href="http://lotr.wikia.com//wiki/Almiel">http://lotr.wikia.com//wiki/Almiel</a>&quot;,<br>   :birth &quot;Between ,SA 700, and ,SA 750&quot;,<br>   :height &quot;&quot;}]<br>}</pre><p>The result has a bunch of characters spread across two races ‘Humans’ and ‘Elves’. Let us list out only the ‘Elves’ like so:</p><pre>(def elves (filter #(= (:race %) “Elf”) (:docs body-parsed )))</pre><p>and pretty print that too:</p><pre>({:_id &quot;5cd99d4bde30eff6ebccfbc1&quot;,<br>  :race &quot;Elf&quot;,<br>  :name &quot;Aegnor&quot;,<br>  :realm &quot;&quot;,<br>  :spouse &quot;Loved ,Andreth but remained unmarried&quot;,<br>  :hair &quot;Golden&quot;,<br>  :gender &quot;Male&quot;,<br>  :death &quot;FA 455&quot;,<br>  :wikiUrl &quot;<a href="http://lotr.wikia.com//wiki/Aegnor">http://lotr.wikia.com//wiki/Aegnor</a>&quot;,<br>  :birth &quot;YT during the ,Noontide of Valinor&quot;,<br>  :height &quot;&quot;}<br> {:_id &quot;5cd99d4bde30eff6ebccfbca&quot;,<br>  :race &quot;Elf&quot;,<br>  :name &quot;Amarië&quot;,<br>  :realm &quot;&quot;,<br>  :spouse &quot;Loved ,Finrod, but it is unknown whether they married&quot;,<br>  :hair &quot;&quot;,<br>  :gender &quot;Female&quot;,<br>  :death &quot;Still alive&quot;,<br>  :wikiUrl &quot;<a href="http://lotr.wikia.com//wiki/Amari%C3%AB">http://lotr.wikia.com//wiki/Amari%C3%AB</a>&quot;,<br>  :birth &quot;YT&quot;,<br>  :height &quot;&quot;}<br>......<br>......<br> {:_id &quot;5cd99d4bde30eff6ebccfbdc&quot;,<br>  :race &quot;Elf&quot;,<br>  :name &quot;Angrod&quot;,<br>  :realm &quot;&quot;,<br>  :spouse &quot;Eldalótë&quot;,<br>  :hair &quot;Golden&quot;,<br>  :gender &quot;Male&quot;,<br>  :death &quot;FA 455&quot;,<br>  :wikiUrl &quot;<a href="http://lotr.wikia.com//wiki/Angrod">http://lotr.wikia.com//wiki/Angrod</a>&quot;,<br>  :birth &quot;YT&quot;,<br>  :height &quot;&quot;}<br> {:_id &quot;5cd99d4bde30eff6ebccfbee&quot;,<br>  :race &quot;Elf&quot;,<br>  :name &quot;Aranwë&quot;,<br>  :realm &quot;&quot;,<br>  :spouse &quot;Unnamed wife&quot;,<br>  :hair &quot;&quot;,<br>  :gender &quot;Male&quot;,<br>  :death &quot;&quot;,<br>  :wikiUrl &quot;<a href="http://lotr.wikia.com//wiki/Aranw%C3%AB">http://lotr.wikia.com//wiki/Aranw%C3%AB</a>&quot;,<br>  :birth &quot;&quot;,<br>  :height &quot;&quot;})</pre><p>Like before, let us list down the names and the count of the Elves that we have got :</p><pre>(def elves (filter #(= (:race %) “Elf”) (:docs body-parsed )))</pre><pre>(pprint (map #(:name %) elves))</pre><pre>(count elves)</pre><p>result is</p><pre>(&quot;Aegnor&quot;<br> &quot;Amarië&quot;<br> &quot;Amroth&quot;<br> &quot;Anairë&quot;<br> &quot;Amras&quot;<br> &quot;Amdír&quot;<br> &quot;Amrod&quot;<br> &quot;Annael&quot;<br> &quot;Angrod&quot;<br> &quot;Aranwë&quot;)</pre><pre>10</pre><p>It could go on, limited only by one’s imagination for gathering and processing the data :-)</p><h4>Tying up all together :</h4><p>Now, let us tie up all the individual pieces of Clojure code that we were executing into function definitions. The complete code is as below :</p><p><strong>rest-api-tutorial/src/rest_api_tutorial/core.clj :</strong></p><pre>(ns rest-api-tutorial.core<br>  (:gen-class)<br>  (:require [clj-http.client :as client]<br>            [cheshire.core :as json]))<br></pre><pre>(def book-url &quot;<a href="https://the-one-api.dev/v2/book">https://the-one-api.dev/v2/book</a>&quot;)<br>(def movie-url &quot;<a href="https://the-one-api.dev/v2/movie">https://the-one-api.dev/v2/movie</a>&quot;)<br>(def characters-url &quot;<a href="https://the-one-api.dev/v2/character?limit=50">https://the-one-api.dev/v2/character?limit=50</a>&quot;)<br></pre><pre>;; Generate the auth header map using the api token env variable<br>(def token-string (str &quot;Bearer &quot; (System/getenv &quot;ONE_API_TOKEN&quot;)))<br>(def header-map (assoc-in {} [:headers :Authorization] token-string))<br></pre><pre>;; Get characters<br>(defn get-elf-characters<br>  [url]<br>  (let [resp (client/get url header-map)<br>        body-parsed (json/parse-string (:body resp) true)]<br>    (def elves (filter #(= (:race %) &quot;Elf&quot;) (:docs body-parsed )))<br>    ;;(pprint elves)<br>    (println (str &quot;Number of Elves we got : &quot; (count elves)))<br>    (map #(:name %) elves)<br>    ))<br></pre><pre>;; Get movies<br>(defn get-movies<br>  [url]<br>  (let [resp (client/get url header-map)<br>        body (json/parse-string (:body resp) true)]<br>    (map #(:name %) (drop 2 (:docs body)))))<br></pre><pre>;; Get books<br>(defn get-books<br>  [url]<br>  (let [resp (client/get url)<br>        body (json/parse-string (:body resp) true)]<br>    (map #(:name %) (:docs body))))<br></pre><pre>(defn -main<br>  [arg]<br>  (case arg<br>    &quot;books&quot; (println (str &quot;The books are: \n&quot; (clojure.string/join &quot;\n&quot; (get-books book-url)) ))<br>    &quot;movies&quot; (println (str &quot;The movies are: \n&quot; (clojure.string/join &quot;\n&quot; (get-movies movie-url)) ))<br>    &quot;elves&quot; (println (str &quot;The Elves are: \n&quot; (clojure.string/join &quot;\n&quot; (get-elf-characters characters-url)) ))<br>    )<br>  )</pre><p>Replace the code in core.clj under the rest-api-tutorial/src/rest_api_tutorial/folder, with the above.</p><p><strong><em>Important Note: Before you execute this, ensure that you have an environment variable named </em></strong><strong><em>ONE_API_TOKEN set in your terminal</em></strong>. <strong>This should be set to your </strong><strong>One-API token</strong></p><p>You can do that by running the command below ( on Mac and Unix based systems ):</p><pre>export ONE_API_TOKEN=&lt;your_api_token&gt;</pre><p>On Windows, the below should work :</p><pre>set ONE_API_TOKEN=&lt;your_api_token&gt;</pre><p>Then execute the application using the command below :</p><pre>lein run books</pre><p>You should see a response like below :</p><pre>The books are:<br>The Fellowship Of The Ring<br>The Two Towers<br>The Return Of The King</pre><p>books here, is the cmd line argument passed to the application</p><p>The other arguments that work as of now are movies &amp; elves</p><pre><strong>lein run movies</strong></pre><pre>The movies are:<br>The Unexpected Journey<br>The Desolation of Smaug<br>The Battle of the Five Armies<br>The Two Towers<br>The Fellowship of the Ring<br>The Return of the King</pre><pre><strong>lein run elves</strong></pre><pre>Number of Elves we got : 10<br>The Elves are:<br>Aegnor<br>Amarië<br>Amroth<br>Anairë<br>Amras<br>Amdír<br>Amrod<br>Annael<br>Angrod<br>Aranwë</pre><p>Feel free to play around with the code.</p><p><em>Note: The code presented here is only for demonstration purposes. They are meant to be neither idiomatic nor production ready in any way.</em></p><p>That brings us to the end of Part-I. We have been able to successfully create and configure a Clojure project, define the dependencies, invoke the REST API end points and tie them all up into an application. Hope this gave you a flavour of how to work with REST APIs in Clojure and was helpful.</p><p>In the next part, we will be building our own REST CRUD APIs that interact with a PostgreSQL database. We will be building a small application that supports the use case.</p><p>Until then, happy Clojuring, if that is a word :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b045e00114c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build, Test and Document REST APIs in PHP & Laravel — Part III — Documenting]]></title>
            <link>https://santhoshkris.medium.com/build-test-and-document-rest-apis-in-php-laravel-part-iii-document-77239bc04181?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/77239bc04181</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 05:18:11 GMT</pubDate>
            <atom:updated>2021-11-05T05:18:11.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build, Test and Document REST APIs in PHP &amp; Laravel — Part III — Documenting</h3><p>Co-authored by <a href="https://medium.com/u/dcf22ba6bd9">Jotheeswaran Gnanasekaran</a>, <a href="https://medium.com/u/644a204322ef">Swati Akkishetti</a>, <a href="https://medium.com/u/1b98b965abab">Charan Sai</a>, <a href="https://medium.com/u/1d4497e6f62e">Harsha Sudheer</a> and <a href="https://medium.com/u/9fbeed9bf28d">Regina Sharon G</a></p><p>Welcome to Part-III of the series on Building, Testing and Documenting REST APIs in PHP+Laravel.</p><figure><img alt="PHP+Laravel CRUD API — Build, Test and Document" src="https://cdn-images-1.medium.com/max/1024/1*ymitAE0FAQfueD_kWzvQ-A.png" /></figure><p>If you haven’t gone through the first two instalments, I highly recommend that you do so.</p><ul><li><a href="https://medium.com/@jotheeswarang/build-test-and-document-rest-apis-in-php-laravel-part-i-building-e7b857f76f47">Build, Test and Document REST APIs in PHP &amp; Laravel — Part I — Building</a></li><li><a href="https://medium.com/@sharonhazel2000/build-test-and-document-rest-apis-in-php-laravel-part-ii-testing-2557b2fbbe3b">Build, Test and Document REST APIs in PHP &amp; Laravel — Part II — Testing</a></li></ul><p>This instalment will focus on generating documentation for the REST APIs that we have built and tested in the earlier two articles.</p><p>Documenting the APIs is a highly important, but often overlooked part of the development process. It becomes all the more imperative when the developed APIs are going to be used by a different team for integrating into something they are building perhaps, which is a very common scenario in a microservices kind of environment.</p><p>Let us quickly dig in and see how this can be achieved in our PHP+Laravel project using Swagger.</p><p>Swagger is a golden standard when it comes to documenting RESTful APIs. Though, Swagger is much more than just a documentation tool, in this article, we will primarily focus on the document generation feature of it. You can read more about Swagger here — <a href="https://swagger.io/">https://swagger.io/</a></p><p><strong>Install &amp; Configure Swagger :</strong></p><p>The Laravel package that we need for this is — ‘<strong><em>DarkaOnLine/L5-Swagger’</em></strong></p><p>Let us install this into our Laravel project.</p><p>If you have followed Part-I and Part-II of the series, you should already have a project setup. If not, would highly recommend that you go through those articles before beginning, since the APIs that we build in those articles are the ones we will be documenting here.</p><p>Open a terminal, switch to your project directory and run this command :</p><pre>composer require darkaonline/l5-swagger</pre><p>With the package installed, let us publish the swagger config. Can be done using this command :</p><pre>php artisan vendor:publish — provider “L5Swagger\L5SwaggerServiceProvider”</pre><p>This should create a file named <strong><em>‘l5-swagger.php’</em> </strong>under the <strong><em>‘config’</em></strong> directory of your project.</p><p>Some of the useful values in that file that you can change would be :</p><pre>&#39;route&#39; =&gt;  [<br>    /*<br>     * Route for accessing api documentation interface<br>     */<br>    <strong><em>&#39;api&#39; =&gt; &#39;api/documentation&#39;</em></strong>,<br>],</pre><p>‘api’ — represents the URL that you will use to access the documentation. Let us change this to be like ‘<strong>/api/docs</strong>’</p><pre>&#39;generate_always&#39; =&gt; env(&#39;L5_SWAGGER_GENERATE_ALWAYS&#39;, <strong>false</strong>),</pre><p>‘generate_always’ — If you would like the docs to be generated automatically every time you make a change, you can change this value to ‘true’. This is better in a DEV environment, surely not on production.</p><p><strong>Generate the Docs :</strong></p><p>Now, let us try to generate the docs by running this command :</p><pre>php artisan l5-swagger:generate</pre><p>When you execute this, you should see an error like so :</p><figure><img alt="Error when you run swagger generate very first time without any annotations" src="https://cdn-images-1.medium.com/max/1024/0*IA0-fqZk9FGgo7v4" /></figure><p>This is expected, as we haven’t yet added any annotations to our code for Swagger to pick up. Let us start doing that.</p><p><strong>Annotations :</strong></p><p>Open up the Base Controller — <strong><em>app/Http/Controllers/Controller.php</em></strong> and add these lines just above the beginning of the class definition.</p><pre><strong>/**</strong></pre><pre><strong>* @OA\Info(</strong></pre><pre><strong>*    title=&quot;BookShop API&quot;,</strong></pre><pre><strong>*    version=&quot;1.0.0&quot;,</strong></pre><pre><strong>* )</strong></pre><pre><strong>*/</strong></pre><p>Some basic annotation to inform Swagger of what the APIs are about. Now, run the generate-docs command as before to verify that things are fine.</p><p><strong>Annotate the Endpoints:</strong></p><p>Next, let us add annotations to the different API Endpoints which in our case would be the route methods in the respective Controller.</p><p>Let us start with the<strong> ‘GET’</strong> API.</p><p>Add these lines above the <strong><em>‘getBook’</em></strong> method in the <strong><em>‘app/Http/Controllers/BookController.php</em></strong> file :</p><pre>/**</pre><pre>* @OA\Get(</pre><pre>*    path=&quot;/books/{bookId}&quot;,</pre><pre>*    operationId=&quot;getBook&quot;,</pre><pre>*    tags={&quot;getBook&quot;},</pre><pre>*    summary=&quot;Get details of a Book&quot;,</pre><pre>*    description=&quot;Returns details of a Book&quot;,</pre><pre>*    @OA\Parameter(</pre><pre>*        name=&quot;bookId&quot;,</pre><pre>*        description=&quot;Book Id&quot;,</pre><pre>*        required=true,</pre><pre>*        in=&quot;path&quot;,</pre><pre>*        @OA\Schema(</pre><pre>*            type=&quot;number&quot;</pre><pre>*        )</pre><pre>*      ),</pre><pre>*    @OA\Response(</pre><pre>*        response=200,</pre><pre>*        description=&quot;successful operation&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;object&quot;,</pre><pre>*             @OA\Property(</pre><pre>*               property=&quot;title&quot;,</pre><pre>*               type=&quot;string&quot;,</pre><pre>*               example=&quot;Hakuna Matata&quot;</pre><pre>*             ),</pre><pre>*             @OA\Property(</pre><pre>*               property=&quot;price&quot;,</pre><pre>*               type=&quot;number&quot;,</pre><pre>*               format=&quot;integer&quot;,</pre><pre>*               example=200</pre><pre>*             ),</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;author&quot;,</pre><pre>*                type=&quot;object&quot;,</pre><pre>*                example={</pre><pre>*                  &quot;first_name&quot;: &quot;John&quot;,</pre><pre>*                  &quot;last_name&quot;: &quot;Brown&quot;,</pre><pre>*                  &quot;email&quot;:&quot;babybuffalo@gmail.com&quot;</pre><pre>*                },</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;first_name&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;John&quot;</pre><pre>*                      ),</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;last_name&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;Brown&quot;</pre><pre>*                      ),</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;email&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;babybuffalo@gmail.com&quot;</pre><pre>*                      ),</pre><pre>*             ),</pre><pre>*        ),</pre><pre>*     ),</pre><pre>*    @OA\Response(response=400, description=&quot;Bad request&quot;),</pre><pre>*    )</pre><pre>*</pre><pre>* Returns all the details for a given Book id</pre><pre>*/</pre><p>These annotations define the input requirements for the GET api along with the JSON structure of the Response.</p><p><strong>A quick look at the annotations:</strong></p><p>@OA — represents Open API specification. Read more <a href="https://swagger.io/specification/">here</a></p><p>@OA\Get — Indicates the HTTP method i.e GET in this case. This will have many attributes associated with it, like :</p><p>‘path’ — URL for the endpoint</p><p>‘tags’ — helpful for grouping the APIs by sections</p><p>‘description’ — some brief information about the API being referred to here</p><p>@OA\Parameter — for the GET api in our case, we need to pass in the bookID. This annotation defines this input parameter, its ‘type’ etc.</p><p>Then, comes the Response</p><p>@OA\Response — You can have multiple Responses to an API. We add one here for a successful response.</p><p>@OA\JsonContent — Defines the structure of the JSON being returned by the GET API. This JSON has multiple property values of various types as you see in the above annotation.</p><p>These properties are annotated by using :</p><p><em>@OA\Property — </em>Each property has a ‘key’ which is the name and a ‘type’. There are different type values like string, number, integer, boolean, array and object.</p><p>The GET api response, the JSON content that is sent back has an ‘object’ which has ‘title’ and ‘price’ fields and another embedded object, ‘author’ that has details about the Author.</p><p><strong>Generate Docs again:</strong></p><p>Once the annotations are added, we can generate the documentation by running :</p><pre>php artisan l5-swagger:generate</pre><p><strong>Swagger UI:</strong></p><p>Now, visit the URL that you configured in ‘config/l5-swagger.php’, in our case that is — <a href="http://127.0.0.1:8000/api/docs">http://127.0.0.1:8000/api/docs</a></p><p>You should see something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QXurxDkWcEGjJIuv" /></figure><p>Expand the section and you see all the details regarding the BookShop GET API endpoint, like so :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0E0vhMI4qV8f3Q6B" /></figure><p>There is also a facility on the UI to quickly invoke and test out the API.</p><p>Awesome, the documentation for GET is now ready!</p><p>Following a similar process you can add annotations to describe the other API endpoints (the POST, PUT and DELETE ).</p><p>Add these lines above the <strong><em>‘addBook’</em></strong> method (POST API) in the <strong><em>‘app/Http/Controllers/BookController.php</em></strong> file :</p><pre>/**</pre><pre>* @OA\POST(</pre><pre>*     path=&quot;/books&quot;,</pre><pre>*     summary=&quot;Add a new Book&quot;,</pre><pre>*     tags={&quot;addBook&quot;},</pre><pre>*     @OA\RequestBody(</pre><pre>*        required = true,</pre><pre>*        description = &quot;New Book Details&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;object&quot;,</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;title&quot;,</pre><pre>*                type=&quot;string&quot;,</pre><pre>*                example=&quot;Davinci Code&quot;</pre><pre>*             ),</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;price&quot;,</pre><pre>*                type=&quot;number&quot;,</pre><pre>*                format=&quot;integer&quot;,</pre><pre>*                example=550</pre><pre>*             ),</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;author&quot;,</pre><pre>*                type=&quot;object&quot;,</pre><pre>*                example={</pre><pre>*                  &quot;first_name&quot;: &quot;Dan&quot;,</pre><pre>*                  &quot;last_name&quot;: &quot;Brown&quot;,</pre><pre>*                  &quot;email&quot;: &quot;dan@danbrown.com&quot;</pre><pre>*                },</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;first_name&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;Dan&quot;</pre><pre>*                      ),</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;last_name&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;Brown&quot;</pre><pre>*                      ),</pre><pre>*                      @OA\Property(</pre><pre>*                         property=&quot;email&quot;,</pre><pre>*                         type=&quot;string&quot;,</pre><pre>*                         example=&quot;dan@danbrown.com&quot;</pre><pre>*                      ),</pre><pre>*             ),</pre><pre>*        ),</pre><pre>*     ),</pre><pre>*</pre><pre>*    @OA\Response(</pre><pre>*        response=201,</pre><pre>*        description=&quot;successful operation&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;string&quot;,</pre><pre>*             example=&quot;Book is successfully added&quot;</pre><pre>*        ),</pre><pre>*     ),</pre><pre>*</pre><pre>* )</pre><pre>*/</pre><p>Add these lines above the <strong><em>‘updateBook’</em></strong> method (PUT API) in the <strong><em>‘app/Http/Controllers/BookController.php</em></strong> file :</p><pre>/**</pre><pre>* @OA\PUT(</pre><pre>*     path=&quot;/books/{bookId}&quot;,</pre><pre>*     summary=&quot;Update a Book&quot;,</pre><pre>*     tags={&quot;updateBook&quot;},</pre><pre>*    @OA\Parameter(</pre><pre>*        name=&quot;bookId&quot;,</pre><pre>*        description=&quot;Book Id&quot;,</pre><pre>*        required=true,</pre><pre>*        in=&quot;path&quot;,</pre><pre>*        @OA\Schema(</pre><pre>*            type=&quot;number&quot;</pre><pre>*        )</pre><pre>*      ),</pre><pre>*     @OA\RequestBody(</pre><pre>*        required = true,</pre><pre>*        description = &quot;Update Book Details&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;object&quot;,</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;title&quot;,</pre><pre>*                type=&quot;string&quot;,</pre><pre>*                example=&quot;The Elephant Whisperer&quot;</pre><pre>*             ),</pre><pre>*             @OA\Property(</pre><pre>*                property=&quot;price&quot;,</pre><pre>*                type=&quot;number&quot;,</pre><pre>*                format=&quot;integer&quot;,</pre><pre>*                example=850</pre><pre>*             ),</pre><pre>*        ),</pre><pre>*     ),</pre><pre>*    @OA\Response(</pre><pre>*        response=200,</pre><pre>*        description=&quot;successful operation&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;string&quot;,</pre><pre>*             example=&quot;Book is successfully updated&quot;</pre><pre>*        ),</pre><pre>*     ),</pre><pre>* )</pre><pre>*/</pre><p>Add these lines above the <strong><em>‘deleteBook’</em></strong> method (DELETE API) in the <strong><em>‘app/Http/Controllers/BookController.php’</em></strong> file :</p><pre>/**</pre><pre>* @OA\Delete(</pre><pre>*    path=&quot;/books/{bookId}&quot;,</pre><pre>*    operationId=&quot;deleteBook&quot;,</pre><pre>*    tags={&quot;deleteBook&quot;},</pre><pre>*    summary=&quot;Delete a Book&quot;,</pre><pre>*    description=&quot;Deletes a Book&quot;,</pre><pre>*    @OA\Parameter(</pre><pre>*        name=&quot;bookId&quot;,</pre><pre>*        description=&quot;Book Id&quot;,</pre><pre>*        required=true,</pre><pre>*        in=&quot;path&quot;,</pre><pre>*        @OA\Schema(</pre><pre>*            type=&quot;number&quot;</pre><pre>*        )</pre><pre>*      ),</pre><pre>*    @OA\Response(</pre><pre>*        response=200,</pre><pre>*        description=&quot;successful operation&quot;,</pre><pre>*        @OA\JsonContent(</pre><pre>*             type=&quot;string&quot;,</pre><pre>*             example=&quot;Book is successfully deleted&quot;</pre><pre>*        ),</pre><pre>*     ),</pre><pre>*    @OA\Response(response=404, description=&quot;Book not found&quot;),</pre><pre>*    )</pre><pre>*</pre><pre>* Returns all the details for a given Book id</pre><pre>*/</pre><p>After these changes, regenerate the API docs by running this command :</p><pre>php artisan l5-swagger:generate</pre><p>Bring up the Swagger UI again or refresh the page if you are already on it.</p><p>You should see something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IC1Lb3U_1JWOSJXW" /></figure><p>Congratulations! With this, you have successfully documented all your REST APIs, a crucial part of the development process.</p><p>You can find all the code that you worked through in this 3 part series on GitHub:</p><p><a href="https://github.com/J-CHARAN-SAI/BookShop">GitHub - J-CHARAN-SAI/BookShop</a></p><p>Note: The code here is only for educational and learning purposes, definitely not production ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77239bc04181" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A TETE-A-TETE WITH THE BOTTLENOSE DOLPHINS]]></title>
            <link>https://santhoshkris.medium.com/a-tete-a-tete-with-the-bottlenose-dolphins-4931896968bc?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/4931896968bc</guid>
            <category><![CDATA[nature-photography]]></category>
            <category><![CDATA[dolphins]]></category>
            <category><![CDATA[nature]]></category>
            <category><![CDATA[andaman]]></category>
            <category><![CDATA[travel]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 06:53:29 GMT</pubDate>
            <atom:updated>2021-10-29T06:53:29.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Dolphins, are NOT FISH, a common misconception. They are highly intelligent and charismatic marine mammals.</p><p>Bottlenose dolphins, the ones you see in the images here, belong to the genus <em>Tursiops</em> and are the most common members of the family <em>Delphinidae</em>, the family of Oceanic dolphins. They are widespread, inhabiting the warm and temperate waters worldwide.</p><p>There are 3 distinct species of Bottlenose dolphins found across the world. The Common bottlenose dolphin (<em>Tursiops truncatus</em>), the Indo-Pacific bottlenose dolphin (<em>Tursiops aduncus</em>) and the Burrunan dolphin (<em>Tursiops australis</em>). As you might have guessed, the species found along the coastal waters of India is the <em>Tursiops aduncus</em>, the species I had a great encounter with, out in the Andaman sea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_oHVzRzwh-omd_lu.jpeg" /></figure><p>The Bottlenose dolphins can grow to a length of around 4 meters and can weigh about a 300 kg. They are known to live for more than 40 years. Their elongated upper and lower jaws form what is known as the rostrum, their snout. The curved structure of the snout give them their characteristic smiling face.</p><p>Dolphins are highly intelligent animals, displaying abilities of mimicry, self recognition and use of tools while looking for food among many others. They are also known to pass on cultural knowledge from generation to generation. Dolphins have the 3rd largest encephalization ( meaning, the ratio of the brain mass to the size of the animal ) of all mammals on Earth, sharing close ratios with those of humans and the great apes.</p><blockquote>A Quick fact — Some researchers hypothesise that the number of nerve cells (neurons) in the cortex of the brain predicts intelligence in mammals. A 2019 study estimated the number of neurons in the cerebral cortex of three common bottlenose dolphins and found numbers ranging from 11.7 to 15.2 billion neurons. The human average being approximately 16 billion.</blockquote><blockquote><em>- </em>Wikipedia</blockquote><p>Though the Dolphins are aquatic and spend most of their time under the water, they cannot breathe out there. They have to surface every few minutes to take in a gasp of fresh air. The blowhole on the top of their heads ( as you see in the image above ) is the functional nose which they open as they surface to breathe. It is closed by a membrane while under water.</p><blockquote>An interesting fact is that, Dolphins can exchange up to 80% of the contents of their lungs when they inhale. Humans, by comparison, can only exchange 17% of the air in their lungs when they breathe.</blockquote><blockquote><em>- </em>Animal Fact Guide</blockquote><p>Also, dolphins are not involuntary breathers like humans. They have to consciously surface every few minutes. This means that Dolphins cannot fully sleep. One side of their brain must always remain active so that they remember to breathe.</p><p>Dolphins are very social and fun loving creatures too. They swim around in large groups called pods, communicating between each other using a variety of pulses, whistles and body language. Dolphins are know to form friendships that last decades.</p><p>The whistle of a Dolphin is its unique signature, something that an individual is born with. They can identify each other by their whistle. The groups stick together, hunting, helping taking care of each other’s young, protecting each other and simply having fun.</p><p>Dolphins are know to be attracted by the wake of ships and boats. They seem to follow the large boats to enjoy a lovely surf over the waves created. It is also a good opportunity to look for a meal I guess, as the fish on the surface get dispersed by the ship’s movement.</p><p>This was exactly what I encountered while on a ship out in the Andaman sea. It was a bright afternoon. We just had finished a lovely lunch on the ship and lazying around when we noticed something out in the sea which seemed to be fast approaching our ship. Leaping and bouncing off the water’s surface, we could clearly see that they were the Bottlenose dolphins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WhDdYs4J2Fc_M_40.jpg" /></figure><p>The pod was a big one with young ones too. Here is a mom and her calf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-23wCS6NQo6bOG-a.jpg" /></figure><p>The fun element was well and truly there. Individuals were throwing themselves out of the water and putting up a full on display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Di1zuat9rkHOz2mo.jpg" /></figure><p><strong><em>Image above: © Sagar Vibhute</em></strong></p><p>They came right up close to our ship and were swimming around, at times, very close to water’s surface. Looked like they were teasing us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TIsWXlPJRkhbA9Ly.jpeg" /></figure><p>One individual came right next to our ship and breached the water’s surface. The huge, majestic mammal was entirely visible in all its glory. What a sight that was !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j8LdNpUdi5i1RVs_.jpg" /></figure><p>Before diving back in, with a huge splash….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fh84jT_KwMR2zI5p.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5S8krlGwGgIMOvC6.jpeg" /></figure><p>After a few minutes of the mind-boggling display, the dolphins were all gone. Bearing witness to this natural wonder, powerful thoughts started rushing to my mind. Such beautiful mammals, who should be roaming the wild waters are instead put in theme parks and trained to perform tricks, just for our entertainment. Such a shame!</p><p>After a period of lull, the beautiful flying fish started coming out to satiate our hearts. These were no less with their amazing displays.</p><p>Flying out of the water….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eEhYAXEbwb2wTmiw.jpg" /></figure><p>They skimmed across the surface using their powerful tail fins, covering quite a distance by doing so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dDUIwbqEq8AFDnpf.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ge4wJhRJG74WVJk8.jpg" /></figure><p>It was nothing short of spectacular!</p><p>All in all, it was a truly memorable and fun filled afternoon. And the rather monotonous ship journey turned out to be a scintillating experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4931896968bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MOODY TONES WITH AN INDIAN EAGLE OWL]]></title>
            <link>https://santhoshkris.medium.com/moody-tones-with-an-indian-eagle-owl-f61bc65b3de8?source=rss-3232a696f5da------2</link>
            <guid isPermaLink="false">https://medium.com/p/f61bc65b3de8</guid>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[nature]]></category>
            <category><![CDATA[nature-photography]]></category>
            <category><![CDATA[indian-eagle-owl]]></category>
            <category><![CDATA[owls]]></category>
            <dc:creator><![CDATA[Santhosh Krishnamoorthy]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 06:42:31 GMT</pubDate>
            <atom:updated>2021-10-29T06:42:31.864Z</atom:updated>
            <content:encoded><![CDATA[<p>Indian Eagle Owl (<a href="https://en.wikipedia.org/wiki/Indian_eagle-owl">Bubo bengalensis</a>), also known as the Rock Eagle Owl or the Bengal Eagle Owl is a large, horned owl found across the hilly, rocky scrub-forests of the Indian Subcontinent. The cat-like long ear tufts, those big glowing eyes and the majestic size are unmistakable.</p><p>Quite widely distributed across India, this species is found all over. However, the place I most love to see them in, is the amazing capital town of the erstwhile Vijayanagar empire, Hampi. This species is always high on my target list whenever I visit the place. In Hampi, they can be found inhabiting the rocky-cliff sides of the Tungabhadra high-level canal in a place called Kamalapura. The cliff face and the scrub forest behind form an ideal habitat for this beautiful bird. The owls are so well camouflaged against the outgrowth that one needs very keen, discerning eyes to spot them.</p><p><strong>THE STARE — The moody tone</strong> that is unmissable when you see an individual. The beautiful ear tufts raise up assessing you and the situation. The big orange-yellow or orange-red eyes seem to glow as they open up wide. They are quite entrancing and so powerful!</p><p>A few of those moments below…</p><figure><img alt="The stare — Indian Eagle Owl" src="https://cdn-images-1.medium.com/max/1024/0*fOzajzLPwRpDVZ_G.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qyTKiTWo7kPVjwBp.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SVZuQG6hcBp-0yxb.jpg" /></figure><p>As you can notice, the Indian eagle owl is a huge and powerful bird, no second thoughts to it. Its presence can be felt just by looking into its eyes.</p><p><strong>PARENTING — A more subtle, mellowed moody tone</strong>. I got lucky to encounter this bird with its chicks. Nesting along the canal’s rocky, slippery walls and having to handle young, naive chicks is indeed a tough job. It was wonderful to see the soft and caring mother, with her curious and over-eager chicks. One of the chicks was quite eager to take its first steps and was heading very close to the rock’s edge too. Yet another one, not shown in the image below was already a few steps down on the slippery slope. A nervous task for the parent indeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ru7KjY3eHaH8SKWF.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZRWPVfNH7tOye8p9.jpg" /></figure><p>Indian Eagle Owls are nocturnal animals like most owls are. As the dusk begins to set in, they are all active and up on the scrub-forest above and behind the walls of the canal. They mainly feed on rodents but are capable and have also been seen taking down big birds like the Indian peafowl.</p><p><strong>SELF INTROSPECTION — A mood of deliberation</strong> I guess, as the day begins for the owl. Sitting over a small mound, it seems to be planning the day, or should I say, the night ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dUxzONaJRCm05rAA.jpg" /></figure><p>With a plan finalised, it was time to move on, to go and find food for itself, its mate and chicks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*araz76BNb5tSRceb.jpg" /></figure><p>These birds are powerful fliers too. They just whizz past you in total silence. The flapping of their huge wings create absolutely no sound whatsoever, very characteristic of Owls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KeLmOd8S9o9SklSE.jpg" /></figure><p><strong>SUNSET LOOKOUT </strong>— <strong>A golden moody tone.</strong> Indian eagle owls prefer to hunt from a perch, a good vantage point. Sitting high up and looking around for potential prey. Caught this individual in a lovely setting as the sun was going down behind the hills in the lovely land of Hampi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SxyIBP1N_MsQwR9f.jpg" /></figure><p>So, there you go, a few interesting settings or moods that I have encountered this majestic bird in. Wanted to share this with you all. Hope you enjoyed them. Do leave your thoughts in the comments below.</p><p>Until next time.., cya…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f61bc65b3de8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>