<?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 Prince Igwenagha on Medium]]></title>
        <description><![CDATA[Stories by Prince Igwenagha on Medium]]></description>
        <link>https://medium.com/@princeigwe?source=rss-99759e6df3d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C5pRhuzjTRJ6Sth1_B2W5A.jpeg</url>
            <title>Stories by Prince Igwenagha on Medium</title>
            <link>https://medium.com/@princeigwe?source=rss-99759e6df3d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:04:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@princeigwe/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[Understanding the Diamond Proxy Pattern (EIP-2535): A Developer’s Guide to Scalable Smart Contracts.]]></title>
            <link>https://princeigwe.medium.com/understanding-the-diamond-proxy-pattern-eip-2535-a-developers-guide-to-scalable-smart-contracts-de58ad014287?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/de58ad014287</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 07:50:05 GMT</pubDate>
            <atom:updated>2026-03-17T07:50:05.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q36vvYx_7kI6n00lLKFQ-w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@onecaratstore?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">One Carat Store</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-diamond-ring-on-a-blue-cloth-DpD5JvEwOds?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>First of all, smart contracts are not “smart” in the AI sense, neither are they “contracts” in the legal sense. Now that I’ve gotten that off my chest…</blockquote><p>Imagine a moment where you have a project idea, with the knowledge of smart contracts being immutable, you ask yourself how you’d apply changes and fixes after you have deployed your contract. You learn about the Transparent Upgradeable Proxy Pattern, which allows you to switch from one implementation contract to another according to the fixes and changes needed. At the point of applying this newly acquired knowledge to your project idea, you realize that this pattern does not fit well, because you don’t want to write all your implementation logic in one contract. And now you are back to square zero of figuring out what works. Yes, I’m exploring web3, and this is my story.</p><p>After a quick web search on “how to attach multiple smart contracts to a proxy contract”, the AI mode highlighted “diamond proxy” in its overview response. At first, I thought it was some type of hallucination, but since I knew nothing else, I did a query search on that, too.</p><p><em>Overwhelmed. Confused. “Just go outside and touch grass, guy.”</em></p><p>These were how I felt as I went through articles and pages on this topic. Things weren’t just connecting, and I just stuck with articles from the author of the pattern himself, <a href="https://substack.com/@eip2535diamonds">Nick Mudge</a>. Now that I believe that I finally understood it, this is me sharing my knowledge (and maybe my experience) with you.</p><h3><strong><em>Upgradable Smart Contracts</em></strong></h3><p>If you’ve played around a bit in smart contract development, you should know by now that they are immutable, meaning that once deployed, that’s it. You can’t make any other changes or fixes to your application. Coming from a web2 software engineering background, this feels very restricted, because errors and ideas for an upgrade will always come up.</p><p>So, how is this handled? Upgradeable smart contracts. “Upgradeable”, not in the sense of making changes to an already deployed contract, but switching an old deployed version with a new one. This way, we have users interacting with the same proxy address, while the implementation logic behind it changes. Based on the upgradeable pattern used, these contracts are called <strong>implementation contracts</strong> or <strong>facets. </strong>They contain the logic of your decentralized application. With every contract having its own storage, doesn’t that mean all your activities and data are gone as a user for every upgrade and fix? Not really. When interacting with a facet/implementation contract, you are not actually doing that directly; you are “delegating a call” to the facet through a channel. This channel is a <strong>proxy contract</strong>.</p><h3><strong><em>Proxy Smart Contract</em></strong></h3><p>As mentioned earlier, when interacting with the implementation contract, this is done through the proxy. This happens with a delegatecall to the implementation contract. In other words, the user wants to use a functionA on Implementation A contract, they interact with the proxy, the proxy “borrows” the function from Implementation A and executes it as its own, and data is saved in the proxy’s storage, instead of the implementation’s. This is the proxy contract executing external code in its own context. This way, whenever there is an update for an implementation contract, users don’t have to repeat the onboarding process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*rmodVdHbfgAyDinIBc0bzg.png" /><figcaption>Transparent proxy operation</figcaption></figure><p>There are different ways (<a href="https://www.cyfrin.io/blog/upgradeable-proxy-smart-contract-pattern">patterns</a>) of doing this, and I found the <strong>Transparent Proxy Pattern </strong>to be the easiest of them all. After learning it, I faced a new conceptual challenge. This pattern can only handle one implementation contract at a time. This means having most of your logic written in one smart contract, which can appear to be tightly coupled. Hmm. If you’re like me, you may also see this as counterproductive as your contract grows, as I love to have different system operations modularized. A different type of pattern helps with this issue.</p><h3><strong><em>Diamond Proxy Pattern</em></strong></h3><p>The diamond proxy pattern is another pattern that allows you to divide logic across multiple smart contracts to be called by a proxy. This solves the counterproductive issue mentioned earlier by the Transparent Proxy pattern. Besides that, the maximum size of a smart contract’s bytecode allowed to be executed on the EVM is 24kb. Once this is reached, there is little to nothing you can do about it, and that could mean no new features allowed. This can be resolved by working with the Diamond pattern from the onset.</p><p>In this pattern, the logic contracts are called <strong>facets</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*o_GGKvk8thbCI4rrM6G6hA.png" /><figcaption>Diamond proxy operation</figcaption></figure><h3><strong><em>Components of the Diamond Proxy Pattern</em></strong></h3><p>There are several key parts that need to be set up when working with this pattern, and yes, it is more technical than the Transparent proxy.</p><h4>Diamond Storage</h4><p>This is a major component of this pattern, as your facets share it; reading and writing data to it. Solidity smart contracts have a storage of about 2²⁵⁶ slots; indexed from 0 to 2²⁵⁶ — 1, and by default, for every state variable defined in a contract, they are sequentially assigned to a slot.</p><pre>contract Profile{<br>  string firstName; // slot 0 [base slot]<br>  string lastName;  // slot 1<br>  uint8 age; // slot 2<br>  ...  // ... slot n<br>}</pre><p>However, working with a diamond storage allows us to start our base slot at any location in the contract’s slot storage with the keccak256 hash of a unique string.</p><pre>bytes32 constant STRUCT_STORAGE_POSITION = keccak256(&quot;my_startup.main.diamond.storage&quot;);<br><br>struct FacetAddressAndFunctionSelectorPosition{<br>  address facetAddress;<br>  uint16 functionSelectorPosition; // position of the function selector in the FacetAddressPositionAndFunctionSelectors.functionSelectors array<br>}<br><br>// this holds details of the position of a facet address in the facetAddresses array,<br>// along with the function selectors of that facet<br>struct FacetAddressPositionAndFunctionSelectors{<br> bytes4[] functionSelectors;<br> uint16 facetAddressPosition; // position of the facet address in the facetAddresses array<br>}<br><br>struct DiamondStorage {<br>  mapping(bytes4 =&gt; FacetAddressAndFunctionSelectorPosition) selectorToFacetAddressAndFunctionSelectorPosition;<br>  mapping(address =&gt; FacetAddressPositionAndFunctionSelectors) addressToFacetAddressPositionAndFunctionSelectors;<br>  address[] facetAddresses;<br>}</pre><p>“Why do we need a diamond storage? Can’t facets use their own storage mechanism?”, you may ask. The diamond storage, being a struct data type for all state variables and mappings of function selectors, solves a storage location problem. In the case where we have facets using their own storage, this can overwrite data. If facets used the standard Solidity storage flow (starting from slot 0), they would overwrite each other because they all execute in the context of the same proxy contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*e2ZKWzyuE0qQMosGt945Zg.png" /><figcaption>storage collision</figcaption></figure><p>So the diamond storage is then imported and used amongst the facets. Think of it like little siblings trying to affirm ownership of a bookshelf, where one tosses away the storybooks of the other, but then daddy comes in and says the bookshelf belongs to neither of them and that it’s his, but then assigns sections of the shelf to the kids and states that they can also read each other’s books. I hope that makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Fo3Yl6_toElTYWtSNGyndw.png" /><figcaption>Diamond Storage</figcaption></figure><p>The most important aspect of this, as you already know, is that you get to replace your facets without data loss. In addition, the diamond storage is responsible for mapping function-selector calls to the appropriate facets, as well as keeping track of all function selectors of a facet and all facets used in the diamond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*K_bpz0KOlxiMz5qGEU3qzQ.png" /><figcaption>Diamond Storage</figcaption></figure><h4>Diamond Cut</h4><p>In real life, a diamond cut is a technique used to shape a diamond in order to make it appear polished and more luminous. Diamond cuts in this proxy pattern follow this concept by enabling you to update contract applications as needed. In other words, the diamond cut is simply a function that allows you to add, replace, or remove facets from your diamond. This function must be reserved for the diamond contract owner.</p><pre>function diamondCut(<br>    IDiamondCut.FacetCut[] memory _diamondCut,<br>    address _init,<br>    bytes memory _calldata<br>  )internal{<br>    for(uint256 facetIndex; facetIndex &lt; _diamondCut.length; facetIndex++){<br>      IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;<br>      if(action == IDiamondCut.FacetCutAction.Add){<br>        addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);<br>      }<br>      else if(action == IDiamondCut.FacetCutAction.Replace){<br>        replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);<br>      }<br>      else if(action == IDiamondCut.FacetCutAction.Remove){<br>        removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);<br>      }<br>      else{<br>        revert(&quot;DiamondCut: Invalid facet cut action&quot;);<br>      }<br>    }<br><br>    emit DiamondCutEvent(_diamondCut, _init, _calldata);<br>    initializeDiamondCut(_init, _calldata);<br>  }</pre><h4>Diamond Loupe Functions</h4><p>In real life, a diamond loupe is a magnifying glass that allows you to examine a diamond for cuts, clarity, and colour. In the same light, these functions work hand-in-hand with the diamond storage, allowing you to examine facets after a cut. There are 4 standard functions in this pattern, with each having its own operation:</p><ul><li>facetAddresses() This function returns the address of all facets used by the diamond.</li><li>facetFunctionSelectors(address _facetAddress) This function returns all the function selectors of a particular facet.</li><li>facetAddressOfFunctionSelector(bytes4 _functionSelector) This returns the facet address of a function selector.</li><li>facets() This returns all facets together with their function selectors.</li></ul><h4>Diamond</h4><p>This is the proxy smart contract that the user interacts with, which in turn interacts with hidden facets. So for every change of facet, the dApp does not have to change its contract address.</p><p>Now that the theory is out of the way, let’s put it to work. We’ll build a diamond with two facets - one for managing user profiles, and another for a reputation token tied to those profiles. The reason for this pairing is intentional: these are two distinct concerns that still need to share state, which is exactly the kind of problem the diamond pattern was designed to handle elegantly.</p><h3>Demonstration</h3><p><em>The repo for this demo can be found </em><a href="https://github.com/Princeigwe/diamond-profile-token"><em>here</em></a><em> (diamond-profile-token).</em></p><p>I consider the diamond storage to be the most important component of this pattern, so we will be starting out by writing a library.</p><p>Just so you know, I’ll be walking through the implementation using a series of embedded GitHub Gist snippets. Each file is built progressively - so DiamondStorage(i).sol is the starting point, DiamondStorage(ii).sol builds on it, and so on. Follow along in that order, and it should all click.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed44db50066798ce1c880f38ca11f8c1/href">https://medium.com/media/ed44db50066798ce1c880f38ca11f8c1/href</a></iframe><p>In the above snippet, we have a set of structs and functions that help with the foundational setup of our contracts. A LibProfileTokenStorage library is defined, which holds reusable components that will be imported for use by the diamond proxy and our facets. The DiamondStorage struct is essentially the diamond&#39;s shared backbone — it keeps track of which facets are registered and where each function selector points, while also holding any state that multiple facets need access to. With a scaffold of our library, we move on to define an interface for the diamond cut operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20fbe5e6e888f0e1fa9cf1173b8b63ff/href">https://medium.com/media/20fbe5e6e888f0e1fa9cf1173b8b63ff/href</a></iframe><p>This interface serves as a blueprint for facet-cutting. The FacetCut struct holds a set of values for a diamond cut. The facetAddress being the address of the facet we want to operate on; the action being what type of action we want to perform on the facet, this is any of the values from the FacetCutAction enum. The actions of the enum are used in different ways.</p><ul><li><strong>Add</strong>: As the name suggests, this is used to add a facet to the diamond.</li><li><strong>Replace:</strong> Say, for example, you needed to make changes to the logic of a specific function without making a change to its identifier or parameters. This action is the one for the operation. You just have to make sure that all function selectors of the new facet exist with nothing new.</li><li><strong>Remove: </strong>As the name implies, this removes a facet and all its function selectors from the registry.</li></ul><p>Then we have the functionSelectors being function selectors for the facet. The _init and _calldata parameters are used to call an initialization contract during the facet cut process, which could help in running a unique function specifically designed for the facet, or setting initial values of diamond-storage state variables for the facet. In our case, we won’t be working with these parameters. And then for the next line of action, an event is to be emitted to tell us that the facet-cut was a successful operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d89246638415c0617a1c3c989d6eaf/href">https://medium.com/media/c8d89246638415c0617a1c3c989d6eaf/href</a></iframe><p>An update on our diamondCut function, it is designed in a way that multiple facets can be operated upon in one single call. These facets, together with their function selectors and actions, are bundled in a _diamondCut list. Each of the items is operated upon by other functions, as a result of its action attribute.</p><p>Populating our action functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87238c2fffe0e0de80b8370c466db4b8/href">https://medium.com/media/87238c2fffe0e0de80b8370c466db4b8/href</a></iframe><p>With our diamond-cut action functions in place, our next line of operation will be implementing diamond loupe functions. Similar to how we defined our diamond cut functions, we will be defining an interface for loupe functions, allowing them to be inherited in the library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757e3ffefd9f79d5fca57be1a4ea3bd6/href">https://medium.com/media/757e3ffefd9f79d5fca57be1a4ea3bd6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1cd504cfe65fbfc699a6886e09ef1c3/href">https://medium.com/media/b1cd504cfe65fbfc699a6886e09ef1c3/href</a></iframe><p>If you have followed up to this point, well done. With our library in place, we have sections for facet mappings, diamond cut, and loupe operations. This library can be reused in our diamond proxy and across all future facets.</p><p>Next up, we will define our diamond proxy contract. This is the contract exposed to users, owners, and admins alike — the single address they will always interact with regardless of what changes underneath.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ae39d687a94dcb6166279705da51996/href">https://medium.com/media/1ae39d687a94dcb6166279705da51996/href</a></iframe><p>In our diamond contract, you will notice several functions being called from our LibProfileTokenStorage . On this contract, the contract owner can make diamond cuts, view the underlying facets, and transfer ownership, while anyone else can interact with the underlying facets through the proxy’s fallback mechanism. You may want to consider receiving Ether for your project, so a receive function is added as well.</p><p>With this in place, we will be defining our facets, Profile and Token .</p><p>Before going down this road, here are a few rules to take note of:</p><ol><li>New state variables must only be added at the end of the diamond storage struct, not in the middle, not at the beginning, just at the end, to avoid overwriting of data for existing facets.</li><li>Aside from the diamond storage struct, if you will ever work with a struct as a state variable, it is advisable to define it with a mapping. This way, it is possible to add new properties to the end of the struct.</li></ol><p>Here is a link to more rules to follow.</p><p><a href="https://eip2535diamonds.substack.com/p/diamond-upgrades">Diamond Upgrades</a></p><p>Now, back to our demo, we will be starting with the profile facet. We want to be able to create and view a profile. However, we will be starting with version 1 of the profile facet, which only allows us to create a profile.</p><p>Focusing only on our new state variables, we add the following to our LibProfileTokenStorage.sol file:</p><pre>  ...<br>  ...<br><br>  struct FacetAddressPositionAndFunctionSelectors{<br>    bytes4[] functionSelectors;<br>    uint256 facetAddressPosition;<br>  }<br><br><br>  ///// CUSTOM ERRORS /////  // new<br>  error AccountExistsError(address caller);<br><br><br>  ///// EVENTS /////  // new<br>  event AccountRegisteredEvent(string message);<br><br><br>  ///// STATE VARIABLES FOR DIAMOND STORAGE //////  // new<br>  struct Account{<br>    address accountAddress;<br>    string displayName;<br>    string bio;<br>  }<br><br><br>  struct DiamondStorage {<br>    mapping(bytes4 =&gt; FacetAddressAndFunctionSelectorPosition) selectorToFacetAddressAndFunctionSelectorPosition;<br>    mapping(address =&gt; FacetAddressPositionAndFunctionSelectors) addressToFacetAddressPositionAndFunctionSelectors;<br>    address[] facetAddresses;<br>    address contractOwner;<br><br>    // new<br>    mapping(address =&gt; Account) account;<br>    mapping(address =&gt; bool) isAccountRegistered;<br>  }</pre><p>Here, we define a custom error to prevent creating accounts with duplicate addresses. We also define an event that is to be emitted once registration is successful. And in our diamond storage struct, we have two mappings; one that returns an account struct from an address, and another that returns a boolean value if there is an existing account.</p><p>On our ProfileV1.sol facet:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity 0.8.30;<br><br>import {LibProfileTokenStorage as LibPTS} from &quot;../libraries/LibProfileTokenStorage.sol&quot;;<br><br>contract ProfileV1 {<br>  <br>  function createProfile(string memory _displayName, string memory _bio) public {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(!ds.isAccountRegistered[msg.sender], LibPTS.AccountExistsError(msg.sender));<br>    ds.account[msg.sender] = LibPTS.Account(msg.sender, _displayName, _bio);<br>    ds.isAccountRegistered[msg.sender] = true;<br>    emit LibPTS.AccountRegisteredEvent(&quot;Profile created&quot;);<br>  }<br><br>}</pre><p>Here, we imported our storage library to access all its properties. Before any operation, we call our diamondStorage() function to access the storage of our diamond storage struct.</p><p>For now, we have a createProfile() function where we have a validation check to make sure that an account has a unique address before creation, and we emit an event upon successful registration.</p><p>Setting up our token facet, let’s make some minor changes to our storage library, LibProfileTokenStorage.sol.</p><pre>  ...<br>  ... <br>  error AccountExistsError(address caller);<br>  error AccountDoesNotExistError(address caller);<br>  error AuthorizationError(string message);<br>  error TokenRewardError(string message);<br><br><br>  ///// EVENTS /////<br>  event AccountRegisteredEvent(string message);<br><br>  struct Account{<br>    address accountAddress;<br>    string displayName;<br>    string bio;<br>  }<br><br>  struct RepToken {<br>    string name;<br>    string symbol;<br>    uint8 decimals;<br>    uint256 totalSupply;<br>  }<br><br><br>  struct DiamondStorage {<br>    mapping(bytes4 =&gt; FacetAddressAndFunctionSelectorPosition) selectorToFacetAddressAndFunctionSelectorPosition;<br>    mapping(address =&gt; FacetAddressPositionAndFunctionSelectors) addressToFacetAddressPositionAndFunctionSelectors;<br>    address[] facetAddresses;<br>    address contractOwner;<br><br>    mapping(address =&gt; Account) account;<br>    mapping(address =&gt; bool) isAccountRegistered;<br><br>    // new<br>    RepToken repToken;<br>    mapping(address =&gt; uint256) repBalance;<br>  }<br><br><br>  ...<br>  ...<br>  function initializeRepToken() internal {<br>    DiamondStorage storage ds = diamondStorage();<br>    require(bytes(ds.repToken.name).length == 0, &quot;LibPTS: Reputation Token already initialized&quot;);<br>    ds.repToken.name = &quot;Reputation Token&quot;;<br>    ds.repToken.symbol = &quot;REP&quot;;<br>    ds.repToken.decimals = 2;<br>    ds.repToken.totalSupply = 0;<br>  }</pre><p>Here, we define the attributes of our RepToken, where name is the name of our token, symbol is our token symbol, decimals to represent divisibility.</p><p>With decimals = 2, all REP amounts are stored as integers representing hundredths. So minting 100 means the user receives 1.00 REP , 50 meaning 0.50 REP . The totalSupply starts at zero and grows as REP gets minted across the system. We then add this definition to the storage struct, with a mapping that represents that balance for every address. We also define a function that initializes our token with values for its attributes.</p><p>Since initializeRepToken should only ever be called once and only by the contract owner, we expose it through the diamond proxy with an ownership guard rather than leaving it directly accessible.</p><pre>...<br>...<br>function initializeRepToken() public onlyOwner{<br>  LibProfileTokenStorage.initializeRepToken();<br>}</pre><p>With this in place, we define our Token.sol contract:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity 0.8.30;<br><br>import {LibProfileTokenStorage as LibPTS} from &quot;../libraries/LibProfileTokenStorage.sol&quot;;<br><br><br>contract Token {<br><br>  modifier onlyOwner(){<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(msg.sender == ds.contractOwner, LibPTS.AuthorizationError(&quot;Not contract owner&quot;));<br>    _;<br>  }<br><br>  function incrementTotalSupply(uint256 _amount) public onlyOwner returns (uint256) {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    ds.repToken.totalSupply += _amount * (10 ** ds.repToken.decimals);<br>    ds.repBalance[msg.sender] += _amount * (10 ** ds.repToken.decimals);<br>    return ds.repToken.totalSupply;<br>  }<br><br><br>  function readBalance() public view returns (uint256) {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    if(msg.sender != ds.contractOwner){<br>      require(ds.isAccountRegistered[msg.sender], LibPTS.AccountDoesNotExistError(msg.sender));<br>    }<br>    return ds.repBalance[msg.sender];<br>  }<br><br><br>  function initialRegistrationReward(address _newUser)public {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(msg.sender == address(this),  LibPTS.TokenRewardError(&quot;Token: only callable via diamond&quot;));<br><br>    require(ds.isAccountRegistered[_newUser], LibPTS.AccountDoesNotExistError(_newUser));<br>    require(ds.repBalance[_newUser] == 0, LibPTS.TokenRewardError(&quot;Token already rewarded to user upon registration&quot;));<br>    require(ds.repBalance[ds.contractOwner] &gt; 0, LibPTS.TokenRewardError(&quot;Invalid token balance of contract owner&quot;));<br><br>    uint256 amountReward = 1 * (10 ** ds.repToken.decimals);<br>    ds.repBalance[ds.contractOwner] -= amountReward;<br>    ds.repBalance[_newUser] += amountReward;<br>  }<br>}</pre><p>In this contract, we have a few sets of functions:</p><ul><li>incrementTotalSupply with the authorization guard, is used by the contract owner to mint new REP tokens with the amount provided. This also increments the balance of the contract owner.</li><li>readBalance reads the token balance of the current sender.</li><li>initialRegistrationReward is designed to reward a new user with 1 REP upon successful registration. This will later be called in the createProfile function of the ProfileV1 facet.</li></ul><p>With an update to our ProfileV1.sol facet, we have:</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity 0.8.30;<br><br>import {LibProfileTokenStorage as LibPTS} from &quot;../libraries/LibProfileTokenStorage.sol&quot;;<br><br>contract ProfileV1 {<br><br>  // new<br>  function tokenFacetRegistrationReward(address _newUser) public {<br>    (bool success, ) = address(this).call(<br>      abi.encodeWithSignature(&quot;initialRegistrationReward(address)&quot;, _newUser)<br>    );<br>    require(success, LibPTS.TokenRewardError(&quot;Token reward upon registration failed&quot;));<br>  }<br>  <br>  function createProfile(string memory _displayName, string memory _bio) public {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(!ds.isAccountRegistered[msg.sender], LibPTS.AccountExistsError(msg.sender));<br>    ds.account[msg.sender] = LibPTS.Account(msg.sender, _displayName, _bio);<br>    ds.isAccountRegistered[msg.sender] = true;<br><br>    // new<br>    tokenFacetRegistrationReward(msg.sender);<br>    emit LibPTS.AccountRegisteredEvent(&quot;Profile created&quot;);<br>  }<br><br>}</pre><p>Notice how the ProfileV1 facet didn’t import the Token facet. Instead, address(this) which refers to the diamond proxy address is used. So, because both facets are registered to the diamond, it is simply routing the call to the facet that owns the initialRegistrationReward function, which will then be called in the createProfile function after a successful registration to reward the new user.</p><p>For the moment of truth… (<em>drumroll</em>)</p><p>We will now deploy our contracts. Irrespective of the Ethereum development framework used (Truffle, Hardhat, Foundry), we’d first deploy our facets, take note of their addresses and respective function selectors, and insert them in the deployment script of our diamond proxy, before deploying it. I will be demonstrating that with Hardhat and ethers.js.</p><p>Writing deployment scripts for ProfileV1 and Token facets, we have:</p><pre>// profile.v1.facet.deploy.ts<br><br>import &quot;@nomiclabs/hardhat-ethers&quot;;<br>import hre from &quot;hardhat&quot;;<br><br>async function deployProfileV1Facet() {<br><br>  const ProfileV1 = await hre.ethers.getContractFactory(&quot;ProfileV1&quot;);<br>  const profileV1 = await ProfileV1.deploy();<br><br>  console.log(&quot;ProfileV1 Facet address: &quot;, await profileV1.getAddress())<br>}<br><br><br>deployProfileV1Facet()<br> .then(() =&gt; process.exit(0))<br> .catch(error =&gt; {<br>   console.error(error)<br>   process.exit(1)<br>})</pre><pre>// token.facet.deploy.ts<br><br>import &quot;@nomiclabs/hardhat-ethers&quot;;<br>import hre from &quot;hardhat&quot;;<br><br>async function deployTokenFacet(){<br>  const Token = await hre.ethers.getContractFactory(&quot;Token&quot;);<br>  const token = await Token.deploy();<br><br>  console.log(&quot;Token Facet address: &quot;, await token.getAddress())<br>}<br><br>deployTokenFacet()<br> .then(() =&gt; process.exit(0))<br> .catch(error =&gt; {<br>  console.error(error)<br>  process.exit(1)<br>})</pre><p>To easily retrieve the function selectors for our facets, we will need to compile our code and obtain the Application Binary Interface (ABI). We do this using the command:</p><pre>npx hardhat compile</pre><p>Then we deploy facets with their scripts by running the commands:</p><pre>npx hardhat run --network localhost scripts/profile.v1.facet.deploy.ts<br>npx hardhat run --network localhost scripts/token.facet.deploy.ts</pre><p>You may get addresses looking like these:</p><pre>ProfileV1 Facet address:  0x5FbDB2315678afecb367f032d93F642f64180aa3<br><br>Token Facet address:  0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512</pre><p>With our facets deployed locally, we can retrieve their function selectors using the following script:</p><pre>import { ethers } from &quot;ethers&quot;;<br>import { profile_v1_facet_abi } from &quot;../abis/profile.v1.facet.abi&quot;;<br>import { token_facet_abi } from &quot;../abis/token.facet.abi&quot;;<br><br>const dotenv = require(&quot;dotenv&quot;);<br>dotenv.config();<br><br><br>async function getProfileV1FacetSelectors() {<br>  const facetAddress = &quot;0x5FbDB2315678afecb367f032d93F642f64180aa3&quot;;<br>  const iFace = new ethers.Interface(profile_v1_facet_abi);<br><br>  const selectors: { [key: string]: string } = {};<br>  const selectorsBytes: string[] = [];<br><br>  iFace.fragments.forEach((fragment) =&gt; {<br>    if (ethers.FunctionFragment.isFunction(fragment)) {<br>      selectors[fragment.name] = fragment.selector;<br>      selectorsBytes.push(fragment.selector);<br>    }<br>  });<br><br>  console.log(&quot; &quot;)<br>  console.log(&quot;Profile V1 Facet Details &quot;);<br>  console.log(&quot;Profile V1 Facet Address: &quot;, facetAddress);<br>  console.log(&quot;Function Names to Selectors: &quot;, selectors);<br>  console.log(&quot;Function Selectors: &quot;, selectorsBytes);<br>}<br><br><br>async function getTokenFacetSelectors() {<br>  const facetAddress = &quot;0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512&quot;;<br>  const iFace = new ethers.Interface(token_facet_abi);<br><br>  const selectors: { [key: string]: string } = {};<br>  const selectorsBytes: string[] = [];<br><br>  iFace.fragments.forEach((fragment) =&gt; {<br>    if (ethers.FunctionFragment.isFunction(fragment)) {<br>      selectors[fragment.name] = fragment.selector;<br>      selectorsBytes.push(fragment.selector);<br>    }<br>  });<br><br>  console.log(&quot; &quot;)<br>  console.log(&quot;Token Facet Details &quot;);<br>  console.log(&quot;Token Facet Address: &quot;, facetAddress);<br>  console.log(&quot;Function Names to Selectors: &quot;, selectors);<br>  console.log(&quot;Function Selectors: &quot;, selectorsBytes);<br>}<br><br><br>getProfileV1FacetSelectors();<br>getTokenFacetSelectors();</pre><p>Running it with the command:</p><pre>npx ts-node scripts/facet.selectors.extract.ts</pre><p>We will get a response that looks like:</p><pre>Profile V1 Facet Details <br>Profile V1 Facet Address:  0x5FbDB2315678afecb367f032d93F642f64180aa3<br>Function Names to Selectors:  {<br>  createProfile: &#39;0xba1feb8a&#39;,<br>  tokenFacetRegistrationReward: &#39;0xd77df923&#39;<br>}<br>Function Selectors:  [ &#39;0xba1feb8a&#39;, &#39;0xd77df923&#39; ]<br> <br>Token Facet Details <br>Token Facet Address:  0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512<br>Function Names to Selectors:  {<br>  incrementTotalSupply: &#39;0xd5dbe634&#39;,<br>  initialRegistrationReward: &#39;0x5078cd0f&#39;,<br>  readBalance: &#39;0x69a28006&#39;<br>}<br>Function Selectors:  [ &#39;0xd5dbe634&#39;, &#39;0x5078cd0f&#39;, &#39;0x69a28006&#39; ]</pre><p>Now we have the remaining pieces to deploy our diamond. Recall that we will need to provide a list of facet cuts, along with an address that serves as the contract owner upon deployment, as specified here:</p><pre><br>constructor(IDiamondCut.FacetCut[] memory _diamondCut, DiamondArgs memory _args) payable {<br>  LibProfileTokenStorage.diamondCut(_diamondCut, address(0), new bytes(0));<br>  LibProfileTokenStorage.setContractOwner(_args.owner);<br>}</pre><p>Next, we compile our diamond to get its ABI, and define our diamond’s deployment script:</p><pre>import &quot;@nomiclabs/hardhat-ethers&quot;;<br>import hre from &quot;hardhat&quot;;<br><br><br>async function deployDiamond(){<br><br>  const accounts = await hre.ethers.getSigners();<br>  const contractOwner = accounts[0];<br><br>  const profileV1FacetCut = {<br>    facetAddress: &quot;0x5FbDB2315678afecb367f032d93F642f64180aa3&quot;,<br>    action: 0,<br>    functionSelectors: [ &#39;0xba1feb8a&#39;, &#39;0xd77df923&#39; ]<br>  }<br><br>  const tokenFacetCut = {<br>    facetAddress: &quot;0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512&quot;,<br>    action: 0,<br>    functionSelectors:  [ &#39;0xd5dbe634&#39;, &#39;0x5078cd0f&#39;, &#39;0x69a28006&#39; ]<br>  }<br><br>  const facetCutList = [<br>    profileV1FacetCut, <br>    tokenFacetCut<br>  ]<br><br>  const diamondArgs = {<br>    owner: contractOwner.address,<br>  }<br><br>  const ProfileTokenDiamond = await hre.ethers.getContractFactory(&quot;ProfileTokenDiamond&quot;)<br>  const profileTokenDiamond = await ProfileTokenDiamond.deploy(facetCutList, diamondArgs)<br>  await profileTokenDiamond.waitForDeployment()<br>  console.log(&quot;ProfileTokenDiamond address: &quot;, await profileTokenDiamond.getAddress())<br>  console.log(&quot;ProfileTokenDiamond owner: &quot;, contractOwner.address)<br>}<br><br><br>deployDiamond()<br>  .then(() =&gt; process.exit(0))<br>  .catch((error) =&gt; {<br>    console.error(error);<br>    process.exit(1);<br>  })</pre><p>We run the command:</p><pre>npx hardhat run --network localhost scripts/diamond.deploy.ts</pre><p>And we should get a response that looks like this:</p><pre>ProfileTokenDiamond address:  0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0<br>ProfileTokenDiamond owner:  0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266</pre><p>After deployment, we’d have to write an ethers.js script to help interact with our contracts. Actions we want to try out are:</p><ul><li>Getting the current contract owner</li><li>Initializing our REP token as the contract owner</li><li>Increment total token supply as contract owner</li><li>Create a profile as a user</li><li>Reading our token balance as a user</li></ul><pre>// ethers.interact.ts<br><br>import { ethers } from &quot;ethers&quot;;<br>import { profile_v1_facet_abi } from &quot;../abis/profile.v1.facet.abi&quot;;<br>import { token_facet_abi } from &quot;../abis/token.facet.abi&quot;;<br>import { diamond_abi } from &quot;../abis/diamond.abi&quot;;<br><br>const dotenv = require(&quot;dotenv&quot;);<br>dotenv.config();<br><br>const providerUrl = process.env.PROVIDER_URL || &quot;http://localhost:8545&quot;;<br>const provider = new ethers.JsonRpcProvider(providerUrl);<br><br><br>const combinedAbi = [...profile_v1_facet_abi, ...token_facet_abi, ...diamond_abi];<br><br>const diamondAddress = &quot;0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0&quot;<br><br>const ownerHardhatPrivateKey = &quot;0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80&quot; // private key for account #0<br>const ownerWallet = new ethers.Wallet(ownerHardhatPrivateKey, provider)<br>const ownerContractConnection = new ethers.Contract(diamondAddress, combinedAbi, ownerWallet)<br><br><br>const dummyUserPrivateKey = &quot;0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d&quot; // private key for account #1<br>const dummyUserWallet = new ethers.Wallet(dummyUserPrivateKey, provider)<br>const dummyUserContractConnection = new ethers.Contract(diamondAddress, combinedAbi, dummyUserWallet)<br><br><br>async function getOwner() {<br>  try {<br>    const response = await ownerContractConnection.getCurrentOwner();<br>    console.log(&quot;Contract owner: &quot;, response);<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      } <br>  }<br>}<br><br><br>async function initializeRepToken(){<br>  try {<br>    await ownerContractConnection.initializeRepToken();<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      } <br>  }<br>}<br><br><br>async function incrementTotalSupply(wallet:ethers.Wallet, tokenAmount: number){<br>  try {<br>    const iFace = new ethers.Interface(combinedAbi)<br>    const data = iFace.encodeFunctionData(&quot;incrementTotalSupply&quot;, [tokenAmount])<br>    const txOption = {<br>      to: diamondAddress,<br>      data: data,<br>    }<br>    const txResponse = await wallet.sendTransaction(txOption)<br>    await txResponse.wait()<br>    console.log(`Total supply incremented by ${tokenAmount} tokens`)<br>    const decodedResponse = iFace.decodeFunctionResult(&quot;incrementTotalSupply&quot;, txResponse.data)<br>    console.log(&quot;Total Supply: &quot;, Number(decodedResponse[0]))<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      }<br>  }<br>}<br><br><br>async function createProfile(wallet: ethers.Wallet, contractConnection: ethers.Contract, displayName: string, bio: string) {<br>  try {<br>    const iFace = new ethers.Interface(combinedAbi)<br>    const data = iFace.encodeFunctionData(&quot;createProfile&quot;, [displayName, bio])<br>    const txOption = {<br>      to: diamondAddress,<br>      data: data,<br>    }<br>    const txResponse = await wallet.sendTransaction(txOption)<br>    await txResponse.wait()<br>    contractConnection.once(&quot;AccountRegisteredEvent&quot;, (message: string)=&gt;{<br>      console.log(&quot;Event emitted: &quot;, message)<br>    })<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      } <br>  }<br>}<br><br><br>async function readBalance(wallet: ethers.Wallet) {<br>  try {<br>    const iFace = new ethers.Interface(combinedAbi)<br>    const data = iFace.encodeFunctionData(&quot;readBalance&quot;)<br>    const txOption = {<br>      to: diamondAddress,<br>      data: data,<br>    }<br>    const response = await wallet.call(txOption)<br>    const decodedResponse = iFace.decodeFunctionResult(&quot;readBalance&quot;, response)<br>    console.log(&quot;Balance: &quot;, Number(decodedResponse[0]))<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      }<br>  }<br>}<br><br>// getOwner()<br>// initializeRepToken()<br>// incrementTotalSupply(ownerWallet, 1000)<br>// incrementTotalSupply(dummyUserWallet, 500)<br>// createProfile(dummyUserWallet, dummyUserContractConnection, &quot;Prince Igwe&quot;, &quot;Software Engineer&quot;)<br>// readBalance(dummyUserWallet)<br>// readBalance(ownerWallet)</pre><p>After uncommenting the initialRepToken function and running the script, if you tried to incrementTotalSupply of REP token as a normal user address, you’d see an error message looking like:</p><pre>Error: Onchain error -  AuthorizationError(Not contract owner)</pre><p>You should know what this means.</p><p>Now increment the token total supply and read the balance as a contract owner, and you should see a response looking like:</p><pre>Balance:  100000</pre><p>This means 1000.00 tokens. Remember our 2decimals in REPtoken initialization? Yeah.</p><p>After creating our dummy profile and reading our balance, you should see our balance of:</p><pre>Balance:  100</pre><p>While our local node is still running, here is a run-through of how we can update our facets to read a profile with a ProfileV2.sol facet.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity 0.8.30;<br><br>import {LibProfileTokenStorage as LibPTS} from &quot;../libraries/LibProfileTokenStorage.sol&quot;;<br><br>contract ProfileV2 {<br><br>  function tokenFacetRegistrationReward(address _newUser) public {<br>    (bool success, ) = address(this).call(<br>      abi.encodeWithSignature(&quot;initialRegistrationReward(address)&quot;, _newUser)<br>    );<br>    require(success, LibPTS.TokenRewardError(&quot;Token reward upon registration failed&quot;));<br>  }<br>  <br>  function createProfile(string memory _displayName, string memory _bio) public {<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(!ds.isAccountRegistered[msg.sender], LibPTS.AccountExistsError(msg.sender));<br>    ds.account[msg.sender] = LibPTS.Account(msg.sender, _displayName, _bio);<br>    ds.isAccountRegistered[msg.sender] = true;<br><br>    tokenFacetRegistrationReward(msg.sender);<br>    emit LibPTS.AccountRegisteredEvent(&quot;Profile created&quot;);<br>  }<br><br>  function readProfile() public view returns (LibPTS.Account memory _account){<br>    LibPTS.DiamondStorage storage ds = LibPTS.diamondStorage();<br>    require(ds.isAccountRegistered[msg.sender], LibPTS.AccountDoesNotExistError(msg.sender));<br>    _account = ds.account[msg.sender];<br>  }<br><br>}</pre><p>Compile it and retrieve its ABI:</p><pre>npx hardhat compile</pre><p>Define a deployment script and deploy:</p><pre>// profile.v2.facet.deploy.ts<br><br>import &quot;@nomiclabs/hardhat-ethers&quot;;<br>import hre from &quot;hardhat&quot;;<br><br>async function deployProfileV2Facet() {<br><br>  const ProfileV2 = await hre.ethers.getContractFactory(&quot;ProfileV2&quot;);<br>  const profileV2 = await ProfileV2.deploy();<br><br>  console.log(&quot;ProfileV2 Facet address: &quot;, await profileV2.getAddress())<br>}<br><br><br>deployProfileV2Facet()<br>  .then(() =&gt; process.exit(0))<br>  .catch(error =&gt; {<br>    console.error(error)<br>    process.exit(1)<br>  })</pre><p>You should see an address looking like:</p><pre>ProfileV2 Facet address:  0x5FC8d32690cc91D4c39d9d3abcBD16989F875707</pre><p>Update the facet.selectors.extract.ts file:</p><pre>// import { profile_v1_facet_abi } from &quot;../abis/profile.v1.facet.abi&quot;; // commented<br>import { profile_v2_facet_abi } from &quot;../abis/profile.v2.facet.abi&quot;;<br><br>...<br>...<br><br>async function getProfileV2FacetSelectors() {<br>  const facetAddress = &quot;0x5FC8d32690cc91D4c39d9d3abcBD16989F875707&quot;;<br>  const iFace = new ethers.Interface(profile_v2_facet_abi);<br><br>  const selectors: { [key: string]: string } = {};<br>  const selectorsBytes: string[] = [];<br><br>  iFace.fragments.forEach((fragment) =&gt; {<br>    if (ethers.FunctionFragment.isFunction(fragment)) {<br>      selectors[fragment.name] = fragment.selector;<br>      selectorsBytes.push(fragment.selector);<br>    }<br>  });<br><br>  console.log(&quot; &quot;)<br>  console.log(&quot;Profile V2 Facet Details &quot;);<br>  console.log(&quot;Profile V2 Facet Address: &quot;, facetAddress);<br>  console.log(&quot;Function Names to Selectors: &quot;, selectors);<br>  console.log(&quot;Function Selectors: &quot;, selectorsBytes);<br>}<br><br><br>getProfileV2FacetSelectors();<br>// getTokenFacetSelectors();</pre><p>We should get a response looking like:</p><pre>Profile V2 Facet Details <br>Profile V2 Facet Address:  0x5FC8d32690cc91D4c39d9d3abcBD16989F875707<br>Function Names to Selectors:  {<br>  createProfile: &#39;0xba1feb8a&#39;,<br>  readProfile: &#39;0x22bb93fe&#39;,<br>  tokenFacetRegistrationReward: &#39;0xd77df923&#39;<br>}<br>Function Selectors:  [ &#39;0xba1feb8a&#39;, &#39;0x22bb93fe&#39;, &#39;0xd77df923&#39; ]</pre><p>Since ProfileV2 introduces a new function readProfile, we can&#39;t use the Replace action; that&#39;s reserved for updating logic when the function signatures stay the same. Instead, we Remove ProfileV1 and Add ProfileV2 as a new facet. With the way the FacetCut function was designed, you only have to pass in the function selectors of the facet to be removed, together with a zero address. The setup would know which facet owns the function selectors.</p><pre>// ethers.interact.ts<br><br>...<br>...<br><br><br>async function removeProfileV1Facet( facetAddress: string, functionSelectors: string[]) {<br>  try {<br>    const facetCut = [<br>      {<br>        facetAddress: facetAddress,<br>        action: 2, // remove facet<br>        functionSelectors: functionSelectors,<br>      },<br>    ];<br>    const response = await ownerContractConnection.diamondCut(facetCut)<br>    await response.wait()<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      }<br>  }<br>}<br><br><br><br>async function addProfileV2Facet( facetAddress: string, functionSelectors: string[]) {<br>  try {<br>    const facetCut = [<br>        {<br>        facetAddress: facetAddress,<br>        action: 0, // add facet<br>        functionSelectors: functionSelectors,<br>      },<br>    ];<br>    const response = await ownerContractConnection.diamondCut(facetCut);<br>    await response.wait();<br>    ownerContractConnection.once(&quot;DiamondCutEvent&quot;, (facetCuts, initAddress, initCalldata) =&gt; {<br>      console.log(&quot;DiamondCut event emitted: &quot;, { facetCuts, initAddress, initCalldata });<br>    })<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      }<br>  }<br>}<br><br><br>async function getDiamondFacets(){<br>  try {<br>    const response = await ownerContractConnection.facets();<br>    console.log(&quot;Facets: &quot;, response);<br>  } catch (error: any) {<br>    const iFace = new ethers.Interface(combinedAbi)<br>    const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>    if (errorData) {<br>      const decodedError = iFace.parseError(errorData)<br>      throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>    }<br>  }<br>}<br><br>...<br>...<br><br>const profileV2FacetAddress = &quot;0x5FC8d32690cc91D4c39d9d3abcBD16989F875707&quot;<br>const profileV2FacetFunctionSelectors = [ &#39;0xba1feb8a&#39;, &#39;0x22bb93fe&#39;, &#39;0xd77df923&#39; ]<br><br>const facetToRemove = ethers.ZeroAddress<br>const profileV1FacetFunctionSelectors = [ &#39;0xba1feb8a&#39;, &#39;0xd77df923&#39; ]<br><br><br>// removeProfileV1Facet(facetToRemove, profileV1FacetFunctionSelectors)<br>// addProfileV2Facet(profileV2FacetAddress, profileV2FacetFunctionSelectors)<br>// getDiamondFacets()<br></pre><p>Call the commented function calls sequentially, and you should see the updated facet in the response.</p><pre>Facets:  Result(2) [<br>  Result(2) [<br>    &#39;0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512&#39;,<br>    Result(3) [ &#39;0xd5dbe634&#39;, &#39;0x5078cd0f&#39;, &#39;0x69a28006&#39; ]<br>  ],<br>  Result(2) [<br>    &#39;0x5FC8d32690cc91D4c39d9d3abcBD16989F875707&#39;,<br>    Result(3) [ &#39;0xba1feb8a&#39;, &#39;0x22bb93fe&#39;, &#39;0xd77df923&#39; ]<br>  ]<br>]</pre><p>Update your ethers.interact.ts to include the following:</p><pre>import { profile_v2_facet_abi } from &quot;../abis/profile.v2.facet.abi&quot;;<br>...<br>...<br><br>const combinedAbi = [...profile_v2_facet_abi, ...token_facet_abi, ...diamond_abi];<br><br>...<br>...<br><br>async function readProfile(wallet: ethers.Wallet) {<br>  try {<br>    const iFace = new ethers.Interface(combinedAbi)<br>    const data = iFace.encodeFunctionData(&quot;readProfile&quot;)<br>    const txOption = {<br>      to: diamondAddress,<br>      data: data,<br>    }<br>    const response = await wallet.call(txOption)<br>    const decodedResponse = iFace.decodeFunctionResult(&quot;readProfile&quot;, response)<br>    console.log(&quot;Decoded response: &quot;, decodedResponse)<br>  } catch (error: any) {<br>      const iFace = new ethers.Interface(combinedAbi)<br>      const errorData = error?.data ?? error?.error?.data ?? error?.info?.error?.data<br><br>      if (errorData) {<br>        const decodedError = iFace.parseError(errorData)<br>        throw new Error(`Onchain error -  ${decodedError?.name}(${decodedError?.args?.join(&#39;, &#39;)})`)<br>      } else {<br>        console.error(error)<br>      }<br>  }<br>}<br><br>...<br>// createProfile(dummyUserWallet, dummyUserContractConnection, &quot;Prince Igwe&quot;, &quot;Software Engineer&quot;)<br>readProfile(dummyUserWallet)<br>// readBalance(dummyUserWallet)<br>...<br></pre><p>Run the script, and you should see a response like:</p><pre>Decoded response:  Result(1) [<br>  Result(3) [<br>    &#39;0x70997970C51812dc3A010C7d01b50e0d17dc79C8&#39;,<br>    &#39;Prince Igwe&#39;,<br>    &#39;Software Engineer&#39;<br>  ]<br>]</pre><p><em>We started with a problem - smart contracts are immutable, one implementation contract isn’t enough, and the 24kb limit is real. The diamond pattern solves all three, and now you’ve seen it in practice.</em></p><p><em>A profile facet. A token facet. A shared storage library. An upgrade that changed the logic without touching the address or losing the data. That’s it. That’s the whole thing.</em></p><p><em>Nick Mudge’s articles got me here. Hopefully, this one gets you a little further.</em></p><h3>REFERENCES</h3><ul><li><a href="https://eip2535diamonds.substack.com/p/introduction-to-the-diamond-standard">Introduction to the Diamond Standard, EIP-2535 Diamonds</a></li><li><a href="https://eip2535diamonds.substack.com/p/example-of-a-diamond-upgrade">Example of Adding New State Variables in Diamond Upgrade</a></li><li><a href="https://dev.to/mudgen/why-loupe-functions-for-diamonds-1kc3">Diamond Loupe Functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de58ad014287" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Responsible AI: Behind the Scenes of Vina, a Mental Health AI Agent.]]></title>
            <link>https://princeigwe.medium.com/designing-responsible-ai-behind-the-scenes-of-vina-a-mental-health-ai-agent-e7d8dfa4b457?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7d8dfa4b457</guid>
            <category><![CDATA[digital-health]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 09:41:40 GMT</pubDate>
            <atom:updated>2025-10-20T09:41:40.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*l-SODr0UL0bE7BwSnXV7aQ.jpeg" /></figure><p><em>We live in a world where millions feel unheard. Not everyone needs therapy. Sometimes, they just need someone to listen.</em></p><p>Imagine being able to always count on someone to help you with whatever you&#39;re thinking about, including emotional stress. In a real-life situation, this can be difficult to find, and even if you did, they might not be in the right frame of mind to truly listen. Everybody experiences life in a different way. This is one reason why people decide to own pets—for emotional support and companionship, while some turn to chatbots like ChatGPT and Meta AI.</p><p><em>Let’s backtrack a bit…</em></p><p>2025—the rise of AI agents, and they didn’t rise without hype. From handing software engineering processes over to agents, to CEOs automating their human team out of their companies, with some regretting their decisions later on. LOL.</p><p>AI technology, specifically narrow AI, has always piqued my interest, and this initially drew me to the domains of data science and machine learning. But let&#39;s not discuss my less-than-ideal experience, shall we? However, a new kind of AI called <strong>Gen AI</strong> has emerged in recent years, and initially, this only involved users interacting via text with ChatGPT, Claude, and similar platforms. Not so much to work with. 2025 came with the concept of AI agents—a facelift for Generative AI—and with it came agent frameworks including AutoGen, CrewAI, Google Vertex, Amazon Bedrock, LangChain, etc.</p><p>With all the news trends of this new shiny tech, I wasn’t really buying into it. You may ask why. Well, I’ve seen what hype looks like during the time of the Bored Ape NFT craze. Never in my life have I seen anything that rose to fame and faded out within a very short period of time. At the time of writing, each NFT currently has a price tag of at least 6 ETH on OpenSea, but I see no real value in those things. That’s a story for another day.</p><p>I started out not liking this idea of an AI agent; however, after several references brought by friends and coworkers, you can say that I decided to explore. Google the meaning of AI agents, and you’d see a response that looks like “AI agents are autonomous systems that execute tasks based on inputs from their environments with little to no human interaction.” As weird as it may seem, I simply saw them as large language models with access to limbs (blocks of external functional code), where the LLM is obviously the brain of the system. You see, LLMs really can’t do much as standalone programs. They are almost very limited with the data they were trained with, which can be outdated, and without being grounded in the real world, they can produce responses that are inaccurate, irrelevant, unethical, or make little logical sense. The best solution to this may not really be to add more training data to extend their reasoning capacity, but to give it access to tools and data that fit our needs. That is where agent frameworks come in, which help to build out AI agents.</p><p><em>Settling with LangChain, I began writing little blocks of code from tutorials in order to see how this concept works. In the midst of that, an idea came to me…</em></p><p>I’m a software engineer who is interested in building for any industry, and the healthcare industry has always stood out to me. The integration of computing technologies in this industry created terms like “digital health,” “health tech,” etc. I’m also guilty of having ChatGPT as my therapist, but I decided to do something a little bit different. And so I built a mental health “AI companion.”</p><p><a href="https://github.com/Vina-Ops/vina">https://github.com/Vina-Ops/vina</a></p><p><em>Building Vina…</em></p><p>After multiple search queries on “how to build conversational AI,” finding conversational datasets was not an easy task. Cleaning them to fit my requirements was a different ball game. I wrote different data cleaning scripts for them to align. Having a Retrieval Augmented Generation (RAG) workflow is almost a key component of any agentic AI system, and building with LangChain, this started out by loading my cleaned datasets as documents. In your own case, this may be data from files, webpages, videos, etc.</p><pre>from langchain_community.document_loaders import DirectoryLoader, JSONLoader<br>from langchain_text_splitters import RecursiveJsonSplitter<br><br># loading all .jsonl files in the datasets directory, and using the loader class of JSONLoader to load each file<br>DRIVE_FOLDER = &quot;llm_workflows/datasets/&quot;<br>loader = DirectoryLoader(<br>  DRIVE_FOLDER, <br>  glob=&quot;**/*.jsonl&quot;, <br>  loader_cls=JSONLoader,<br>  loader_kwargs={<br>        &quot;jq_schema&quot;: &quot;.&quot;, <br>        &quot;text_content&quot;: False,<br>        &quot;json_lines&quot;: True<br>  }<br>)<br>docs = loader.load()<br><br>splitter = RecursiveJsonSplitter(max_chunk_size=1000)</pre><p>The next processes after this included recursive document splitting, which simply breaks down documents into smaller chunks while maintaining contextual meaning between each chunk, along with vector embeddings and storage.</p><p>Consider the following scenario: You were developing a recommendation engine for an API feature, which required choosing a collection of data objects that were comparable to the object in question. Building this out with a relational database like PostgreSQL may not be the best approach. Of course, you may decide to work with hashtags (#), but in a case where you are working with unstructured data like videos, music, and pictures, this will not hold. This is where vector stores and embeddings come in.</p><p>An embedding is a numerical representation of data that captures semantic meaning. This eases the hassle of working with a variety of unstructured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*Bj0lS1dpv_2M-WtIOW8eug.png" /><figcaption>Embedding</figcaption></figure><p>Based on the format of the data, there are various embedding models available for embedding. After this process, this is where vector stores and indexes come in handy. I went with the <a href="https://www.pinecone.io/">Pinecone</a> vector database system because their documentation was easy to follow, and they offered a free plan.</p><p>Because of the verbosity of the cleaned conversational dataset, which was in a JSON format, I had an issue with loading it as a document into LangChain. And so I converted them into JSONL format for smooth processing. However, this made it impossible to use the RecursiveJsonSplitter class, even though you’ll still see it in the code, but I wrote a custom splitter code.</p><p>While initializing the vector index, I defined the metric parameter to cosine to enable a cosine-similarity machine-learning algorithm upon vector retrieval.</p><pre># embedding_conversations.py<br><br>pc = Pinecone(api_key=PINECONE_API_KEY)<br><br>index_name = &quot;vina-index&quot;<br>existing_indexes = [index_info[&quot;name&quot;] for index_info in pc.list_indexes()]<br><br>if index_name not in existing_indexes:<br>  pc.create_index(<br>    name=index_name,<br>    dimension=1024,<br>    metric=&quot;cosine&quot;,<br>    spec=ServerlessSpec(cloud=&quot;aws&quot;, region=&quot;us-east-1&quot;))<br>  while not pc.describe_index(index_name).status[&quot;ready&quot;]:<br>    time.sleep(1)<br><br>index = pc.Index(index_name)</pre><p>You can find it in the repo.</p><p>With RecursiveCharacterTextSplitter splitter class from LangChain, and Mistral AI’s embedding model — mistral-embed , I was able to split my mental health-related documents, transform them along with the JSONL files into vector embeddings, and store them in my vector database vina-index index.</p><pre># vector_store_embedding.py<br><br>import os<br>from langchain_pinecone import PineconeVectorStore<br>from pinecone import Pinecone<br>from langchain_mistralai import MistralAIEmbeddings<br><br>from dotenv import load_dotenv<br>load_dotenv(override=True)<br><br>##* this solved the error: Could not download mistral tokenizer from <br>##* Huggingface for calculating batch sizes. Set a Huggingface token <br>##* via the HF_TOKEN environment variable to download the real tokenizer.<br>HF_TOKEN=os.environ.get(&quot;HF_TOKEN&quot;)<br>os.environ[&quot;HF_TOKEN&quot;] = HF_TOKEN<br><br>MISTRAL_KEY=os.environ.get(&quot;MISTRAL_KEY&quot;)<br>PINECONE_API_KEY=os.environ.get(&quot;PINECONE_API_KEY&quot;)<br><br><br><br>embeddings = MistralAIEmbeddings(<br>  model=&quot;mistral-embed&quot;, # mistral ai embedding model<br>  api_key=MISTRAL_KEY,<br>  max_retries=2<br>)<br><br>pc = Pinecone(api_key=PINECONE_API_KEY)<br><br>index_name = &quot;vina-index&quot;<br>index = pc.Index(index_name)<br>vector_store = PineconeVectorStore(index=index, embedding=embeddings)</pre><pre># embedding_pdf_articles.py<br><br>import logging<br>from uuid import uuid4<br>from llm_workflows.vector_store_embedding import vector_store<br>from llm_workflows.documents import document_pdf_articles<br><br>splitted_docs = document_pdf_articles.splitted_docs<br><br>uuids = [str(uuid4()) for _ in range(len(splitted_docs))]<br><br>def vector_embed_pdf_faqs():<br>  logging.info(&quot;LLM Workflow: Embedding splitted PDF documents...&quot;)<br>  vector_store.add_documents(documents=splitted_docs, ids=uuids)<br>  logging.info(&quot;LLM Workflow: PDF documents embedded successfully&quot;)<br><br>vector_embed_pdf_faqs()</pre><p>After setting up Vina’s RAG system, the following code was written to test it out.</p><pre># dummy_retrieval_conversations.py<br><br>import os<br>from langchain_pinecone import PineconeVectorStore<br>from langchain_core.messages import HumanMessage<br>from langchain_core.prompts import ChatPromptTemplate<br>from llm_workflows.llm import llm<br><br>from dotenv import load_dotenv<br>load_dotenv(override=True)<br><br>embeddings = MistralAIEmbeddings(<br>  model=&quot;mistral-embed&quot;, # mistral ai embedding model<br>  api_key=MISTRAL_KEY,<br>  max_retries=2<br>)<br><br>pc = Pinecone(api_key=PINECONE_API_KEY)<br><br>index_name = &quot;vina-index&quot;<br>index = pc.Index(index_name)<br>vector_store = PineconeVectorStore(index=index, embedding=embeddings)<br><br>human_prompt = &quot;I&#39;m depressed and I don&#39;t know what to do. Can you help me?&quot;<br>human_msg = HumanMessage(human_prompt)<br><br>results = vector_store.similarity_search(human_prompt, k=1)<br><br>result_contents = [result.page_content for result in results]<br><br>formatted_prompt = ChatPromptTemplate.from_template(<br>  &quot;You are a empathetic companion. You are also funny, loving and caring. &quot; \<br>  &quot;Answer the {query} based on the {context} provided.&quot;\<br>  &quot;Always be empathetic and avoid giving clinical diagnoses.&quot;\<br>  &quot;Refrain from speculating if you are unsure, and simply admit that you do not know.&quot;<br>  )<br><br>chain = formatted_prompt | llm<br><br>ai_response = chain.invoke({&quot;context&quot;:result_contents, &quot;query&quot;: human_msg})<br>print(ai_response.content)</pre><p>In LangChain, a chain is a sequence of calls — whether to an LLM, an agent tool, or any data processing steps. You can liken this to Python’s pipe operator ( | ), where information is passed from one process to another.</p><p>From the snippet above, I defined a chain which starts with a prompt on how the LLM should respond to a query- human_prompt . Based on the information (context), it could be used as an answer to the query. This “context” was a retrieved document that was most similar to the human_prompt . This prompt was then passed on to the LLM for AI inference.</p><p><em>Multi-Agent Orchestration: LangGraph…</em></p><p>Initially, I thought of building Vina using the single-agent pattern, but then I faced a contextual issue about it keeping up with our chat history. I would give it chat A , but then after 3 or 4 to/fro chats, it wouldn’t remember anything about chat A . I realized LangGraph helped with this issue, and even offered more. With LangGraph, one can break down a task into subtasks to be distributed among agents according to their area of specialization. Still on this, state data can be passed around agents, thereby making room for context engineering — an engineering approach that manages all the information an AI model needs to work with.</p><p>Working with LangGraph, a <strong>state graph</strong> should be defined. A state graph is a collection of <strong>nodes or agents </strong>that collaborate with an LLM to work on a variety of tasks. These nodes can communicate with each other with the help of <strong>edges</strong>. With this in place, the data received from outside the application can be modified to fit the requirements of each agent. This data is known as a <strong>state </strong>with the data structure of a dictionary.</p><pre># vina_state.py<br><br>from typing import Annotated, TypedDict<br><br>from langchain_core.messages import HumanMessage, AnyMessage<br>from langgraph.checkpoint.memory import MemorySaver<br>from langgraph.graph import StateGraph, START, END, add_messages<br><br>from llm_workflows.llm import llm<br><br>class State(TypedDict):<br>  user_id: str<br>  messages: Annotated[list[AnyMessage], add_messages] <br>  query: str <br>  iteration_count: int<br>  dominant_emotional_state: str<br>  mental_cognitive_pattern: str<br>  intent: str<br>  classifier_context: str<br>  safety_crisis_resource: str<br>  contact_therapist_approval: str<br><br><br>class ConfigSchema(TypedDict):<br>  msg: str<br><br># initializing a state graph<br>state_workflow = StateGraph(State, config_schema=ConfigSchema)<br><br><br>def safety_intent_classifier(state: State):<br>  msg = config[&quot;configurable&quot;].get(&quot;msg&quot;)<br>  ...<br>  ...<br>  return {<br>    &quot;query&quot;: msg,<br>    &quot;dominant_emotional_state&quot;: json_parsed_response[&quot;dominant_emotional_state&quot;],<br>    &quot;mental_cognitive_pattern&quot;: json_parsed_response[&quot;mental_cognitive_pattern&quot;],<br>    &quot;intent&quot;: json_parsed_response[&quot;intent&quot;],<br>    &quot;classifier_context&quot;: json_parsed_response[&quot;classifier_context&quot;]<br>  }<br><br><br># definition of other nodes<br>...<br>...<br><br><br>state_workflow.add_node(&quot;safety_intent_classifier&quot;, safety_intent_classifier)<br>state_workflow.add_node(&quot;safety_crisis_resource_search&quot;, safety_crisis_resource_search)<br><br>state_workflow.add_edge(START, &quot;safety_intent_classifier&quot;)<br>state_workflow.add_edge(&quot;safety_crisis_resource_search&quot;, &quot;passive_self_harm_companion&quot;)<br><br>...<br>...</pre><p>The above snippet is a dummy representation of Vina’s state graph, as the actual graph would make this article overly lengthy.</p><p>After this process, I configured a LangChain’s PostgreSQL checkpointer to help with state persistence, thereby solving the contextual issue I mentioned earlier.</p><pre># vina_state.py<br><br>...<br>from psycopg_pool import AsyncConnectionPool<br>from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver<br>...<br><br>async def state_run(human_msg: str, user_thread_id: str):<br>  try:<br>    ...<br>    connection_pool = AsyncConnectionPool(<br>      conninfo=DATABASE_URL,<br>      max_size=30,<br>      kwargs=connection_kwargs<br>    )<br>    await connection_pool.open()<br>    checkpointer = AsyncPostgresSaver(connection_pool)<br>    await checkpointer.setup()<br><br>    graph = state_workflow.compile(checkpointer=checkpointer)<br>    user_configuration = {<br>      &quot;configurable&quot;: {&quot;thread_id&quot;: user_thread_id, &quot;msg&quot;: human_msg},<br>      &quot;callbacks&quot;: [langfuse_handler]<br>    }<br><br>      ...<br>      ...<br><br>      state_messages = await graph.ainvoke({&quot;messages&quot;: [human_msg], &quot;user_id&quot;: user_thread_id}, user_configuration)<br>    <br>    return state_messages<br><br>  finally:<br>    await connection_pool.close()<br></pre><p>A lot was involved in building Vina’s multi-agent system, but I won’t go into details. Things were going well, but eventually I preferred to interact with Vina through an API rather than the CLI.</p><p><em>FastAPI…</em></p><p>If you’ve followed my previous articles before reading this one, you’ll realize that I work well with Django. However, I decided to follow a different route with FastAPI. The reason is that Django is an opinionated framework, and testing new waters with agentic AI, I wanted to be as flexible as possible. Aside from that, with Django’s built-in batteries, it already felt like an overload with Vina’s workflow. The minimalistic nature of FastAPI made it ideal for serving Vina’s real-time AI interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*Xf8SuOI1CAKTopZooxkp2w.png" /><figcaption>Layered Architecture</figcaption></figure><p>After setting up the backend service with FastAPI, I created an abstraction class to serve as the entry point into Vina’s multi-agent system. This was instantiated in Vina’s AI websocket connection endpoint. For authorization and privacy, chat messages were encrypted before storage, and the user’s ID was used as a parameter for Vina to maintain the contextual meaning of chats among various users.</p><p>Learning about the dangers of prompt injection and the need for protection of personal identifiable information (PII), I integrated guardrails into Vina’s layered architecture with <a href="https://www.lakera.ai/lakera-guard">Lakera Guard</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*AA2pWdZOgpt8AfKroOiguQ.png" /><figcaption>Updated Layered Architecture</figcaption></figure><p>For every input to the agent system, each input was validated before entering the agent system, and blocked out if found to be inappropriate in the context of mental health.</p><pre># ai.py<br><br>...<br>...<br>from llm_workflows.guard import input_evaluation<br>...<br><br>class AI():<br>  async def invoke(self, human_msg: str, user_thread_id: str):<br>    is_safe = input_evaluation(human_msg) # checking if prompt is safe with the guardrail<br>    if is_safe == False:<br>      guard_prompt = PromptTemplate.from_template(template=guard_template)<br>      formatted_guard_prompt = guard_prompt.format_prompt()<br>      guard_response = retry_llm_call(llm, formatted_guard_prompt)<br>      logging.info(f&quot;guard flag raised: {guard_response}&quot;)<br>      return guard_response.content<br>    else:<br>      state_messages = await state_run(human_msg, user_thread_id)<br>      ...</pre><p>One may ask, “You built a chatbot, what’s unique about it?”. Yeah, well, an agentic system is not really complete without agent tools, and a human in the loop, is it?</p><p><em>Human-In-The-Loop…</em></p><p>AI agents are autonomous in nature. This means that when given a task, they see to it that it is completed with almost no interruption. However, there are moments when human decision-making is important in their operation. This is the importance of the Human-In-The-Loop design pattern. Agents are interrupted to accept human decision, and based on it, they know the next set of actions to take.</p><p>Implementing this was quite tricky, as I wanted to design this within a single point of communication. One of the interesting abilities of Vina is real-time therapist escalation, where the intelligent detection of crisis language (e.g., suicidal ideation) triggers a human-in-the-loop interrupt, allowing the user to accept or reject connecting with a human therapist.</p><p>To accomplish this, the coordinator agent — safety_intent_classifier would parse the intent of the human message for signs of active crisis or suicidal risk. If there were any such case, the agent would transmit the message to the active_crisis_companion agent. This agent would, in turn, call the therapists_node tool node, which fetches registered therapists from the database with an API endpoint.</p><p>The data retrieved is redirected to the contact_therapist_human_approval agent, which creates an interrupt to be used to display the retrieved therapists&#39; data while waiting for the decision to go ahead with a therapist. If the user decides on a therapist, the contact_human_therapist agent is called, which in turn fetches the details of the selected therapist and creates a chat space between both parties with the help of the fetch_therapist_node and create_therapy_chat_room_node tool nodes.</p><p>Combining AI-driven operations<strong> </strong>with human oversight was a very important part of Vina’s design. This concept bridges the gap between automation and human judgment, ensuring that technology supports rather than replaces human care.</p><p>With Vina, I learned that the future of AI in healthcare depends not on how autonomous our agents become, but on how responsibly we build them.</p><p><em>Peace…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d8dfa4b457" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smart Relationships: A Practical Guide to Neo4j with Django.]]></title>
            <link>https://princeigwe.medium.com/building-smart-relationships-a-practical-guide-to-neo4j-with-django-cd5f178c0aa9?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd5f178c0aa9</guid>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[graph-database]]></category>
            <category><![CDATA[data-driven]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 10:00:51 GMT</pubDate>
            <atom:updated>2025-03-21T10:00:51.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vEvvqwQG4XL_sITgW1z5g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">NASA</a> on <a href="https://unsplash.com/photos/photo-of-outer-space-Q1p7bh3SHj8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Data is everywhere; it’s all around us. And sometimes we see these data in the form of numbers and statistics—statistics that show us what has happened and what hasn&#39;t. Examples can include finding the number of houses in an area and how many houses are occupied. These types of statistics can be important for a real estate company, or for a pharmaceutical company: the stock taken for medicinal products, which would have details like the types of drugs gotten, the types and number of drugs bought by patients, and the number of drugs that are still in store.</p><p>This form of data is important in any type of organization. However, this type of data only shows us the results of actions, and not really the actions. Let’s say you own a mini food stand that has a few items like 10 loaves of bread, 6 cans of sardines, 3 bottles of fruit juice, 4 water bottles, and a tuber of yam. And then you have 3 loyal customers who come to you every two days, and at the end of the day, you are left with 2 loaves of bread, 3 cans of sardines, and 2 bottles of water. Yes, your customers bought those items, and you stated that down in your sales record, but who bought what? This is the action I’m referring to. For a mini-business like yours, it can be easy to tell, but what if you secured a large area of space for your business and ran it online? Can you tell?</p><p>Knowing who bought what or who did what can give an insight into what your customers need or prefer. Now you will no longer be acting on just results but on <strong>relationships</strong>. What relationship does this person have with this item? This way, as a business owner, you can come up with assumptions on what they may like, thereby promoting your business. For example, if I bought eggs, sugar, flour, and butter, it is okay to assume that I’m a baker, and you would like to let me know that you also sell baking powder.</p><p>Now, as a software engineer, it can be difficult to represent this type of relationship with a relational database, especially if there are different varieties of relationships. This is where graph databases come into the picture. As its name suggests, a graph database is a database that stores graphs. It is as simple as that.</p><p><strong><em>Okay, so what is a graph?</em></strong></p><p>A graph (no, not your line graph or bar chart or anything similar) is a data structure that shows the relationship between two or more entities, represented as nodes, with edges as the relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*c1wthyPLO0SZFgMs2Y-7nQ.png" /><figcaption>A Graph</figcaption></figure><p>These nodes can represent anything ranging from a person to an animal, an object, or a place. These nodes and edges can also carry attributes that give more details about the graph. This type of graph is called the <strong>property graph, </strong>as it displays the meaning of relationships between entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*yh47xDUEZSClQ5KTkhzJeA.png" /><figcaption>Property Graph</figcaption></figure><p>Here, we see 3 nodes are connected together. However, we have an understanding of what is going on here, as edges are directed from one node of attributes to another. We see that Alex, aged 56, has been married to 54-year-old Sonia since 1989 and gave birth to Esther, an 18-year-old lady.</p><p>Taking things one step further, we move into <strong>knowledge graphs</strong>. These are property graphs that are designed for a specific domain (usually related to business) in order to make sense of organizational or business data within that domain. Such domains can include:</p><ul><li>Fintech</li><li>Social media</li><li>E-commerce</li><li>Healthcare and Life Sciences</li></ul><p>Going into the nitty-gritty of how these domains benefit from knowledge graphs is outside the scope of this article. However, one popular type of application that is built on these graphs is a recommendation engine. Moving forward, we will be learning how to build an API on a graph database. Popular examples of graph database management systems include AWS Neptune, Dgraph, and Neo4j. For this article, we will be working with Neo4j.</p><p><strong><em>Neo4j…</em></strong></p><p>Just like we have different database management systems for different types, Neo4j is a database management system for the graph database type, and it was created by Neo4j, Inc. You can learn more about it <a href="https://neo4j.com/">here</a>.</p><p>One interesting thing to know is that Neo4j provides its own query language. Just as we have SQL for writing relational database queries on PostgreSQL and MySQL database management systems, Neo4j has “Cypher”, which allows you to create, read, update, and delete nodes and relationships in the system.</p><p>Here are some graph operations with Cypher:</p><pre>CREATE (person:Person{name:&quot;Prince Igwe&quot;, gender:&quot;Male&quot;, age:53}) RETURN peson;</pre><p>This query creates a node of the class, Person, with the attributes name , gender, and age , and returns the node.</p><pre>MATCH (person:Person{name:&quot;Prince Igwe&quot;}) RETURN person;</pre><p>The above query searches for a node of the class, Person, using “Prince Igwe” as a name identifier, and returns the node.</p><p>Here is an example of creating relationships between nodes:</p><pre>CREATE (person:Person{name:&quot;John Doe&quot;, gender:&quot;Male&quot;})-[loves:LOVES]-&gt;(food:Food{name:&quot;Chicken&quot;, size: &quot;Large&quot;}) RETURN person,loves,food;</pre><p>Here is another example of updating a node:</p><pre>MATCH (person:Person{name:&quot;Prince Igwe&quot;}) SET person.age=45 RETURN person;</pre><p>With the above query, a person node is fetched with the name identifier, and the age value of the person is updated using the SET keyword. To delete this node, we can replace the RETURN keyword with DELETE .</p><pre>MATCH (person:Person{name:&quot;Prince Igwe&quot;}) DELETE person;</pre><p>In cases where we would want to delete a node that already has one or more relationships with other nodes, the DETACH DELETE keywords help. First, the node is detached from all relationships before it is deleted.</p><p>To fetch all relationships in the database, we can have a query looking like this:</p><pre>MATCH(x)-[y]-&gt;(z) RETURN x,y,z;</pre><p>This will return all nodes that are connected to other nodes in the database.</p><p>Okay, enough with the query examples. How do we apply this Graph DBMS in a Django application? Well… as a chronic music lover, we will be building a mini-music streaming API to demonstrate this. This API will show music producers and artists dropping albums, and other users liking songs from the album. Let’s get down with it.</p><p><strong><em>Demo…</em></strong></p><p>Neo4j, Inc. provides AuraDB, a cloud-based database platform you can work with. To use this platform for this guide, you will need to create an account.</p><p><a href="https://neo4j.com/product/auradb/">https://neo4j.com/product/auradb/</a></p><p>However, to tinker around things locally, you can start by installing Neo4j directly on your computer. Or if you are like me, you can use the Neo4j Docker image provided <a href="https://hub.docker.com/_/neo4j">here.</a> We will be working with the Docker image, and you can clone the GitHub repo for this article <a href="https://github.com/Princeigwe/spotify-lite">here</a>.</p><p>On your terminal, create a project directory called “spotify-lite”, call the directory you just created, and create a virtual environment for the codebase.</p><pre>mkdir spotify-lite<br>cd spotify-lite<br>virtualenv env<br>source env/bin/activate</pre><p>Next, install Django and Django Rest Framework:</p><pre>pip install django djangorestframework</pre><p>Creating a Django project in our current directory, we run the command:</p><pre>django-admin startproject core .</pre><p>You should see a directory named “core” in the spotify-lite filesystem. As usual, to make sure you are starting on the right track, run the commands:</p><pre>python manage.py migrate<br>python manage.py runserver</pre><p>You should get a response looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*y0PaExMtILU_UM4y4_z9mQ.png" /><figcaption>Django runserver response</figcaption></figure><p>After this, create a Django app with the name “api”. This is where we will be building our mini-music streaming API.</p><pre>python manage.py startapp api</pre><p>We will also need to install a package called django-neomodel , a Django plugin for Neo4j’s Neo-Model Object Graph Mapper (OGM). This OGM allows you to interact with a Neo4j graph database without solely depending on Cypher queries. In other words, just as Django has its own built-in ORM for relational databases, you can also interact with a Neo4j graph database with Python classes.</p><p>Run the commands:</p><pre>pip install django_neomodel<br>pip freeze &gt; requirements.txt</pre><p>Up next, we will build a Docker image of our Django project, where we will be able to interact with the Neo4j Docker container, as both containers will be managed by docker-compose.</p><p>In the root directory of our project, create a Dockerfile containing the following:</p><pre><br>FROM python:3.11<br>ENV PYTHONDONTWRITEBYTECODE=1<br>ENV PYTHONUNBUFFERED=1<br><br><br>WORKDIR /code<br><br>COPY requirements.txt /code/<br>RUN pip install -r requirements.txt<br>COPY . /code/<br><br><br>EXPOSE 8000<br><br>CMD [&quot;python3&quot;, &quot;manage.py&quot;, &quot;runserver&quot;, &quot;0.0.0.0:8000&quot;]</pre><p>Create a compose.yml with its content looking like this:</p><pre>version: &#39;3&#39;<br><br>services:<br>  <br>  neo4j-aura-db:<br>    container_name: neo4j-aura-db<br>    image: neo4j:latest<br>    volumes:<br>      - ./neo4j/data:/data<br>      - ./neo4j/logs:/logs<br>      - ./neo4j/plugins:/plugins<br>      - ./neo4j/conf:/conf<br>    environment:<br>      NEO4J_AUTH: neo4j/${NEO_4J_AURA_DB_PASSWORD}<br>      dbms.connector.bolt.listen_address: 0.0.0.0:7687<br>    ports:<br>      - &quot;7474:7474&quot;<br>      - &quot;7687:7687&quot;<br>    restart: always<br><br>  <br>  api-service:<br>    build:<br>      context: .<br>    container_name: api-service<br>    restart: on-failure<br>    env_file:<br>      - .env<br>    develop:<br>      watch:<br>        - action: sync<br>          path: .<br>          target: /code/<br>    volumes: <br>      - .:/code<br>    ports:<br>      - 8000:8000</pre><p>Also, don’t forget to add 0.0.0.0 to the list of ALLOWED_HOSTS in the settings.py file.</p><pre>ALLOWED_HOSTS = [&quot;0.0.0.0&quot;]</pre><p>Run the following commands; they should build your local Docker image and pull the Neo4j Docker image from DockerHub:</p><pre>docker compose build ; docker compose up</pre><p>To test out if you successfully have a Neo4j container running, go to the link “<a href="http://127.0.0.1:7474/">http://127.0.0.1:7474</a>&quot; on your browser, and you should see an environment looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*ONwAxqDThEF1bv-FgyFuUw.png" /><figcaption>Neo4j AuraDB environment</figcaption></figure><p>Edit your settings.py file to include the following configuration:</p><pre>import os<br>from neomodel import config<br><br>...<br>...<br><br>NEO_4J_AURA_DB_PASSWORD = os.environ.get(&#39;NEO_4J_AURA_DB_PASSWORD&#39;)<br>NEO_4J_AURA_DB_HOST = os.environ.get(&#39;NEO_4J_AURA_DB_HOST&#39;)<br><br>config.DATABASE_URL = f&#39;bolt://neo4j:{NEO_4J_AURA_DB_PASSWORD}@{NEO_4J_AURA_DB_HOST}&#39;<br><br>...<br>...<br><br>INSTALLED_APPS = [<br>    ...<br>    ...<br><br>    # local apps<br>    &#39;api.apps.ApiConfig&#39;,<br><br>    #3rd party apps<br>    &#39;django_neomodel&#39;,<br>]</pre><p>Here, we connect to a Neo4j database instance with the hostNEO_4J_AURA_DB_HOST, with an immutable username as “neo4j”, and password, NEO_4J_DB_PASSWORD. In this case, our NEO_4J_AURA_DB_HOST is our Neo4j Docker container. So in your .env, you should have variables looking like this:</p><pre>NEO_4J_AURA_DB_PASSWORD=admin-password<br>NEO_4J_AURA_DB_HOST=neo4j-aura-db</pre><p>Also, remember to create a api/urls.py file and register it in the core/urls.py file:</p><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;api/&#39;, include(&#39;api.urls&#39;))<br>]</pre><p>Now, let’s define some nodes and relationships. In a music streaming API, we have entities including album, producer/artist, track, genre, and customer, with relationships looking like:</p><ul><li>(producer)-[PRODUCED]-&gt;(album)</li><li>(album)-[HAS_TRACK]-&gt;(track)</li><li>(producer/artist)-[COLLABOED_WITH]-&gt;(artist)</li><li>(artist)-[SANG_IN]-&gt;(track)</li><li>(customer)-[LIKED]-&gt;(track)</li><li>(genre)-[HAS_TRACK]-&gt;(track)</li></ul><p>In your api/models.py file, include the following code... take your time:</p><pre><br>import neomodel<br>import datetime<br>import pytz<br><br><br>class Genre(neomodel.StructuredNode):<br>    name = neomodel.StringProperty(unique_index=True, required=True)<br><br>    has_track = neomodel.RelationshipTo(&#39;Track&#39;, &#39;HAS_TRACK&#39;)<br><br>class Artist(neomodel.StructuredNode):<br>    name = neomodel.StringProperty(unique_index=True, required=True)<br>    age = neomodel.IntegerProperty()<br>    is_producer = neomodel.BooleanProperty(default=False)<br>    place_of_birth = neomodel.StringProperty()<br>    website = neomodel.StringProperty()<br>    followers = neomodel.IntegerProperty()<br><br>    produced = neomodel.RelationshipTo(&#39;Album&#39;, &#39;PRODUCED&#39;)<br>    collaboed_with = neomodel.RelationshipTo(&#39;Artist&#39;, &#39;COLLABOED_WITH&#39;)<br>    sang_in = neomodel.RelationshipTo(&#39;Track&#39;, &#39;SANG_IN&#39;)<br><br><br>class Album(neomodel.StructuredNode):<br>    name = neomodel.StringProperty(unique_index=True, required=True)<br>    release_date = neomodel.DateTimeProperty(default=lambda: datetime.datetime.now(pytz.utc), index=True)<br>    cover_art = neomodel.StringProperty()<br><br>    has_track = neomodel.RelationshipTo(&#39;Track&#39;, &#39;HAS_TRACK&#39;)<br><br><br>class Track(neomodel.StructuredNode):<br>    title = neomodel.StringProperty(unique_index=True, required=True)<br>    length = neomodel.IntegerProperty()<br><br><br>class Customer(neomodel.StructuredNode):<br>    name = neomodel.StringProperty(unique_index=True, required=True)<br>    age = neomodel.IntegerProperty()<br>    email = neomodel.StringProperty()<br><br>    liked = neomodel.RelationshipTo(&#39;Track&#39;, &#39;LIKED&#39;)<br><br></pre><p>Okay… So, in the above code, we see that we defined nodes with different attributes, with relationships defined using the RelationshipTo(&#39;x&#39;, &#39;y&#39;) property, where ‘x’ is the node class the current node will be connected to, and ‘y’ is the label of the relationship.</p><p>Create a api/serializers.py file for our nodes’ serializer classes, which will be used to validate request bodies on our endpoints.</p><pre>#api/serializers.py<br><br>from rest_framework import serializers<br>from .models import Genre, Artist, Album, Track, Customer<br><br>class GenreSerializer(serializers.Serializer):<br>  name = serializers.CharField(max_length=100)<br><br>  def create(self, validated_data):<br>    return Genre(**validated_data).save()<br><br>class ArtistSerializer(serializers.Serializer):<br>  name = serializers.CharField(max_length=100)<br>  age = serializers.IntegerField()<br>  is_producer = serializers.BooleanField()<br>  place_of_birth = serializers.CharField(max_length=100)<br>  website = serializers.URLField(max_length=100, required=False)<br>  followers = serializers.IntegerField(required=False)<br><br>  def create(self, validated_data):<br>    return Artist(**validated_data).save() # create and save Artist node with validated data<br><br>class AlbumReleaseSerializer(serializers.Serializer):<br>  name = serializers.CharField(max_length=100) <br>  release_date = serializers.DateTimeField()<br>  cover_art = serializers.URLField(max_length=100)<br>  producer_name = serializers.CharField(max_length=100)<br><br>  def create(self, validated_data):<br>    return Album(**validated_data).save() # create and save Album node with validated data<br><br><br>class AlbumTrackSerializer(serializers.Serializer):<br>  title = serializers.CharField(max_length=100)<br>  length = serializers.IntegerField(required=False)<br>  album_name = serializers.CharField(required=False)<br>  genre_name = serializers.CharField(required=False)<br><br>  def create(self, validated_data):<br>    return Track(**validated_data).save() # create and save Track node with validated data<br><br>class TrackSerializer(serializers.Serializer):<br>  title = serializers.CharField(max_length=100)<br>  length = serializers.IntegerField(max_value=4)<br>  producer_name = serializers.CharField(max_length=100)<br>  singer_name = serializers.CharField(max_length=100)<br>  album_name = serializers.CharField(max_length=100)<br>  genre_name = serializers.CharField(max_length=20)<br><br>  def create(self, validated_data):<br>    return Track(**validated_data).save()<br><br><br>class CustomerSerializer(serializers.Serializer):<br>  name = serializers.CharField(max_length=100)<br>  age = serializers.IntegerField()<br>  email = serializers.EmailField()<br><br>  def create(self, validated_data):<br>    return Customer(**validated_data).save() # create and save Customer node with validated data</pre><p>Focusing on areas with single-line comments, we simply create and save nodes with validated data that pertains to each node class. In other words, this means:</p><pre>Artist(name=name, age=age, is_producer=is_producer, place_of_birth=place_of_birth, website=website, followers=followers).save()<br>Album(name=name, release_date=release_date, cover_art=cover_art).save()<br>Track(title=title, length=length).save()<br>Customer(name=name, age=age, email=email).save()</pre><p>In your api/views.py file, create a GenreList class to inherit from the APIView class.</p><pre>#api/views.py<br><br>from django.shortcuts import render<br>from .models import Genre, Artist, Album, Track, Customer<br>from .serializers import GenreSerializer<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br><br><br><br>class GenreList(APIView):<br><br>  def get(self, request):<br>    genres = Genre.nodes.all()<br>    serializer = GenreSerializer(genres, many=True)<br>    return Response(serializer.data)<br>  <br>  def post(self, request):<br>    serializer = GenreSerializer(data=request.data)<br>    if serializer.is_valid():<br>      serializer.save()<br>      return Response(serializer.data, status=status.HTTP_201_CREATED)</pre><p>In your api/urls.py file, add a path for the POST and GET operations of the GenreList class.</p><pre>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>  path(&quot;genres/&quot;, views.GenreList.as_view())<br>]</pre><p>Test out our endpoint, and build and run your docker container with docker-compose. On your API client, send a POST request to the genres’ endpoint: “http://0.0.0.0:8000/api/genres/”, with the request body looking like:</p><pre>{<br>  &quot;name&quot;: &quot;EDM&quot;<br>}</pre><p>You should get the same data as a response. Login into your Docker’s neo4j database instance, and on your neo4j query field, write the Cypher query match(n) return n;and click the play button. This will return all the nodes you have created. So far, just one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf0SLhB4Eo_DmxIlR2dreg.png" /><figcaption>Fetching all nodes with Cypher</figcaption></figure><p>You should also get a list of nodes created with the same endpoint with GET action. Create two more genres, pop, and R&amp;B; you can create as many as you want. Next, we need artists and producers. We will create them with our ArtistList API class:</p><pre>from .serializers import GenreSerializer, ArtistSerializer #new<br>...<br>...<br><br>class ArtistList(APIView):<br>  <br>  def get(self, request):<br>    artists = Artist.nodes.all()<br>    serializer = ArtistSerializer(artists, many=True)<br>    return Response(serializer.data)<br>  <br>  def post(self, request):<br>    serializer = ArtistSerializer(data=request.data)<br>    if serializer.is_valid():<br>      serializer.save()<br>      return Response(serializer.data, status=status.HTTP_201_CREATED)<br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p>With our api/urls.py file including:</p><pre>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>  path(&quot;genres/&quot;, views.GenreList.as_view()),<br>  path(&quot;artists/&quot;, views.ArtistList.as_view()) #new<br>]</pre><p>Creating nodes to represent 3 of my favourite artists with the api/artists/ endpoint, with request bodies looking like this:</p><pre>{<br>  &quot;name&quot;: &quot;Chris Brown&quot;,<br>  &quot;age&quot;: 36,<br>  &quot;place_of_birth&quot;: &quot;Virginia, USA&quot;,<br>  &quot;is_producer&quot;: &quot;False&quot;<br>}<br><br><br>{<br>  &quot;name&quot;: &quot;Alan Walker&quot;,<br>  &quot;age&quot;: 27,<br>  &quot;place_of_birth&quot;: &quot;Northampton, England&quot;,<br>  &quot;is_producer&quot;: &quot;True&quot;,<br>  &quot;followers&quot;: 600000000<br>}<br><br><br>{<br>  &quot;name&quot;: &quot;Metro Boomin&quot;,<br>  &quot;age&quot;: 31,<br>  &quot;place_of_birth&quot;: &quot;Missouri, USA&quot;,<br>  &quot;is_producer&quot;: &quot;True&quot;,<br>  &quot;followers&quot;: 900000000<br>}</pre><p>Running the Cypher match(n) return n; query, you should see extra nodes displayed in your AuraDB environment. Next, we want our artists/producers to release albums and tracks.</p><p>To create our logic for producers to release albums, modify our api/views.py to include the following:</p><pre>from .serializers import GenreSerializer, ArtistSerializer, AlbumReleaseSerializer #new<br>from neomodel import DoesNotExist #new<br>...<br>...<br>class AlbumReleaseList(APIView):<br>  <br>  def get(self, request):<br>    albums = Album.nodes.all()<br>    serializer = AlbumReleaseSerializer(albums, many=True)<br>    return Response(serializer.data)<br>  <br>  def post(self, request):<br>    serializer = AlbumReleaseSerializer(data=request.data)<br>    if serializer.is_valid():<br>      try:<br>        serializer.save()<br>        artist = Artist.nodes.get(name=serializer.validated_data[&#39;producer_name&#39;])<br>        album = Album.nodes.get(name=serializer.validated_data[&#39;name&#39;])<br>        artist.produced.connect(album)<br>        return Response(serializer.data, status=status.HTTP_201_CREATED)<br>      except DoesNotExist as e:<br>        return Response({&quot;error&quot;: f&quot;{e}&quot;}, status=status.HTTP_404_NOT_FOUND)<br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p>Add an endpoint for the AlbumReleaseList view in your api/urls.py:</p><pre>from django.urls import path<br>from . import views<br><br>urlpatterns = [<br>  path(&quot;genres/&quot;, views.GenreList.as_view()),<br>  path(&quot;artists/&quot;, views.ArtistList.as_view()),<br>  path(&quot;albums/&quot;, views.AlbumReleaseList.as_view()) # new<br>]</pre><p>Send an HTTP POST request to the endpoint, with a request body looking like this:</p><pre>{<br>  &quot;name&quot;: &quot;Heroes and Villains&quot;,<br>  &quot;release_date&quot;: &quot;2022-10-06&quot;,<br>  &quot;cover_art&quot;: &quot;http://image.com&quot;,<br>  &quot;producer_name&quot;: &quot;Metro Boomin&quot;<br>}</pre><p>You should get the same data as a response. However, the magic happens when you execute the query, match(n)-[r]-&gt;(p) n,r,p; in your AuraDB environment. This query will fetch the nodes in relationships with other nodes.</p><p>You will get a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*AVZCnuddCWn-7HQDZMKFwg.png" /><figcaption>All relationships between producer and album nodes</figcaption></figure><p>Here our graph shows that Metro Boomin released the album, “Heroes and Villains”.</p><p>To spice things up, we will:</p><ul><li>Help Alan Walker release an album called “Different World”.</li><li>Assist Alan in releasing a track, “Faded,” with the EDM genre, under the album.</li><li>Help Metro collaborate with Chris Brown to release a track, “My First Track” (lol), under the “Heroes and Villains” album, with the R&amp;B genre. Don’t come after me. This also means that we have to give Chris credit for singing in the song.</li><li>Delete the “Faded” track.</li><li>Finally chill by editing the R&amp;B genre node to Rap, and editing the Tracknode with “My First Track” to “Superhero”.</li></ul><p>On the api/albums endpoint, send a POST request with the body:</p><pre>{<br>  &quot;name&quot;: &quot;Different World&quot;,<br>  &quot;release_date&quot;: &quot;2018-10-06&quot;,<br>  &quot;cover_art&quot;: &quot;http://image-aw.com&quot;,<br>  &quot;producer_name&quot;: &quot;Alan Walker&quot;<br>}</pre><p>This will create another Album node, with a relationship from Alan, in our graph. Next, we write the logic that connects an album to a track.</p><pre>#api/views.py<br><br>from .serializers import GenreSerializer, ArtistSerializer, AlbumReleaseSerializer, AlbumTrackSerializer #new<br>...<br>...<br><br>class AlbumTrackList(APIView):<br>  def get(self, request):<br>    tracks = Track.nodes.all()<br>    serializer = AlbumTrackSerializer(tracks, many=True)<br>    return Response(serializer.data)<br>  <br>  def post(self, request):<br>    serializer = AlbumTrackSerializer(data=request.data)<br>    if serializer.is_valid():<br>      try:<br>        serializer.save()<br>        album = Album.nodes.get(name=serializer.validated_data[&#39;album_name&#39;])<br>        genre = Genre.nodes.get(name=serializer.validated_data[&#39;genre_name&#39;])<br>        track = Track.nodes.get(title = serializer.validated_data[&#39;title&#39;])<br>        album.has_track.connect(track)<br>        genre.has_track.connect(track)<br>        return Response(serializer.data, status=status.HTTP_201_CREATED)<br>      except DoesNotExist as e:<br>        return Response({&quot;error&quot;: f&quot;{e}&quot;}, status=status.HTTP_404_NOT_FOUND)<br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><pre>#api/urls.py<br><br>...<br>...<br><br>urlpatterns = [<br>  path(&quot;genres/&quot;, views.GenreList.as_view()),<br>  path(&quot;artists/&quot;, views.ArtistList.as_view()),<br>  path(&quot;albums/&quot;, views.AlbumReleaseList.as_view()),<br>  path(&quot;albums/tracks/&quot;, views.AlbumTrackList.as_view()), #new<br>]</pre><p>Sending a POST request to the api/albums/tracks endpoint with the body:</p><pre>{<br>  &quot;title&quot;:&quot;Faded&quot;,<br>  &quot;length&quot;:2,<br>  &quot;album_name&quot;:&quot;Different World&quot;,<br>  &quot;genre_name&quot;:&quot;EDM&quot;<br>}</pre><p>We will have our graph showing all relationships that pertain to the “Faded” track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*peIEReS8yyS9ysI28NF-RA.png" /><figcaption>Relationship among nodes</figcaption></figure><p>Writing our logic where Chris sings his first track, we have:</p><pre>#api/views.py<br><br>from .serializers import GenreSerializer, ArtistSerializer, AlbumReleaseSerializer, AlbumTrackSerializer, TrackSerializer #new<br>...<br>...<br><br>class TrackList(APIView):<br>  def get(self, request):<br>    tracks = Track.nodes.all()<br>    serializer = TrackSerializer(tracks, many=True)<br>    return Response(serializer.data)<br>  <br>  def post(self, request):<br>    serializer = TrackSerializer(data=request.data)<br>    if serializer.is_valid():<br>      try:<br>        serializer.save()<br>        producer = Artist.nodes.get(name=serializer.validated_data[&#39;producer_name&#39;], is_producer=True)<br>        singer = Artist.nodes.get(name=serializer.validated_data[&#39;singer_name&#39;], is_producer=False)<br>        album = Album.nodes.get(name=serializer.validated_data[&#39;album_name&#39;])<br>        track = Track.nodes.get(title=serializer._validated_data[&#39;title&#39;])<br>        genre = Genre.nodes.get(name=serializer.validated_data[&#39;genre_name&#39;])<br><br>        album.has_track.connect(track)<br>        producer.collaboed_with.connect(singer)<br>        singer.sang_in.connect(track)<br>        genre.has_track.connect(track)<br>        return Response(serializer.data, status=status.HTTP_201_CREATED)<br>      except DoesNotExist as e:<br>        return Response({&quot;error&quot;: f&quot;{e}&quot;}, status=status.HTTP_404_NOT_FOUND)<br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p>After the request body is validated and the track is created, relationships between the album and track, producer and singer, singer and track, and genre and track, are created.</p><p>In our api/urls.py, we have:</p><pre>urlpatterns = [<br>  ...<br>  ...<br>  path(&quot;albums/tracks/&quot;, views.AlbumTrackList.as_view()),<br>  path(&quot;tracks/&quot;, views.TrackList.as_view()) #new<br>]</pre><p>Sending a POST request to the api/tracks endpoint, with the data:</p><pre>{<br>  &quot;title&quot;: &quot;My First Track&quot;,<br>  &quot;length&quot;: 3,<br>  &quot;producer_name&quot;: &quot;Metro Boomin&quot;,<br>  &quot;singer_name&quot;: &quot;Chris Brown&quot;,<br>  &quot;album_name&quot;: &quot;Heroes and Villains&quot;,<br>  &quot;genre_name&quot;: &quot;R&amp;B&quot;<br>}</pre><p>creates new relationships in our AuraDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*qYJwpeDuC5xgcIhpgR1R-g.png" /><figcaption>New relationships among nodes</figcaption></figure><p>So far, we have worked with Neomodel OGM classes. However, there may be cases where we want to execute Cypher queries in the code. Let’s say we wanted to delete Alan Walker’s “Faded” track, we could delete it with:</p><pre>track = Track.nodes.get(title=&quot;Faded&quot;)<br>track.delete()</pre><p>We could also have:</p><pre># api/views.py<br>class TrackView(APIView):<br>  def delete(self, request, title):<br>    query = &quot; MATCH (track: Track{ title: $title }) DETACH DELETE track; &quot;<br>    db.cypher_query(query=query, params={&quot;title&quot;:title} )<br>    return Response(status=status.HTTP_204_NO_CONTENT)</pre><p>We see that we can execute Cypher queries with the provided parameter variable.</p><pre># api/urls.py<br>urlpatterns = [<br>  ...<br>  ...<br>  path(&quot;tracks/&quot;, views.TrackList.as_view()),<br>  path(&quot;tracks/&lt;str:title&gt;&quot;, views.TrackView.as_view()) # new<br>]</pre><p>Sending a DELETE request to the URL api/tracks/Faded will delete the node, along with its relationships.</p><p>Writing the logic for our final task, we have:</p><pre># api/views.py<br><br>class GenreTrackView(APIView):<br>  def put(self, request, genre_name, title):<br>    serializer = AlbumTrackSerializer(data = request.data)<br>    if serializer.is_valid():<br>      try:<br>        genre = Genre.nodes.get(name=genre_name)<br>        genre.name = serializer.validated_data[&#39;genre_name&#39;]<br>        genre.save()<br><br>        track = Track.nodes.get(title=title)<br>        track.title = serializer.validated_data[&#39;title&#39;]<br>        track.save()<br>        return Response(serializer.data, status=status.HTTP_200_OK)<br>      except DoesNotExist as e:<br>        return Response({&quot;error&quot;: f&quot;{e}&quot;}, status=status.HTTP_404_NOT_FOUND)<br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p>Both nodes in question are fetched, edited, and saved on the graph database.</p><pre># api/urls.py<br><br>urlpatterns = [<br>  ...<br>  ...<br>  path(&quot;tracks/&lt;str:title&gt;&quot;, views.TrackView.as_view()),<br>  path(&quot;genres/&lt;str:genre_name&gt;/tracks/&lt;str:title&gt;&quot;, views.GenreTrackView.as_view()) # new<br>]</pre><p>Sending a PUT request to our endpoint looking like api/genres/R&amp;B/tracks/My First Track , with data looking like this:</p><pre>{<br>  &quot;title&quot;:&quot;Superhero&quot;,<br>  &quot;genre_name&quot;:&quot;Rap&quot;<br>}</pre><p>We will see the changes on our knowledge graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*IRU4OC29mnXu9PZm6j5Rhg.png" /><figcaption>Relationships among updated nodes</figcaption></figure><p><strong><em>In Conclusion…</em></strong></p><p>In this article, we explored how to model and manage complex relationships in Django using Neomodel, a powerful OGM for Neo4j. We walked through defining nodes and relationships, building serializers, and creating API endpoints to interact with our graph database.</p><p>By leveraging Neomodel’s intuitive syntax, we can efficiently handle interconnected data, making it an excellent choice for applications that rely on rich relationships, such as social networks, recommendation systems, and knowledge graphs.</p><p>To test your knowledge, consider adding a Cypher query that connects a Customer node that has a LIKED relationship to the “Superhero” track.</p><p>So, any time your Spotify DJ suggests hit or lovely tracks for you, it’s probably because there’s a recommendation engine built on the graph of your data.</p><p><em>Till we meet again, dear reader, keep building…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd5f178c0aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Event-Driven Architectures with Kafka, Django and Microservices-Part 2.]]></title>
            <link>https://princeigwe.medium.com/building-event-driven-architectures-with-kafka-django-and-microservices-part-2-fa9382309e28?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa9382309e28</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 09:58:29 GMT</pubDate>
            <atom:updated>2024-08-20T04:46:27.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQoDnz4G2lx5Q9uMwnK1TA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@artcoastdesign?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Dmitry Mashkin</a> on <a href="https://unsplash.com/photos/white-and-black-lego-blocks-NBzr3NUnxRg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In <a href="https://princeigwe.medium.com/building-event-driven-architectures-with-kafka-django-and-microservices-part-1-2b85501f5040">Part 1</a> of this series, we explored the role of Kafka producers in a Django-based microservices environment. We discussed how producers publish messages to Kafka topics, laying the groundwork for efficient event-driven communication between services.</p><p>Part 2 shifts our focus to Kafka consumers, the components responsible for receiving and processing these messages. As it was mentioned earlier, a consumer automatically receives these messages from the topic it subscribes to and acts on them according to its business logic. It is good to note that while one consumer subscribes to a topic, more consumers can be created to subscribe to the same topic to process event data with the same business logic. These consumers, acting as one, are known as a <strong>consumer group</strong>. To add to this, one consumer running alone can still be identified as a member of a consumer group.</p><p><strong>Question: Why do we need a consumer group?</strong></p><p>It is pretty much okay to have one consumer listen to and process events from a topic. However, having a consumer group helps balance the workload of receiving and processing events among consumers, ensuring that no single consumer is overwhelmed with the rate at which events are published.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wQBr0VLR3ZH_ABel5eyOQ.jpeg" /><figcaption>Load-balancing in a Consumer Group</figcaption></figure><p>A consumer group can be identified by a <strong>group ID.</strong> With this ID, we can know what group a consumer belongs to. During the course of the demo, we will see the importance of this ID.</p><p>Currently, not much work is done on our inventory microservice, as there’s very little user interaction here. However, a predefined inventory of food items is available. These are the same items with the same names as the ordered items from the previous microservice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrFN_wy1j5R3ezx9m1JsjA.png" /><figcaption>Food Inventory data records</figcaption></figure><p>How we configure the consumer depends on the importance of the message that it will be receiving. As an enterprise, every published message is very important. We want equality between the inventory table’squantity data and the physical quantity kept in actual storage; in other words, zero loss of event data is our top priority.</p><p>In a scenario where our inventory microservice is down but our orders service is still publishing messages, this would mean some messages would not be processed accordingly to update the food item inventory quantity data, even when the inventory microservice is restored. To resolve this issue, <strong>offsets</strong>, <strong>commits,</strong> and the consumer group ID all play important roles.</p><p>Think of offsets as page numbers in a book. Each number is attached to the writing on that page. That way, we can make quick reference to a piece of information without going through the whole book all over again. In this context, offsets are the page numbers for published messages to a topic.</p><p><strong>Commits</strong> are simply the process of the consumer keeping track of offsets. Let’s assume you were reading a novel, and for some reason, you stopped reading it for a while. By now, you will probably forget the last page you read, and when you get back to the book, you will most likely have a hard time finding where you left off. This is because you didn’t keep track of the page number. Keeping track may mean that you make a mark on the page or fold the page in some way, even though some people may consider this to be bad behaviour. Committing offsets ensures that when a consumer resumes reading (or consuming messages), it can pick up exactly where it left off without missing or repeating any data.</p><p>Configuring a consumer requires several arguments:</p><ul><li><strong>bootstrap servers: </strong>This argument holds the values of brokers’ connection strings, connecting the consumer to the Kafka cluster.</li><li><strong>key deserializer and value deserializer: </strong>These work in a manner opposite to key and value serializers. They take in byte arrays and convert them back to data structures.</li><li><strong>enable-auto-commit: </strong>We can manually commit an offset for a consumer, but with this argument set to true by default, the consumer’s offset is automatically committed at periodic intervals.</li><li><strong>group id: </strong>This is an optional property used to identify the consumer group that the consumer belongs to. If no group ID is given, offset commits are disabled for the consumer. In our case, we want this present.</li><li><strong>auto-commit-interval-ms: </strong>This is simply the number of milliseconds with which the consumer should periodically commit offsets. By default, this is set to 5000 ms, equivalent to 5 seconds. This can be set to a lower value, thereby committing offsets at a faster rate, resulting in a reduction in the loss of published messages.</li></ul><p>With our understanding of these arguments, we can now set up our consumer for our inventory microservice. We also install kafka-python :</p><pre>pip install kafka-python</pre><p>After this step, we set up things a little bit differently. Unlike the producer, which only publishes messages to the broker when the need arises, the consumer cannot operate in such manner. It must always listen for new messages, whether or not a new message is published. At the same time, it must continue with its existing processes. So this is like a task ratio of 1:2 between the producer and the consumer, respectively.</p><p>Knowing this, how do we ensure that the inventory service runs as a consumer while executing other processes? Although Django is a single-threaded framework by default, it is capable of multi-threading. This means that while it was originally designed to execute tasks in a single sequence, Python’s multi-threading capability enables it to execute multiple parts of a program at the same time. In other words, we can set up a consumer to run on a separate thread from the framework’s main thread.</p><p>You may wonder why a separate thread should be set up for the consumer. This is because running a consumer on the main thread blocks the process of running Django’s server. Once the consumer starts listening for messages, it will prevent the server from executing any other instructions, effectively halting the entire application. By running the consumer on a separate thread, we ensure that the server remains responsive and can continue to handle requests, while the consumer processes messages in the background without interference.</p><p>Configuring the consumer:</p><pre>## utils/kafka/consumer.py<br>from kafka import KafkaConsumer<br>import json<br>from utils.update_inventory import update_inventory<br>topics = [&#39;orders&#39;]<br>consumer = KafkaConsumer(bootstrap_servers=&quot;localhost:29092&quot;,<br>                        value_deserializer=lambda m: json.loads(m.decode(&#39;ascii&#39;)),<br>                        group_id=&quot;inventory_relation&quot;,<br>                        auto_commit_interval_ms=1000,<br>                        api_version=(2, 0, 0)<br>)<br>consumer.subscribe(topics)<br>while True:<br>  all_records = consumer.poll(timeout_ms=100, max_records=100)<br>  for topic_partition, messages in all_records.items():<br>    if topic_partition.topic == &quot;orders&quot;:<br>      update_inventory(messages)</pre><p>From the beginning, we see a list of Kafka topics that the consumer will subscribe to. For our demo, this list only contains the orders topic. Our consumer is configured to connect to our local Kafka broker with the bootstrap_servers argument. With the value_deserializer , our message values will be deserialized from byte arrays to Python objects. The consumer belongs to the consumer group having the group_id of inventory_relation . We then set the periodic auto commit interval time of the consumer to 1000 ms (1 second), and we make it subscribe to the Kafka topics.</p><p>While our consumer infinitely loops through subscribed topics, it polls each topic with a polling timeout of 100 ms (0.1 second), fetching a maximum of 100 records for every poll on that topic. The records of these topics are packaged into a dictionary and returned for processing. This dictionary has Kafka’s topic partitions for keys, and a list of messages for value for each topic partition.</p><p>For our business logic, we call a function update_inventory on every message that belongs to the orders topic. We see how this function is defined below:</p><pre>## utils/update_inventory.py<br>from inventories.models import FoodItemInventory<br>def update_inventory(messages):<br>  for message in messages:<br>      ordered_items = message.value<br>      <br>      for item in ordered_items:<br>        food_item = FoodItemInventory.objects.get(name=item[&#39;name&#39;])<br>        current_food_item_quantity = food_item.quantity<br>        new_food_item_quantity = current_food_item_quantity - item[&#39;quantity&#39;]<br>        food_item.quantity = new_food_item_quantity<br>        food_item.save()<br>        print(f&quot; Quantity of {food_item.name} has now reduced from {current_food_item_quantity} to {food_item.quantity}. &quot;)</pre><p>We can see that this function acts on a list of messages, and for each message, it acts on a list of items belonging to that message. For each item, a FoodItemInventory record having the same name as the item’s name is called. The quantity value of this record is reduced by the quantity of the food item that was ordered from the orders microservice. This inventory record is then updated and saved, and a message is printed, showing the updated food item quantity.</p><p>With our consumer configured and business logic applied, this is just half of what we should do for our consumer. The next task is to add new configurations to keep our consumer running while the Django server is also running. We can accomplish this with Python’s Threading module- a module that helps spin up additional threads in a program, and Django’s custom command management, which will help in creating a command that activates our thread.</p><p>Defining a thread for our Kafka consumer:</p><pre>## threads/kafka_consumer_thread.py<br>from threading import Thread<br>from utils.kafka.consumer import consume_kafka_messages<br>class ConsumeKafkaMessageThread(Thread):<br>  def __init__(self):<br>    Thread.__init__(self)<br>  <br>  def run(self):<br>    print(&quot;Kafka consumer thread running&quot;)<br>    consume_kafka_messages()</pre><p>In the above snippet, we import the Thread class from the threading module. We then import our consume_kafka_messages function from our kafka.consumer.py file. A ConsumeKafkaMessageThread class is defined as having the Thread class as a super class. We then execute our function for consuming Kafka messages with the run method. Going back to our consumer.py file, we make changes to it in order to match the requirements for the thread class.</p><pre>## utils/kafka/consumer.py<br><br># modified<br>from kafka import KafkaConsumer<br>import json<br>from utils.update_inventory import update_inventory<br>def consume_kafka_messages():<br>  topics = [&#39;orders&#39;]<br>  consumer = KafkaConsumer(bootstrap_servers=&quot;localhost:29092&quot;,<br>                          value_deserializer=lambda m: json.loads(m.decode(&#39;ascii&#39;)),<br>                          group_id=&quot;inventory_relation&quot;,<br>                          auto_commit_interval_ms=1000,<br>                          api_version=(2, 0, 0)<br>  )<br>  consumer.subscribe(topics)<br>  while True:<br>    all_records = consumer.poll(timeout_ms=100, max_records=100)<br>    for topic_partition, messages in all_records.items():<br>      if topic_partition.topic == &quot;orders&quot;:<br>        update_inventory(messages)</pre><p>Now that we have defined our consumer thread, let’s define a command for activating it. We want our consumer thread to start running as soon as the command, python3 manage.py runserver is executed. In our Django inventories app, create a folder structure of management/commands/ where management is the parent folder and commands is the child. In the commands folder, create two files, __init__.py and kafka_consumer.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*c5b4tn1989P4q407EH1xiw.png" /><figcaption>Folder structure of custom command for Kafka consumer.</figcaption></figure><p>In the kafka_consumer.py file, we have the code:</p><pre>from typing import Any<br>from django.core.management.base import BaseCommand<br>from threads import kafka_consumer_thread<br><br>class Command(BaseCommand):<br>  help = &quot;Start Kafka consumer&quot;<br>  def handle(self, *args: Any, **options: Any) -&gt; str | None:<br>    kafka_consumer = kafka_consumer_thread.ConsumeKafkaMessageThread()<br>    kafka_consumer.start()</pre><p>This creates a command that runs our ConsumerKafkaMessageThread class. This command has a description saying, “Start Kafka consumer”. To run the command automatically on the server’s start up, we make one little change to our inventories app configuration.</p><pre>## inventories/apps.py<br><br>from django.apps import AppConfig<br>import os<br>from django.core.management import call_command<br><br>class InventoriesConfig(AppConfig):<br>    default_auto_field = &#39;django.db.models.BigAutoField&#39;<br>    name = &#39;inventories&#39;<br>    def ready(self) -&gt; None:<br>        if os.environ.get(&#39;RUN_MAIN&#39;):<br>            print(&quot;hello kafka...&quot;)<br>            call_command(&#39;kafka_consumer&#39;)</pre><p>This snippet has the ready method defined. With this method, when the application is ready, Django checks if it is running on the main thread. If that happens to be true, the kafka_consumer command is called. This is equivalent to writing python3 manage.py kafka_consumer on the terminal.</p><p>Running our microservices on different terminals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*DJ9lLd5udUWASB09k6fY8w.png" /><figcaption>Running orders-microservice</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Fw9kvzWz7LXhlI4K1o3OVw.png" /><figcaption>Running inventories-microservice</figcaption></figure><p>To test our services, we run our Kafka service with docker compose up , and order food items. Let’s test with three items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL07KnZihUEH7BqV-Qfipg.png" /><figcaption>Items’ quantity before ordering</figcaption></figure><p>You can see that before we place an order, we have 300 chicken wings, 50 apples, and 683 bananas.</p><p>Now, we add 6 chicken wings to the cart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYkkxVOcABnrmluFKtP4zg.png" /></figure><p>Add 4 apples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qqwf0UCvYPazCLGw4AZaKg.png" /></figure><p>And 10 bananas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIf8fdaarSDgO5YCnageTw.png" /></figure><p>We then place an order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpmDwf80bMDkPEFsYzq1eg.png" /></figure><p>Our ordered items are published as a message to the Kafka broker. We should see that our inventory is updated accordingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsQkyPGN3l503JqiJYpcwg.png" /><figcaption>Items’ quantity after ordering</figcaption></figure><p>To test how effective our consumer’s configuration is during downtime, stop the inventory microservice for some seconds, place an order for 6 apples, and spin back up the microservice after a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCTDosgvn3soGIsqhwPHBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3q7iEeRXLdWuxlJV5V20A.png" /></figure><p>Run the microservice again, and you should see the updated value. Apples are now down to 40.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90FvXz2BxrAbh1BCAqRoOw.png" /><figcaption>Items’ quantity after ordering</figcaption></figure><p><strong><em>In Conclusion…</em></strong></p><p>In this article, we delved into the crucial role of Kafka consumers in ensuring reliable event-driven communication within a Django-based microservices architecture. We explored how consumers receive and process messages from Kafka topics, and the importance of offset management to ensure data consistency even in the face of service downtime.</p><p>We also walked through the practical steps of configuring a Kafka consumer in Django, including threading considerations to maintain application responsiveness. By implementing these practices, you can enhance the reliability of your microservices, ensuring that your system can handle events with minimal risk of data loss.</p><p><em>Till we meet again, dear reader, keep building...</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa9382309e28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Event-Driven Architectures with Kafka, Django and Microservices- Part 1.]]></title>
            <link>https://princeigwe.medium.com/building-event-driven-architectures-with-kafka-django-and-microservices-part-1-2b85501f5040?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b85501f5040</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 09:30:00 GMT</pubDate>
            <atom:updated>2024-08-20T04:44:49.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPGLVCKtPaWoAdp58Aog8A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">rivage</a> on <a href="https://unsplash.com/photos/brown-and-black-jigsaw-puzzle-B-x4VaIriRc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Events are occurrences or actions that have happened. These actions can trigger other actions, creating a chain of reactions within a system. In an event-driven architecture (EDA), these events serve as the primary means of communication between decoupled components, enabling systems to respond to changes and process data in real-time without being tightly coupled.</p><p><strong>Prerequisites:</strong> Before delving into the rest of the article, knowledge of Django is required. Also, ensure you have the following tools installed, as they may be required if you plan to install Kafka on your local machine:</p><ul><li>Docker</li><li>Docker Compose</li></ul><p>It is required that data be transferred among software components for the whole application to operate effectively, regardless of the architecture with which the application was built. In a monolithic application, data is sent and received between exported function calls. ModuleA.function1 is imported and called in ModuleB.function2. Whatever data the function, function1 has access to, can be utilized in function2. There are few or no complications in this form of transfer because components are familiar with themselves, and they act together as though they are of a single unit.</p><p>In an application made up of decoupled units (microservices), these units have very little interaction with each other, almost like total strangers. However, these isolated environments manage to work effectively with data transferred among themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_9msflgt5JOwXiUkvgGyQ.jpeg" /><figcaption>Monolith and Microservices</figcaption></figure><p>One may ask how this is possible?</p><p><strong><em>Event-driven architecture</em></strong></p><p>To understand what event-driven architectures are, we must first have a basic understanding of the ways in which microservices communicate with each other. There are two major forms of communication in this scenario:</p><ul><li><strong>Synchronous communication</strong></li><li><strong>Asynchronous communication</strong></li></ul><p>With synchronous communication, a microservice sends an HTTP request to another service, asking for a piece of data through an API (Application Programming Interface). Operations and processes running in the requesting service are put on hold until a response is received from the other microservice.</p><p>With asynchronous communication, a microservice “dumps” a piece of data that it thinks will be needed by another microservice. Whether or not the latter receives the data, the former does not care, and life goes on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-bllluw8beBtJCti0tvqg.jpeg" /><figcaption>Communication types across microservices</figcaption></figure><p>Event-driven architecture belongs to the category of asynchronous communication.</p><p>Event-driven architecture (<strong>EDA</strong>) is simply a design pattern that helps decoupled systems (microservices) communicate with each other with the help of triggered events. This architecture is made of 4 components:</p><ul><li><strong>Publisher:</strong> This component is the system that publishes events to the event broker. It sends these events, which are the results of actions that were carried out in its system.</li><li><strong>Subscriber:</strong> Just as the name implies, this component subscribes to one or more “topics” in the event broker. By subscribing, it automatically listens and fetches events that were sent to these topics for processing. In this context, think of a topic as a folder that is used to contain related files (events).</li><li><strong>Event:</strong> This is the result of an action containing data that was worked on by the publisher.</li><li><strong>Event Broker:</strong> This is middleware software between publishers and subscribers. It is responsible for distributing events among decoupled systems. Popular event broker technologies include Google Cloud Pub/Sub, Azure Event Grid, RabbitMQ, and Apache Kafka.</li></ul><p><strong><em>Apache Kafka</em></strong></p><p>Kafka is a streaming platform that’s used to collect, store, and process streams of data in real-time. Think of Kafka like a mail service. You prepare your letter and take it to the post office so that it will be processed and sent to your dear fellow. During this process, the recipient is unaware of what is going on at the moment and continues with his life, and suddenly he has a letter from you, his dear friend. The difference here is that you and your friend are familiar with each other; microservices using Kafka aren’t. In this scenario, we can all agree that the operations of the mail service revolve around people’s mail. In the same way, one of the most important components of Kafka is the <strong>message</strong>.</p><p>Messages are made up of components, including keys (not so important for your work) and values (responsible for holding your event data). These messages are sent by applications known as <strong>producers</strong> to a server known as a <strong>broker</strong> and kept in a type of database known as the <strong>commit log</strong>.</p><p>This broker keeps the operations of reading, writing, and storing records functional. The <strong>consumer,</strong> on the other end, automatically receives these messages from <strong>topics</strong> it subscribes to and acts on them according to its business logic. All the operations of Kafka are managed by <strong>Zookeeper,</strong> a software that maintains brokers and manages the configuration of topics and partitions.</p><p>With Kafka in the picture, EDAs are implemented, allowing application systems to share data effectively among themselves without interfering with each other’s running operations.</p><p>Given this understanding, how do we implement EDAs in our Python microservices?</p><p><strong><em>Demo</em></strong></p><p>Knowing that Kafka is an important unit, you can either configure your Kafka cluster and deploy it to a remote environment, or you can use managed Kafka instances from various cloud services for production, but these are outside the scope of this article.</p><p>Here, we will be configuring and running Zookeeper and our Kafka cluster locally with Docker Compose for a food supermarket enterprise.</p><p>If you need a step-by-step guide to setting them up, refer to <a href="https://medium.com/@erkndmrl/kafka-cluster-with-docker-compose-5864d50f677e">this detailed Medium article</a>.</p><p>You can find the GitHub repo for this demo <a href="https://github.com/Princeigwe/kafka-EDA-demo">here.</a></p><p>So a food supermarket company from some alternate universe came to us with a problem. The issue is that most times they run out of food on business days, leaving customers angry and unsatisfied, and that’s bad business.</p><p>The solution? We build software that takes customers’ orders and, at the same time, keeps track of the quantity of food items in store after they are ordered. In this scenario, we would have two microservices. One for taking orders, the other for inventory management, running with our local Kafka broker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*PfTEqCsEtqDVgTTgLUa8pg.png" /><figcaption>Demo folder structure</figcaption></figure><p>Installing Kafka does not come with a GUI, so most commands run only with the command line interface. For this demo, we have a Kafka setup in our compose.ymlfile:</p><pre>version: ‘3.7&#39;<br><br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    container_name: zookeeper<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - 2181:2181<br><br>  kafka:<br>    image: confluentinc/cp-kafka:latest<br>    container_name: kafka<br>    depends_on:<br>      - zookeeper<br>    ports:<br>      - 9092:9092<br>      - 29092:29092<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092 #  makes Kafka accessible outside the container to clients on the Docker host<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br><br>  kafka_cli:<br>    image: confluentinc/cp-kafka:latest<br>    container_name: kafka_cli<br>    depends_on:<br>      - kafka<br>    entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;] This runs an executable script in the Kafka Docker container followed by the next set of arguments after it. In this case, kafka-topics is the script.<br>    command: |<br>      &quot;<br>      sleep 15<br>      kafka-topics --bootstrap-server kafka:9092   --create --if-not-exists --topic orders --replication-factor 1 --partitions 1 --config retention.ms=1800000<br>      echo -e &#39;Topic created&#39;<br>      kafka-topics --bootstrap-server kafka:9092   --list<br>      kafka-topics --describe --bootstrap-server kafka:9092  --topic orders<br><br>      &quot;</pre><p>Here we have Confluent Docker images of Apache Zookeeper and Kafka. Without paying much attention to the zookeeper service, we see that kafka builds and runs right after the Zookeeper container is up and running. The kafka service connects to Zookeeper management through the zookeeper:2181 URL. This service exposes Kafka to clients both within the Docker network (kafka:9092) and on the host machine (localhost:29092).</p><p>For the kafka_cli service, we see that it is set to run right after the kafka container is ready. The sole purpose of this particular service is to run commands on the kafka environment. At the beginning, a delay of 15 seconds is set. This is to ensure that the Kafka broker is fully operational before we run any Kafka commands.</p><p>Next, we run a command that executes an executable script — kafka-topics.sh, for creating kafka topics. This script is executed with several arguments to create a topic named orders , only if that topic does not exist, with 1 partition, and a custom message retention period of 30 minutes (1,800,000 milliseconds) instead of the default 7-day retention period.</p><p>The next command simply gives a list of created topics, after which we can see the configurations for the orders topic. Running these services with docker compose up give the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2JEOp9n7hkRetnky-rO4g.png" /><figcaption>Docker logs</figcaption></figure><p>With a Kafka broker ready, we can now integrate it into our microservices. It is good to know that microservices are language-agnostic, meaning that a group of them can be built and function efficiently with several programming languages and frameworks, unlike a monolith application, where a single programming language/framework is used from start to finish. For the scope of this article, we will be building both microservices with Django.</p><p>In the orders-microservice folder, we already have our business logic, starting with the data models, down to the URL endpoints:</p><pre>## orders/models.py<br><br>from django.db import models<br>from . import status<br><br><br>class FoodItem(models.Model):<br>  name       = models.CharField(max_length=50)<br>  price      = models.DecimalField(max_digits=10, decimal_places=2)<br><br>  def __str__(self) -&gt; str:<br>    return self.name<br><br>class Order(models.Model):<br>  customer_name = models.CharField(max_length=50)<br>  status        = models.CharField(max_length=20, choices=status.ORDER_STATUS, default=&quot;PLACED&quot;)<br>  created       = models.DateTimeField(auto_now_add=True)<br><br>  def __str__(self) -&gt; str:<br>    return self.customer_name<br><br><br>class OrderItem(models.Model):<br>  name       = models.CharField(max_length=50)<br>  quantity   = models.PositiveIntegerField()<br>  unit_price = models.DecimalField(max_digits=10, decimal_places=2)<br>  price      = models.DecimalField(max_digits=10, decimal_places=2)<br>  order      = models.ForeignKey(Order, on_delete=models.CASCADE)<br><br>  def __str__(self) -&gt; str:<br>    return self.name</pre><pre>## orders/serializers.py<br><br>from rest_framework import serializers<br><br>class CartSerializer(serializers.Serializer):<br>  quantity = serializers.IntegerField()</pre><pre>## orders/views.py<br><br>from django.shortcuts import render<br>from rest_framework.response import Response<br>from rest_framework.views import APIView<br>from rest_framework import status<br>from .models import FoodItem, Order as OrderModel, OrderItem<br>from . serializers import CartSerializer<br>from django.http import Http404<br>from django.core.cache import cache<br><br><br>cart_owner = &quot;prince_igwe_cart&quot;<br><br>class CartItems(APIView):<br>  def post(self, request, food_id):<br>    try:<br>      serializer = CartSerializer(data=request.data)<br>      if serializer.is_valid():<br>        item_quantity = request.data[&#39;quantity&#39;]<br>        food_item = FoodItem.objects.get(id=food_id)<br><br>        ## setting new cart for Prince only if there&#39;s none existing<br>        cache.add(key=cart_owner, value={&quot;customer_name&quot;: &quot;prince igwe&quot;, &quot;items&quot;: [] }, timeout=1200)<br><br>        ## add food item to cart<br>        my_cart_items = cache.get(cart_owner)[&#39;items&#39;]<br>        cart_item = { &quot;name&quot;: food_item.name, &quot;price&quot;: int(food_item.price), &quot;quantity&quot;: item_quantity }<br>        my_cart_items.append(cart_item)<br>        cache.set(key=cart_owner, value={ &quot;customer_name&quot;: &quot;prince igwe&quot;, &quot;items&quot;: my_cart_items })<br><br>        updated_cart = cache.get(key=cart_owner)<br>        print(updated_cart)<br><br>        return Response({&quot;message&quot;: &quot;Added to cart&quot;}, status=status.HTTP_200_OK)<br>      return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br>    except FoodItem.DoesNotExist:<br>      raise Http404<br><br><br>class Order(APIView):<br>  # place an order<br>  def post(self, request):<br>    my_cart = cache.get(key=cart_owner)<br>    order = OrderModel.objects.create(customer_name=my_cart[&#39;customer_name&#39;])<br>    order.save()<br><br>    my_cart_items = cache.get(cart_owner)[&#39;items&#39;]<br>    for item in my_cart_items:<br>      item_name = item[&#39;name&#39;]<br>      item_quantity = item[&#39;quantity&#39;]<br>      item_unit_price = item[&#39;price&#39;]<br>      price = item_unit_price * item_quantity<br><br>      order_item = OrderItem.objects.create(name=item_name, quantity=item_quantity, unit_price=item_unit_price, price=price, order=order)<br>      order_item.save()<br><br>    cache.delete(cart_owner)<br>    <br>    return Response({&quot;message&quot;: &quot;Order has been placed for delivery.&quot;}, status=status.HTTP_200_OK)</pre><pre>## orders/urls.py<br><br>from django.urls import path<br>from .views import CartItems, Order<br><br>urlpatterns = [<br>  path(&quot;cart/&lt;int:food_id&gt;&quot;, CartItems.as_view()),<br>  path(&quot;&quot;, Order.as_view())<br>]</pre><p>From the first set of code, we have models that work hand-in-hand to keep up with the details of the customers’ needs. FoodItem hold the data on the delicious foodstuffs displayed on the company’s e-commerce website—their names and prices. The Order model represents the customers’ orders, holding details of the customers’ names, the order&#39;s status, and the time the order was placed. The OrderItem holds data of food items that are related to the order that was placed.</p><p>In the views.py file, we have simple logic for our cart and order features. Here we see aPOST action that will be responsible for adding food items to a cart cache for a customer named prince igwe. This customer can specify the quantity for each food item of his choice, with the CartSerializer . After prince is satisfied with his choices, he can place an order for those items, which clears his cart later on.</p><p>In the urls.py file, we see endpoints are attached to our logic in the previous file.</p><p>After running the server for this API, on Django’s admin page, we see that there are predefined foodstuffs for customers, along with their prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UaOl1_EM1ukEaPqtuFX4sw.png" /><figcaption>Food Items on Django Admin page</figcaption></figure><p>Testing our endpoints, we see that items are added to cart, orders placed and data is stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1zVoM8KrMdRqhZU75hHEg.png" /><figcaption>Add item to cart</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGX7__Azo7fglzW2FTg4yg.png" /><figcaption>Place an order</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URyx7Ok1k9vagXDwXg3h0Q.png" /><figcaption>Orders</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7MTiHwojSwmUMP68rdq1w.png" /><figcaption>Ordered Items</figcaption></figure><p>With almost half of the problem solved, we will integrate Kafka into this API. The orders microservice will be working as a producer, publishing events to the Kafka broker.</p><p>Configuring a producer requires several properties, of which three are most popularly known:</p><ul><li><strong>bootstrap servers: </strong>This argument holds the values of brokers’ connection strings, connecting the producer to the Kafka cluster.</li><li><strong>key serializer: </strong>This is the serializer that serializes an optionally specified key to a byte array for publishing messages. This key is responsible for determining what partition the message will be going to, in the topic. If no key is provided by us, then messages will be evenly distributed among all partitions in the topic.</li><li><strong>value serializer: </strong>This serializer serializes our message (event data) into a byte array for transactions over the network.</li></ul><p>Out of these arguments, the value(s) for the bootstrap servers must be provided.</p><p>With this basic knowledge, let’s set up our producer. We will be installing a Kafka client for Python, called kafka-python .</p><pre>pip install kafka-python</pre><p>After installation, we can create a utilities folder where we can setup the Kafka configurations for the producer.</p><pre>## utils/kafka/producer.py<br><br>from kafka import KafkaProducer<br>from kafka.errors import KafkaError<br>import json<br><br>producer = KafkaProducer(bootstrap_servers=&quot;localhost:29092&quot;,<br>                        value_serializer=lambda m: json.dumps(m).encode(&#39;ascii&#39;),<br>                        api_version=(2, 0, 0)<br>)<br><br>topic = &quot;orders&quot;<br><br>def update_inventory(ordered_items):<br>  future = producer.send(topic, ordered_items)<br>  try:<br>    metadata = future.get()<br>    print(metadata)<br>  except KafkaError as e:<br>    print(e)</pre><p>This snippet of code sets up a producer client that connects to our Kafka broker in our compose.yml file, with the URL “localhost:29092”. The value_serializer converts our message value to a JSON format, before serializing it to a byte array. It api_version selects the Kafka version we want to use. In this case, 2.0.0. The default value is 0.10.2.</p><p>We define a function which publishes the details of the ordered items to our orders topic in a synchronous manner. This means that the producer publishes our message to the broker and waits for a response object containing details of our successfully published message, which is called the <strong>RecordMetaData</strong>. If an error is encountered, it is printed as well.</p><p><strong><em>In Conclusion…</em></strong></p><p>In this article, we’ve explored how to set up a Kafka producer in a Django microservice to publish events. By configuring Kafka to act as a communication bridge, we’ve taken the first step toward building an event-driven architecture that allows for scalable and decoupled services.</p><p>But publishing events is only half of the equation. In the next part of this series, we’ll dive into how another microservice can consume these events and take action based on them. We’ll cover how to set up a Kafka consumer in Django, handle event processing, and ensure that our inventory management microservice stays in sync with the orders placed by customers.</p><p>Stay tuned for <a href="https://princeigwe.medium.com/building-event-driven-architectures-with-kafka-django-and-microservices-part-2-fa9382309e28">Part 2</a>, where we’ll continue building out this real-time, event-driven system with Apache Kafka.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b85501f5040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamless Authentication: Integrating OpenID Connect with Django Using Auth0.]]></title>
            <link>https://princeigwe.medium.com/seamless-authentication-integrating-openid-connect-with-django-using-auth0-35d83068f197?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d83068f197</guid>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 05:34:47 GMT</pubDate>
            <atom:updated>2024-04-16T05:34:47.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePXMxF048qf6pcxTM_6CRQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@piensaenpixel?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Emilio Garcia</a> on <a href="https://unsplash.com/photos/left-human-eye-BKyJBKBloBQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Data is everywhere; it’s all around us. In our schools, our industries, our workplaces, and our lives in general, there’s some form of data that concerns us, waiting to be requested or manipulated. In order to utilise our data effectively, our software applications need to know the identity of the person requesting for such data.</p><p>As developers, we can figure this out by asking users to always provide their emails/usernames and passwords whenever they need to access data. However, this may not be the best experience for them, as there could be some delays in the authentication process during the time the users are cooking up random “strong” passwords like “JohnDoe123” for account creation or while trying to remember a hint for their precious forgotten passwords.</p><p>To provide better user experience with seamless authentication, we could look to third-party methods that take control of the authentication process, popularly referred to as the authentication flow, while we focus on providing data to their rightful owners.</p><p>This is where OpenID Connect (OIDC) comes into play.</p><p><strong><em>So, what is OpenID Connect?</em></strong></p><p>OpenID Connect (OIDC) is an identity protocol built on OAuth 2.0, a delegated authorization framework, that’s used to define how users authenticate their identities across multiple software applications. Rather than requiring users to provide their credentials repeatedly to several applications during authentication, these applications just need to request for the authenticated user’s ID token, which contains a set of user <strong>claims</strong> (simply pieces of information about the end user) from an OpenID provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*3tAKaUWiqydM8ADTPKblbQ.png" /><figcaption>User access with and without OIDC</figcaption></figure><p>So if you’ve ever tried signing up or logging in to your account with a login page looking like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*yI-QugvXJfrcqIPv8AxA-A.png" /><figcaption>sign in page</figcaption></figure><p>congratulations; you’ve mostly likely used OIDC.</p><p>For a complete OIDC authentication process, several components are required to play their roles.</p><ol><li><strong>OpenID Provider (OP)</strong>—responsible for managing the user’s credentials and identity data. Popular examples of providers include Google, Microsoft, Twitter, and LinkedIn.</li><li><strong>The Relying Party (RP) or Client Application</strong>—the application requesting for the identity data of the user.</li><li><strong>End-User</strong>—needs access to the client application.</li></ol><p>With these three bodies in place, here is an overview of the authentication process:</p><ol><li>The user makes an unauthenticated request to the client application.</li><li>The client application redirects the user to an OP for authentication.</li><li>The OP prompts the user to authenticate.</li><li>After authentication, authorization for user’s data is granted to the client application</li><li>With the authorization given, the client application requests for the user’s identity data from the OP in order to create or retrieve related custom data of the user from its own local data store.</li></ol><p>In OAuth2.0 and OIDC, there are methods that determine the authentication and delegation flows in a software application; these methods are called <strong>grant types</strong> and they include:</p><ul><li><strong>Client credentials</strong>: This grant type is used when the client application is acting on its own behalf, typically for server-to-server communication. It involves the client providing its credentials directly to the authorization server.</li><li><strong>Authorization code</strong>: This is the most common grant type for web applications. It involves the client first obtaining an authorization code from the authorization server, which is then exchanged for an access token.</li><li><strong>Resource owner credentials</strong>: This grant type involves the client obtaining the user’s credentials directly and using them to authenticate and obtain an access token from the authorization server. This method is less secure and is not recommended.</li><li><strong>Implicit</strong>: In this grant type, the client obtains an access token directly from the authorization server, without an intermediate authorization code exchange step.</li><li><strong>Refresh token</strong>: With this grant type, the client requests a new access token after the existing one is expired with a refresh token without needing the user to re-authenticate</li><li><strong>Hybrid flow</strong>: This grant type originating from OpenID Connect combines both the authorization code and implicit delegation flows, where the client receives both an authorization code and an ID token after the user authorizes it, but then the client can go ahead and request an access token with the authorization code.</li></ul><p>Out of these grant types and authentication flows, the authorization code flow is the most implemented for web applications that involve an end user, due to its robust support for user authentication. In this flow, both authentication and authorization revolve around an authorization code.</p><p>There are components involved in this process.</p><ul><li>The authorization server: This is responsible for authenticating the end user.</li><li>Client: The software application that’s in need of the user’s data.</li><li>User: You, me, the individual that needs access to the client application.</li></ul><p>Here’s how the authorization code delegation flow works:</p><ol><li>The client application initiates the delegation flow by sending a request to the authorization server’s authorization endpoint, along with a set of parameters that include:</li></ol><ul><li><strong>redirect_uri</strong>: This is the URI that the authorization server uses to redirect the user back to the client application after authentication.</li><li><strong>scope</strong>: This can be one or more permissions that need to be granted in order to enable the client application to access data or execute some functionalities on behalf of the user.</li><li><strong>response_type</strong>: Determines the grant type of the delegation flow, typically set to “code” for the Authorization Code flow.</li><li><strong>client_id</strong>: This is the public identifier that the authorization server uses to identify a client. It acts as the username of the client application.</li></ul><p>2. The authorization server prompts the user to authenticate. After user authentication, it presents the requested scopes for approval, and the user grants the client access to the specified scope permissions.</p><p>3. The user is redirected to the client with an authorization code indicating that its permissions were granted.</p><p>4. The client exchanges the authorization code for an access token by sending a request to the authorization server’s token endpoint.</p><p>5. The authorization server validates the authorization code and issues an access token to the client.</p><p>6. With the access token, the client accesses the user’s data and resources for a limited period of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcSWZNH905x13GWLvuDpbg.png" /><figcaption>OAuth2.0 Authorization Code Delegation Flow</figcaption></figure><p>In an OIDC flow, the client application sends a request to three endpoints:</p><ol><li><strong>Authorization endpoint</strong>: This endpoint is responsible for the authentication of the end user. This request is sent in this format:</li></ol><pre>GET &lt;authorization endpoint&gt;/?<br>response_type=code<br>&amp;client_id=&lt;client id&gt;<br>&amp;redirect_uri=&lt;redirect uri&gt;<br>&amp;scope=openid%20profile%20email</pre><p>2. <strong>Token endpoint</strong>: With this endpoint, the client application receives an ID token and an access token. The ID token is a JWT that contains both user and registered claims.</p><p>The registered claims contain details about the creation of the ID token, such as:</p><ul><li><strong>iss</strong>: Issuer of the JWT</li><li><strong>sub</strong>: Subject of the JWT (the client ID)</li><li><strong>iat:</strong> Time at which the JWT was issued, which can be used to determine age of the JWT</li><li><strong>exp</strong>: Time after which the JWT expires</li></ul><p>These claims appear as a result of the openid scope.</p><p>Upon receiving a token response, the ID token must be validated before use in order to make sure that it has not been tampered with while in transit. Token validation is done by verifying the signature of the token with its public key.</p><p>We can either validate and decode the ID token with Python’s <a href="https://pyjwt.readthedocs.io/en/stable/">PyJWT</a> package to get user claims, or we can send a request to the userinfo endpoint with the access token gotten from the token response as a Bearer token in the Authorization header, to selectively retrieve user claims.</p><p>3. <strong>UserInfo endpoint</strong> (Optional)</p><p>While OAuth2.0 delegates authorization rights to client applications, allowing them to execute functionalities on user data, OIDC focuses on facilitating the sharing of a user’s identity information across multiple applications. This depends on the nature of the scope specified during the authorization request. In the context of OIDC authentication, an authorization server is the OpenID provider. To make an OIDC authentication request, the openid scope value should be included in the scope parameter, along with an optionalemail or/and a profile scope for user information.</p><p>The profile scope returns claims about the user, containing the user’s</p><ul><li>family name</li><li>given name</li><li>middle name</li><li>nickname</li><li>profile picture</li></ul><p>The email scope returns claims about the user, containing their email address and a boolean value of email verification.</p><p>There are many OpenID providers that you can integrate into your software application, including Google, Microsoft, PayPal, Apple and Okta. For this article, we would be focusing on one, which is Auth0.</p><p><strong><em>What is Auth0?</em></strong></p><p>Firstly, I must say that Auth0 is different from OAuth2.0. I made this mistake when I first learned about them.</p><p>Auth0 is an identity platform used by developers to integrate various security protocols and frameworks into their applications before granting users access to these applications. So while OAuth2.0 is an authorization framework, Auth0 helps developers integrate this framework into software applications. While Auth0 is an identity provider, we should also know that it is an identity broker, connecting to external identity providers as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpidWSvJMS-UJ6VfkflL_Q.png" /><figcaption>Auth0 as an IdP and Identity broker</figcaption></figure><p>In order to work with Auth0, you must have an account with the platform. You can visit the <a href="https://auth0.com/">homepage</a> and sign up.</p><p>Now that we’ve seen how OIDC improves user experience and data security, as developers, how do we integrate it into our Django applications? Let’s find out.</p><p><strong><em>Demo…</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*oYAvvDrdkcMN7i6o6jSjEQ.png" /><figcaption>Gojo’s domain expansion</figcaption></figure><p>To begin with, I’ll be working with an existing demo GitHub <a href="https://github.com/Princeigwe/blog-QL">repo</a>. In this case, the repo will be our client application. When you create an account, a “room” is automatically created for your application. This is what Auth0 calls a <strong>tenant</strong>. A tenant holds all the Auth0 assets of your client application, such as connections, applications, and user profiles. However, if you want to create a new tenant for your application, here’s how you do it:</p><p>On the top left corner of your account’s dashboard, click the drop-down button and click the create tenant button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Os4wPWbxdLVdYDUrZJpSUQ.png" /><figcaption>create tenant</figcaption></figure><p>Input a tenant name that contributes to the Auth0 domain for our blog API and create a tenant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*daI7BDML_2A8s2qKaDlNBA.png" /><figcaption>tenant setup</figcaption></figure><p>On the next page, you will see two options that provide more details about Auth0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPpC4av-zDmH8qRti2W6kw.png" /><figcaption>tenant created</figcaption></figure><p>Next, we register our client application with the tenant. On the side bar, click the Applications drop-down button and select Applications, then click the Create Application button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lBFdniiFNpb8mPAAdVPJg.png" /><figcaption>create application</figcaption></figure><p>On the modal, type in your client application’s name, mine will be blog-ql. Set the application type to Regular Web Applications and click the create button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*QngVIrrSpzJWFj6pu-PhPw.png" /><figcaption>application setup</figcaption></figure><p>On the next page, click the settings tab, and you will see the details needed to set your application as an Auth0 client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Eo7d_pCf8evLF0ZMWWfC7g.jpeg" /><figcaption>client details</figcaption></figure><p>Now, you need to store the details of your Domain , Client ID , and Client Secret in your source code, which helps Auth0 recognize your application.</p><p>Recall that an end user is redirected to the client application after authentication, so we have to provide a redirect_uri in our settings. Running on a localhost server, our redirect URI could look like this:http://127.0.0.1:8000/blog/auth0/callback.</p><p>Add this to the list of Allowed Callback URLs in the Applications URIs section of the Settings tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*VdSkUOZ6nrfbo6dYseQHmA.png" /></figure><p>Once a tenant has been created, it is automatically linked to Google as an Identity Provider. We can find it in our Social Connections by clicking the Social button in the Authentication drop-down menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPwNz4ilayUWE51Y5qVxCw.png" /><figcaption>Auth0 social connections</figcaption></figure><p>You can choose to link your client application to more social connections by clicking the Create Connections button.</p><p>Moving to our Django source code, we need to import three Python packages:</p><ul><li><strong>Python-dotenv:</strong> to help read our client data in environment variables</li><li><strong>requests</strong>: to send HTTP requests from our source code.</li><li><strong>PyJWT:</strong> used to validate and decode JWTs</li></ul><pre>pip install python-dotenv requests pyjwt</pre><p>In our views.py file, create a view function that will be called by the user to authenticate.</p><pre>from django.shortcuts import render, redirect<br>import requests<br>import os<br>from dotenv import load_dotenv<br>load_dotenv()<br>from django.http import JsonResponse<br><br>import json<br>import jwt<br><br># Auth0 client details<br>auth0_domain = os.environ.get(&#39;AUTH0_DOMAIN&#39;)<br>client_id = os.environ.get(&#39;AUTH0_CLIENT_ID&#39;)<br>client_secret = os.environ.get(&#39;AUTH0_CLIENT_SECRET&#39;)<br>redirect_uri = &quot;http://127.0.0.1:8000/blog/auth0/callback&quot;<br><br><br># user interacts with this function to be authenticated by <br>def oidc_authenticate(request):<br>  auth0_authorization_url = f&quot;http://{auth0_domain}/authorize&quot; # authorization endpoint<br>  params = {<br>      &quot;response_type&quot;: &quot;code&quot;, # OIDC flow will be of the authorization code grant type<br>      &quot;client_id&quot;: client_id,<br>      &quot;redirect_uri&quot;: redirect_uri,<br>      &quot;scope&quot;: &quot;openid profile email&quot;, # scopes<br>  }<br>  <br>  # redirect user to OpenID provider to be authenticated<br>  return redirect( f&quot;{auth0_authorization_url}?{&#39;&amp;&#39;.join([f&#39;{key}={value}&#39; for key, value in params.items()])}&quot; )</pre><p>After the view function is called, our client application receives a response containing the keys,id_token, access_token, scope, expires_in and token_type. In order to use our ID token, it must first be validated with its public key. In the process of token validation, only the recipient in possession of the public key can validate the token. This brings us to the question:</p><ul><li><em>How do we check for possession of the public key?</em></li></ul><p>A token is made up of three parts: a header, a payload, and a signature. The header contains three details:</p><ul><li><strong>alg: </strong>the algorithm that was used to sign the token.</li><li><strong>typ: </strong>the type of token</li><li><strong>kid</strong>: the key identifier of the public key</li></ul><p>Here, the attribute needed to check for possession of a public key is the kid , in the sense that it must be present in our tenant&#39;s JSON Web Key Set (JWKS) for the token to be considered valid. Every tenant has a set of JSON Web Keys (JWK), and each key makes up a public key. This set can be accessed with the URL format: <a href="https://blog-ql.us.auth0.com/.well-known/jwks.json">https://{your_auth0_domain}/.well-known/jwks.json</a>. For our demo application, it is <a href="https://blog-ql.us.auth0.com/.well-known/jwks.json">https://blog-ql.us.auth0.com/.well-known/jwks.json</a>.</p><p>Moving to the next step of the OIDC flow, we define another function for the redirect_uri. This will be used to redirect the user to the client application. Upon redirection, the client requests a token, which will be validated and decoded to access user claims:</p><pre>def oidc_callback(request):<br>  # https://blog-ql.us.auth0.com/.well-known/jwks.json<br>  jwks_endpoint = os.environ.get(&#39;AUTH0_JWKS_ENDPOINT&#39;)<br><br>  authorization_code = request.GET.get(&quot;code&quot;)<br><br>  # exchanging code for token<br>  token_url = f&#39;https://{auth0_domain}/oauth/token&#39;<br>  token_data = {<br>      &quot;grant_type&quot;: &quot;authorization_code&quot;,<br>      &quot;client_id&quot;: client_id,<br>      &quot;client_secret&quot;: client_secret,<br>      &quot;code&quot;: authorization_code,<br>      &quot;redirect_uri&quot;: redirect_uri<br>  }<br><br>  token_response = requests.post(token_url, data=token_data)<br>  token_response_data = token_response.json()<br><br>  id_token = token_response_data[&#39;id_token&#39;]<br><br>  ## token validation<br>  # get ID token header<br>  id_token_jwt_header = jwt.get_unverified_header(id_token)<br>  jwks = requests.get(jwks_endpoint).json()<br>  public_key = None<br>  for jwk in jwks[&#39;keys&#39;]:<br>    if jwk[&#39;kid&#39;] == id_token_jwt_header[&#39;kid&#39;]:<br>      public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))<br>  if public_key is None:<br>    raise Exception(&quot;Public key not found&quot;)<br>  <br>  try:<br>    decoded_data = jwt.decode(id_token, public_key, audience=client_id, issuer=issuer, algorithms=[&#39;RS256&#39;])<br>    return JsonResponse(decoded_data)<br>  except jwt.exceptions.DecodeError as e:<br>    print(&quot;Invalid Token: &quot;, e)</pre><p>Create URLs for these view functions in your app’s urls.py file.</p><pre>from django.urls import path<br>from .views import oidc_authenticate, oidc_callback<br><br><br>urlpatterns = [<br>  # http://127.0.0.1:8000/blog/auth/<br>  path(&#39;auth/&#39;, oidc_authenticate, name=&quot;oidc_authenticate&quot;),<br><br>  # http://127.0.0.1:8000/blog/auth0/callback/<br>  path(&#39;auth0/callback/&#39;, oidc_callback)<br>]</pre><p>The app’s URLs must be contained in the project’s urlpatterns.</p><pre>urlpatterns = [<br>    ...<br>    ...<br>    path(&#39;blog/&#39;, include(&#39;blog.urls&#39;))<br>]</pre><p>Run the localhost server with python3 manage.py runserver and call the blog authentication URL, <a href="http://127.0.0.1:8000/blog/auth/">http://127.0.0.1:8000/blog/auth/,</a> from your browser. At first, you should see a page where you’re asked to authorize the blog API to access your profile and email data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Wlk8m9S3skOdR0yCZulfmg.png" /></figure><p>Another time, you will be visited by a page with a “Sign in with Google” button because of the Google social connection.</p><p>You should get a response page with your user claims, where you can go ahead and use the data according to your application’s requirements.</p><p><strong><em>In conclusion…</em></strong></p><p>OpenID Connect (OIDC) offers a streamlined approach to authentication, enhancing user experience while maintaining security. Auth0 serves as an identity platform, integrating security protocols seamlessly into applications.</p><p>By understanding OIDC’s authentication flow and leveraging platforms like Auth0, developers can ensure both user convenience and robust data protection.</p><p>So next time you’re building an application, please think twice and reconsider your method of authentication, for the sake of your dear users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d83068f197" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fostering Real-Time Interactivity: A Guide to GraphQL Subscriptions in Django for Web APIs.]]></title>
            <link>https://princeigwe.medium.com/fostering-real-time-interactivity-a-guide-to-graphql-subscriptions-in-django-for-web-apis-0e763ca33564?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e763ca33564</guid>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 09:05:43 GMT</pubDate>
            <atom:updated>2024-03-04T09:05:43.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i70M6oTT8TooCD90qha19g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sebastiandumitru?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Sebastian Dumitru</a> on <a href="https://unsplash.com/photos/persons-hand-on-white-wall-36g19a7ivrs?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Most modern applications have one or two features that promote real-time interactivity with the user. These interactions can have high and low priorities. High-priority real-time interactions require time-sensitive actions. An example of an application that falls into this category is our messaging app. We want to receive a quick response after sending our message. On the other hand, low-priority real-time interactions may involve less critical updates or notifications that enhance the user experience but may not require immediate attention. An example is timely game updates as notifications on our sports apps.</p><p>These interactions can be implemented with asynchronous communication among application components with the help of events or with popular communication protocols like WebSockets and MQTT. Since we are talking about GraphQL, subscriptions are suitable for incorporating real-time interactivity into applications.</p><p>In my previous article, I introduced GraphQL, covering its fundamental operations, <em>mutation and query </em>with demonstrations.</p><p><a href="https://princeigwe.medium.com/unveiling-graphql-in-django-a-straightforward-guide-to-modern-api-development-111d390c257e">Unveiling GraphQL in Django: A straightforward guide to modern API development.</a></p><p>In the article, we also see that there was a brief explanation of subscriptions.</p><blockquote>For the <strong>subscription</strong> operation, think of it as the WebSocket connection for GraphQL APIs. While the <strong>query</strong> operation receives an API response after a single request, the subscription reads data continuously in real-time.</blockquote><p>This is because the operation actually works with a WebSocket connection, which helps push updates to the client application listening for real-time data.</p><p>Assuming we were building a feature where we wanted the user to receive goal updates for an ongoing football match, on the server-side, we would have to define a Goal schema that would contain the necessary data about a scored goal, and then we would create a resolver function, let’s say,goalScored that would work with the Subscription schema type to publish in real time.</p><pre>type Goal {<br>  team: String!<br>  scorer: String!<br>  minute: Int!<br>}<br><br>type Subscription {<br>  goalScored: Goal<br>}</pre><p>On the client side of our application, listening for real-time goal updates would be done by sending the query:</p><pre>subscription {<br>  goalScored {<br>    team<br>    scorer<br>    minute<br>  }<br>}</pre><p>This would give the response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;goalScored&quot;: {<br>      &quot;team&quot;: &quot;Barcelona FC&quot;,<br>      &quot;scorer&quot;: &quot;Lionel Messi&quot;,<br>      &quot;minute&quot;: 45<br>    }<br>  }<br>}</pre><p>Once the first subscription query has been sent out, the client app doesn’t need to send another request to see if another goal was scored; it just updates in real-time.</p><p>With enough introduction, implementing subscriptions in your Django API requires its server to run asynchronously. Knowing that Django operates on a synchronous server by default, you would have to make your server operate asynchronously with a Python ASGI server like Daphne.</p><p><strong><em>Demo…</em></strong></p><p>In the demo from the previous article, we built a blog-author GraphQL API, where we created Author ‘accounts’ and published blogs. Let’s assume that a reader has subscribed to get their authors’ latest articles on our API. How do we implement a real-time notification feature where this reader gets these updates? Come with me.</p><p>Django Channels is a Django library that helps you write code efficiently on an ASGI server. While the default Django package enables you to write code for HTTP connections, Django Channels enables you to write code beyond the HTTP request-response cycle.</p><p>To get started, we will have to install Django Channels with the optional Daphne add-on to install both Channels and Daphne at once.</p><pre>pip install channels[&quot;daphne&quot;]</pre><p>Place the Daphne package at the beginning of your INSTALLED_APP settings to enable the ASGI server to run on Django’s runserver command.</p><pre>INSTALLED_APPS = [<br>    &#39;daphne&#39;, ## here<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br><br>    # 3rd party apps<br>    &quot;ariadne_django&quot;,<br><br>    # local apps<br>    &quot;blog.apps.BlogConfig&quot;,<br>]</pre><p>Edit the asgi.py file in your core folder to look like this:</p><pre>import os<br><br>from django.core.asgi import get_asgi_application<br>from ariadne.asgi import GraphQL<br>from channels.routing import URLRouter<br>from .schema import schema<br>from django.urls import path, re_path<br>from ariadne.asgi.handlers import GraphQLTransportWSHandler<br><br>os.environ.setdefault(&#39;DJANGO_SETTINGS_MODULE&#39;, &#39;core.settings&#39;)<br><br># application = get_asgi_application()<br><br>application =  URLRouter([<br>  path(&quot;graphql/&quot;, GraphQL(schema=schema, websocket_handler=GraphQLTransportWSHandler())),<br>  re_path(r&quot;&quot;, get_asgi_application())<br>])</pre><p>From the above code, we set our GraphQL API to run on the ASGI server with Ariadne’s ASGI GraphQL class. By specifying websocket_handler=GraphQLTransportWSHandler , we choose to use the sub-protocol (graphql-transport-ws) of the GraphQL-over-Websocket protocol (<a href="https://github.com/enisdenjo/graphql-ws">graphql-ws</a>) to handle subscription WebSocket connections in GraphQL queries. Another subscription protocol for GraphQL WebSocket connections is the default subscriptions-transport-ws written by <a href="https://github.com/apollographql/subscriptions-transport-ws">Apollo</a>, but this is no longer maintained.</p><p>Edit the settings.py file to register our ASGI application as the root application.</p><pre># WSGI_APPLICATION = &#39;core.wsgi.application&#39;<br>ASGI_APPLICATION = &quot;core.asgi.application&quot;</pre><p>Define the subscription schema type for our subscription operation.</p><pre>type Blog{<br>  pk: Int<br>  title: String<br>  content: String<br>  author: Author<br>}<br><br><br>type Subscription {<br>  getLatestBlog: Blog<br>}</pre><p>Now, because we are operating on an ASGI server with Channels, we would have to make changes to how we interact with Django’s synchronous ORM-in an asynchronous manner. This can be done with the help of Channels’ database_sync_to_async method.</p><p>Edit our resolvers.py to include:</p><pre>from channels.db import database_sync_to_async<br>import asyncio<br><br><br>async def latest_article_generator(*_):<br>  while True:<br>    await asyncio.sleep(1)<br>    # wrapping Django ORM synchronous operation (Blog.objects.latest(&quot;title&quot;)) with<br>    # database_sync_to_async method to be executed in an asynchronous environment<br>    blog = await database_sync_to_async(Blog.objects.latest)(&quot;title&quot;)<br>    <br>    # applying the same database_sync_to_async method to get author&#39;s data<br>    author = await database_sync_to_async(lambda: blog.author)()<br>    author_details = {<br>      &quot;username&quot;: author.username,<br>      &quot;age&quot;: author.age<br>    }<br>    response = blog.__dict__<br>    response[&#39;author&#39;] = author_details<br>    yield response<br><br><br>async def resolve_get_latest_blog(response, obj):<br>  return response</pre><p>In our schema.py, edit it to include:</p><pre>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType, SubscriptionType<br><br>subscription = SubscriptionType()<br>subscription.set_source(&#39;getLatestBlog&#39;, blog_resolvers.latest_article_generator)<br>subscription.set_field(&#39;getLatestBlog&#39;, blog_resolvers.resolve_get_latest_blog)<br><br>schema = make_executable_schema(type_defs, mutation, query, subscription)</pre><p>From the above code snippets, we wrote an asynchronous generator function, latest_article_generator , that would be responsible for fetching the latest blog article from the database at a one-second interval. Once gotten, the data would be passed to any function that would need it, with the help of the yield keyword. The data is sent to the resolver function, resolve_get_latest_blog , were the response parameter is the yielded data to be delivered to the API client.</p><p>Of course, this is done with the set_source() method that sets the data source of the subcription operation, and set_field() method that sets the resolver function of the getLatestBlog field of the Subscription schema.</p><p>Start the Django server: python3 manage.py runserver, you should now see that you are running on the Daphne ASGI server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*E6eskxjODGLR8IDVQtg6RQ.png" /></figure><p>On your browser, go to the graphql/ endpoint and send the query:</p><pre>subscription LatestBlog{<br>  getLatestBlog{<br>    title<br>    content<br>    author{<br>      username<br>      age<br>    }<br>  }<br>}</pre><p>You should get a response looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*lKHFGOyC01wj-l7nbqh0Iw.png" /></figure><p>The stop button you see there tells you that you&#39;ll continuously get the latest blog response until you click it.</p><p>To test this out, we will make a little change to the resolver responsible for creating blogs, since we are now working in an asynchronous environment.</p><pre>@database_sync_to_async # new<br>def resolve_post_blog(*_, input:dict):<br>  try:<br>    author = Author.objects.get(username=input[&#39;authorUsername&#39;])<br>    blog = Blog.objects.create(title=input[&#39;title&#39;], content=input[&#39;content&#39;], author=author)<br>    blog.save()<br>    return{<br>      &quot;message&quot;: &quot;Blog posted&quot;,<br>      &quot;blog&quot;: blog<br>    }<br>  except Author.DoesNotExist:<br>    raise Exception(&quot;Author does not exist&quot;)</pre><p>Send the data query, for our “<strong>third</strong>” blog article:</p><pre>mutation{<br> postBlog(input:{<br>  authorUsername: &quot;TheAlchemist&quot;,<br>  title: &quot;My third blog&quot;<br>  content: &quot;This is my third blog, man&quot;<br> }){<br>  message<br>  blog{<br>   pk<br>   title<br>   content<br>   author{<br>    username<br>   }<br>  }<br> }<br>}</pre><p>And you should automatically see that our subscription fetches the latest blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Bj20oRXu9ZsFD7Wkc6id8w.png" /></figure><p><strong><em>In conclusion…</em></strong></p><p>Subscriptions in GraphQL provide a valuable mechanism for real-time interactivity, and with the right tools and techniques, you can leverage this feature to create dynamic and engaging applications.</p><p>So whenever you see those Twitter posts’ like count increasing automatically, just keep in mind that it could be the work of a GraphQL subscription.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e763ca33564" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling GraphQL in Django: A straightforward guide to modern API development.]]></title>
            <link>https://princeigwe.medium.com/unveiling-graphql-in-django-a-straightforward-guide-to-modern-api-development-111d390c257e?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/111d390c257e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 10:24:28 GMT</pubDate>
            <atom:updated>2023-12-19T10:24:28.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0LHtG_qCxGp36WLilxdhw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jballa?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">J. Balla Photography</a> on <a href="https://unsplash.com/photos/red-metal-bridge-over-river-6wmFPgnd__Q?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>GraphQL, a not-so-new <em>tool</em> on the block. Almost every new and old software developer has heard of it, if not played with it. As a developer who recently delved into it, I’m here to share some knowledge with you.</p><p><strong><em>The Introduction</em></strong></p><p>Facebook is credited with creating GraphQL, which consists of a runtime layer and a query language. It is a query language used on the frontend to request specific data from web APIs.</p><p>On the side of a runtime layer, it processes and validates queries against the defined data schema, that are being sent to the server, and the requested data is returned.</p><p>As a <strong>query language</strong>, it is made up of three operations:</p><ul><li><strong>Query</strong></li><li><strong>Mutation</strong></li><li><strong>Subscription</strong></li></ul><p>The query and mutation operations are used to perform actions that are analogous to HTTP verbs (POST, READ, PATCH, DELETE). The <strong>query</strong> operation works just like the <strong>HTTP-READ</strong> action, requesting data from the server, while the <strong>mutation</strong> operation is responsible for data creation and modification (<strong>HTTP-POST, PATCH, DELETE)</strong>.</p><p>For the <strong>subscription</strong> operation, think of it as the WebSocket connection for GraphQL APIs. While the <strong>query</strong> operation receives an API response after a single request, the subscription reads data continuously in real-time.</p><p>When using GraphQL, data queries can be sent using HTTP-POST or HTTP-GET actions. By now, you should realize that queries are the specific data we need from a GraphQL API.</p><p>Now, what do queries actually look like?</p><p>Let’s say we want to be greeted by a GraphQL API as soon as we wake up in the early hours of the morning. We can send a data query to the API, requesting a &quot;Hello, {first_name}, what a wonderful day to try again” message.</p><pre>{<br>  greeting{<br>    hello<br>  }<br>}</pre><p>We would get a response like this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;greeting&quot;: {<br>      &quot;hello&quot;: &quot;Hello Prince, what a wonderful day to try again&quot;<br>    }<br>  }<br>}</pre><p>We could as well send another data query to the API, requesting a “Goodbye, and take care” message.</p><pre>{<br>  greeting{<br>    goodbye<br>  }<br>}</pre><p>We would get a response like this:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;greeting&quot;: {<br>      &quot;goodbye&quot;: &quot;Goodbye, and take care&quot;<br>    }<br>  }<br>}</pre><p>While it is possible to send queries that look like this:</p><pre>{<br>  hello<br>}</pre><p>or this:</p><pre>{<br>  goodbye<br>}</pre><p>The previous examples were given to show that we can specify the data we need from the <strong>greeting</strong> <em>field</em>.</p><p>This type of request has an unnamed data query, where a certain type of operation for the request is not given. By default, this is a request using the query operation with HTTP-GET.</p><p>The <strong>greeting</strong> field is a <em>resolver</em> that leads to the <strong>hello</strong> and <strong>goodbye </strong>resolvers to fetch the data (messages) we need. This means that we can request both hello and goodbye messages at the same time.</p><pre>{<br>  greeting{<br>    hello<br>    goodbye<br>  }<br>}</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;greeting&quot;: {<br>      &quot;hello&quot;: &quot;Hello Prince, what a wonderful day to try again&quot;<br>      &quot;goodbye&quot;: &quot;Goodbye, and take care&quot;<br>    }<br>  }<br>}</pre><p>Another type of data query is one with a named operation. Here, the client gives the type of operation, along with a name, that should be performed with the HTTP-POST request. Multiple related requests can be sent at once to the API.</p><pre>query InteractWithUser{<br>  greeting{<br>    hello<br>  }<br>  <br>  assitance{<br>    checkTime<br>  }<br>}</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;greeting&quot;: {<br>      &quot;hello&quot;: &quot;Hello Prince, what a wonderful day to try again&quot;<br>    },<br>    &quot;assistance&quot;: {<br>      &quot;checkTime&quot;: &quot;The current time is 07:34 AM&quot;<br>    }<br>  }<br>}</pre><p>Now, you must have noticed the word, resolver, before reaching this point. Each field in a data query is tied to a function called a <strong>resolver</strong>. This function, implemented on the runtime layer, is responsible for defining how data is processed and presented in the API response whenever its field is called. This is where the magic is created.</p><p>On the part of the <strong>runtime layer</strong>, this is the server-side of a GraphQL application. It reads the data query requested from the query language, fetches the data from the data sources, and gives a response with the exact data that was requested, according to the <em>schema</em> that was defined.</p><p>A <strong>schema</strong> defines the structure of data that can be queried. Each schema has fields of different data types, which are referred to as <em>schema types</em>. These fields are what will be used in the query language to request the exact data needed.</p><p>A GraphQL server uses a <strong>Schema Definition Language (SDL)</strong> to define the schema of data... just as the name implies. The SDL is made up of several schema types; some of them include:</p><ul><li><strong>Scalar type</strong></li><li><strong>Object type</strong></li><li><strong>Query and Mutation types</strong></li><li><strong>Enumeration type</strong></li><li><strong>Input type</strong></li></ul><p><strong>SCALAR TYPE</strong>: This schema type is the most basic form of data. Examples include: String, Int, Float, Boolean.</p><p><strong>OBJECT TYPE:</strong> This is the schema type that represents an entity from a data source, along with the fields it has. This is the type needed by the client application. An example of such a type is:</p><pre>type Student{<br>  pk: Int<br>  name: String<br>  department: String<br>}</pre><p><strong>QUERY AND MUTATION TYPES</strong>: These are the main schemas that the query language uses to communicate with data sources in order to indicate which fields should be queried or manipulated when retrieving or storing data in a database. The Query type fetches the data needed by the client, from a data source. The Mutation type creates and modifies already-existing data in a data source. Both types operate with fields.</p><pre>type Query{<br>  students: [Students]<br>}<br><br>type Mutation{<br>  register(name: String, department: String): Student<br>}</pre><p>From the Queryschema, a list of students is returned when the students field is called. And with the Mutation schema, a student record is created and returned with the name and department arguments given in the register field.</p><p><strong>ENUMERATION TYPE,</strong> or, as sometimes I like to call it, “the schema of choice,&quot; is used to select an option from a predefined set of choices. This is effective when you want to limit the possible values for a field when working with the mutation operation.</p><pre>enum ClassLevel {<br>  JUNIOR<br>  SENIOR<br>}<br><br>type Student{<br>  pk: String<br>  name: String<br>  department: String<br>  classLevel: ClassLevel<br>}<br><br>type Mutation{<br>  register(name: String, department: String, classLevel: ClassLevel): Student<br>}</pre><p><strong>INPUT TYPE: </strong>From the last example of Enumeration type, we have a Mutation schema defined with a register field, having three arguments; name, department, and classLevel. While it is okay to pass data to a mutation with one argument after another, we can define a schema that passes this data to the operation.</p><pre>enum ClassLevel {<br>  JUNIOR<br>  SENIOR<br>}<br><br>type Student{<br>  pk: String<br>  name: String<br>  department: String<br>  classLevel: ClassLevel<br>}<br><br>input StudentInput{<br>  name: String<br>  department: String<br>  classLevel: ClassLevel<br>}<br><br>type Mutation{<br>  register(input: StudentInput): Student<br>}</pre><p><strong><em>The Analogy of GraphQL and REST</em></strong></p><p>While both API architectural styles are widely popular, GraphQL shows advantages over REST.</p><p><strong>Solving overfetching with GraphQL.</strong> GraphQL allows the client to precisely request the data needed; every other irrelevant data is omitted from the response. It minimizes unnecessary data transfers. This is not the same case with REST, as it will return all the properties of a data resource when requested.</p><p>If we had a REST endpoint that retrieved a student’s information,</p><ul><li>GET students/{name}</li></ul><p>We would get a response showing all the details of the resource without actually selecting the specific data we wanted.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;name&quot;: &quot;Isaac&quot;,<br>    &quot;department&quot;: &quot;Physics&quot;,<br>    &quot;classLevel&quot;: &quot;Junior&quot;<br>  }<br>}</pre><p>Whereas with GraphQL, we could specify that we just want the name and department information of the student.</p><pre>query {<br>  student(name: &quot;Isaac&quot;){<br>    name<br>    department<br>  }<br>}</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;student&quot;: {<br>      &quot;name&quot;: &quot;Isaac&quot;,<br>      &quot;department&quot;: &quot;Physics&quot;<br>    }<br>  }<br>}</pre><p><strong>Solving underfetching with GraphQL.</strong> Imagine a scene where our client application wants to fetch multiple pieces of information from our database, and display them on a page in our application. Let’s say:</p><ul><li>Fetching details about a student</li><li>Retrieving their course enrollment history</li><li>Obtaining information about all departments</li></ul><p>We have multiple REST endpoints that do those:</p><ul><li>GET students/{name}</li><li>GET courses-enrolled?student=Isaac</li><li>GET departments</li></ul><p>This would mean making multiple API requests with these endpoints, and combining their responses to fit our UI design.</p><p>But with GraphQL, we can send a single request to a single /graphql endpoint with a named Query operation to our API, and all the data we need will be returned.</p><pre>query PageUI{<br>  student(name: &quot;Isaac&quot;){<br>    name<br>    department<br>    classLevel<br>  }<br>  coursesEnrolled(student: &quot;Isaac&quot;){<br>    name<br>    description<br>  }<br>  departments{<br>    name<br>    headOfDepartment<br>  }<br>}</pre><pre>{<br>  &quot;data&quot;: {<br>    &quot;student&quot;: {<br>      &quot;name&quot;: &quot;Isaac&quot;,<br>      &quot;department&quot;: &quot;Physics&quot;,<br>      &quot;classLevel&quot;: &quot;Junior&quot;<br>    },<br>    &quot;coursesEnrolled&quot;: [<br>      {<br>        &quot;name&quot;: &quot;Quantum Mechanics&quot;,<br>        &quot;description&quot;: &quot;Exploring the principles of quantum physics.&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;Mathematical Methods in Physics&quot;,<br>        &quot;description&quot;: &quot;Application of mathematical techniques in solving physical problems.&quot;<br>      }<br>    ],<br>    &quot;departments&quot;: [<br>      {<br>        &quot;name&quot;: &quot;Physics&quot;,<br>        &quot;headOfDepartment&quot;: &quot;Prof. Anderson&quot;<br>      },<br>      {<br>        &quot;name&quot;: &quot;Chemistry&quot;,<br>        &quot;headOfDepartment&quot;: &quot;Dr. Brown&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>GraphQL solves the problem of making multiple API calls to get a sufficient amount of data for an application.</p><p><strong><em>Django</em></strong></p><p>“The web framework for perfectionists with deadlines&quot;... well, I’m not so sure about that statement. But we know it’s used for building full-stack web applications and RESTful APIs with the Django REST Framework. There was a time when I never thought it could build GraphQL APIs as well, until I came across <a href="https://docs.graphene-python.org/en/latest/quickstart/">Graphene</a>, a framework for building GraphQL APIs with Django. I played with it a bit on a dummy project. I thought I was enjoying it, then I came across <a href="https://ariadnegraphql.org/">Ariadne</a>, another Python framework for GraphQL with Django.</p><p>Comparing my experience with Graphene to Ariadne, I felt restricted using Graphene. It was like I had to follow a lot of rules. There were so many Python classes written for just a dummy project. Plus, it took me away from GraphQL schema types. I wanted to write my own schemas, just like I saw them in the GraphQL documentation. Graphene isn’t bad at all, but Ariadne feels better. All I have to do is define my data models, write my schemas and resolver functions, connect them to the Mutation and Query types, and make the schemas executable.</p><p>Another framework available for writing GraphQL APIs is <a href="https://strawberry.rocks/">Strawberry</a>; I&#39;ve not tried it and will not be doing so anytime soon. This article is not to convince you to pick any framework, but if you’d be following with Ariadne, this one is for you.</p><p><strong><em>Demo…</em></strong></p><p>For the sake of simplicity, the topic of authentication is outside the scope of this article. We will be creating a simple GraphQL API called <strong>Blog-QL</strong>.</p><p>Create the project directory from your terminal by running the command:</p><pre>$ mkdir blog-QL</pre><p>Open the directory with your favourite code editor. After this, create a Python virtual environment in the code directory and activate it.</p><pre>virtualenv env<br>source env/bin/activate</pre><p>Install Ariadne for Django with the command:</p><pre>(env) pip install ariadne_django</pre><p>This installs Django and Ariadne packages at once, together with other packages needed for our API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*irfCr9zRoteqofGC8Wc5tw.png" /></figure><p>Up next, create a Django project called <strong>core</strong> in the current directory:</p><pre>django-admin startproject core .</pre><p>Add the package, <strong>ariadne_django </strong>to the list of installed apps in the settings.py file:</p><pre>INSTALLED_APPS = [<br>    ...<br>    &quot;ariadne_django&quot;,<br>]</pre><p>Now we’ve installed the Ariadne package and registered it in our Django project. We now have to create a Django application, &quot;blog,&quot; with which we will be writing. We do this with the command:</p><pre>python manage.py startapp blog</pre><p>Add the blog app to the list of installed apps:</p><pre>INSTALLED_APPS = [<br>    # 3rd party apps<br>    &quot;ariadne_django&quot;,<br><br>    # local apps<br>    &quot;blog.apps.BlogConfig&quot;,<br>]</pre><p>Unlike the normal routine for building applications with Django (fullstack and REST API), where we have to create a urls.py file for each Django app created, and register it in the urlpatterns of the project’s mainurls.py file, when building a GraphQL API, “we don&#39;t do that here”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*rua9Ru6GPcgMbe666diBPg.jpeg" /></figure><p>This is because every piece of data that we will ever create and request will be done from the/graphql/ endpoint.</p><p>To get through the next stage without an error, create a schema.py file in the core’s directory. Create a dummy schema in the file and make it executable.</p><pre>from ariadne import QueryType, make_executable_schema<br><br>type_defs = &quot;&quot;&quot;<br>    type Query {<br>        hello: String!<br>    }<br>&quot;&quot;&quot;<br><br>query = QueryType()<br><br>## the decorator attaches the &quot;hello&quot; field from the Query schema<br>## to the resolver function<br>@query.field(&quot;hello&quot;)<br>def resolve_hello(*_):<br>    return &quot;Hello world!&quot;<br><br>schema = make_executable_schema(type_defs, query)</pre><p>From the code above, we defined a Query schema type, with which we would resolve the field, “hello”, to return a string value. We also defined a resolver function resolve_hello to returnHello world! whenever the “hello” field is queried. In the end, we make our schema executable with the make_executable_schema function.</p><p>Edit our core’s urls.py file to look like this:</p><pre>from django.contrib import admin<br>from django.urls import path<br>from ariadne_django.views import GraphQLView<br>from .schema import schema<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;graphql/&#39;, GraphQLView.as_view(schema=schema), name=&#39;graphql&#39;),<br>]</pre><p>We now have two endpoints, one for our admin site and the other for all GraphQL API requests. At this point, we can now test our API with the hello to see that it has been properly set.</p><p>Apply migrations for Django system apps, and start the server:</p><pre>python3 manage.py migrate<br>python3 manage.py runserver</pre><p>Send a request to the GraphQL endpoint, <a href="http://127.0.0.1:8000/graphql/">http://127.0.0.1:8000/graphql/</a> with a hello field in the query, from your API client. You should see a “Hello world!” message in the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IztLFlZL5hq82Yq1grllXg.png" /></figure><p>Now let’s flesh out our blog API. Recall that I mentioned that authentication is out of the scope of the article. So there is no password creation or validation for our author’s account.</p><p>In the models.py of our blog app, create an Author model:</p><pre>from django.db import models<br><br>class Author(models.Model):<br>  username = models.CharField(max_length=20, unique=True)<br>  age = models.PositiveIntegerField()<br><br>  def __str__(self) -&gt; str:<br>    return self.name</pre><p>A simple nameand agefield will do for our model.</p><p>Create migrations for the model and migrate:</p><pre>python3 manage.py makemigrations blog<br>python3 manage.py migrate</pre><p>In our previous code, we defined a Query schema directly in our schema.py file. While there is nothing wrong with that, we can create our schema types in GraphQL files to be called in the schema.py file. This is best for modularization, where we may have multiple schema types for multiple models, in multiple Django apps.</p><p>In the parent directory, create a folder, schemas. This will contain all GraphQL files for schemas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*grsS4LjTZfozVEnFnsSztQ.png" /></figure><p>In the folder, create a author.blog.graphql file. This will contain object schema types for our author and blog models:</p><pre>type Author{<br>  username: String<br>  age: Int<br>}<br><br>input AuthorInput{<br>  username: String!<br>  age: Int!<br>}<br><br>type AuthorResponse{<br>  message: String<br>  author: Author<br>}<br><br>type Mutation{<br>  createAuthor(input: AuthorInput): AuthorResponse<br>}<br><br>type Query{<br>  hello: String<br>}</pre><p>Here we defined an Author object schema type for our author model. We also defined an input schema type with which we would be providing data, when creating an author with the mutation operation. We would get a response containing a message and our newly created author.</p><p>Register the schemas created in the schema.py file in our core’s directory.</p><pre># core/schema.py<br>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType<br><br>type_defs = load_schema_from_path(&quot;schemas&quot;)<br><br>query = QueryType()<br>mutation = MutationType()<br><br>schema = make_executable_schema(type_defs, mutation, query)</pre><p>In the code, we imported the load_schema_from_path function that will read every schema type in every GraphQL file in the schemas directory. The QueryType and MutationType classes are responsible for our query and mutation operations, and schemas are made executable. Yeah, it’s that simple.</p><p>Let’s create our resolver function for creating an author.</p><p>In the blog’s app directory, create a resolvers.py file, which will contain all our resolver functions for the blog app.</p><pre>from .models import Author<br><br>def resolve_create_author(*_, input: dict):<br>  author = Author.objects.create(username=input[&#39;username&#39;], age=input[&#39;age&#39;])<br>  author.save()<br>  return {<br>    &quot;message&quot;: &quot;Author created&quot;,<br>    &quot;author&quot;: author<br>  }</pre><p>The resolver function takes two parameters: *_ and input .</p><p>The *prefix says that the function works with GraphQL-related parameters that don’t need to be listed as parameters. The underscore is simply a variable, which will not be used, but it represents the parent object of the function, which in this case is the mutation object.</p><p>The input parameter will be responsible for passing our data into the query for the mutation operation.</p><p>Edit our schema.py file to look like this:</p><pre>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType<br>from blog import resolvers as blog_resolvers<br><br>type_defs = load_schema_from_path(&quot;schemas&quot;)<br><br>query = QueryType()<br><br>mutation = MutationType()<br>mutation.set_field(&#39;createAuthor&#39;, blog_resolvers.resolve_create_author)<br><br>schema = make_executable_schema(type_defs, mutation, query)</pre><p>The mutation.set_field function ties our createAuthor field of the Mutation schema type to the resolver function responsible for creating an author.</p><p>Testing this on our API client, provide the data query to the GraphQL endpoint:</p><pre>mutation{<br> createAuthor(input:{<br>  username: &quot;TheAlchemist&quot;,<br>  age: 123<br> }){<br>  message<br>  author{<br>   username<br>   age<br>  }<br> }<br>}</pre><p>We should get the following response:</p><pre>{<br> &quot;data&quot;: {<br>  &quot;createAuthor&quot;: {<br>   &quot;message&quot;: &quot;Author created&quot;,<br>   &quot;author&quot;: {<br>    &quot;username&quot;: &quot;TheAlchemist&quot;,<br>    &quot;age&quot;: 123<br>   }<br>  }<br> }<br>}</pre><p>We created an author object with the input argument, which represents the input schema type, and we specified the data we needed to be returned. After we have created an author, we should create a blog for the author.</p><p>Define a blog data model in the models.py file in the blog app’s directory.</p><pre>from django.db import models<br><br>class Author(models.Model):<br>  username = models.CharField(max_length=20, unique=True, default=&quot;&quot;)<br>  age = models.PositiveIntegerField()<br><br>  def __str__(self) -&gt; str:<br>    return self.name<br><br><br>class Blog(models.Model):<br>  title = models.CharField(max_length=20)<br>  content = models.TextField()<br>  author = models.ForeignKey(Author, on_delete=models.CASCADE)<br><br>  def __str__(self) -&gt; str:<br>    return self.title</pre><p>Make migrations for the new model, and migrate:</p><pre>python3 manage.py makemigrations blog<br>python3 manage.py migrate</pre><p>Make changes to the author.blog.graphql file:</p><pre>...<br><br>type Blog{<br>  pk: Int<br>  title: String<br>  content: String<br>  author: Author<br>}<br><br>type BlogInput{<br>  authorUsername: String<br>  title: String<br>  content: String<br>}<br><br>type BlogResponse{<br>  message: String<br>  blog: Blog<br>}<br><br>type Mutation{<br>  createAuthor(input: AuthorInput): AuthorResponse<br>  postBlog(input: BlogInput): BlogResponse<br>}</pre><p>Create the resolver function for posting the blog by the author:</p><pre>def resolve_post_blog(*_, input:dict):<br>  try:<br>    author = Author.objects.get(username=input[&#39;authorUsername&#39;])<br>    blog = Blog.objects.create(title=input[&#39;title&#39;], content=input[&#39;content&#39;], author=author)<br>    blog.save()<br>    return{<br>      &quot;message&quot;: &quot;Blog posted&quot;,<br>      &quot;blog&quot;: blog<br>    }<br>  except Author.DoesNotExist:<br>    raise Exception(&quot;Author does not exist&quot;)</pre><p>Attach the resolver function to the postBlog field of our Mutation schema type in our schema.py file:</p><pre>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType<br>from blog import resolvers as blog_resolvers<br><br>type_defs = load_schema_from_path(&quot;schemas&quot;)<br><br>query = QueryType()<br><br>mutation = MutationType()<br>mutation.set_field(&#39;createAuthor&#39;, blog_resolvers.resolve_create_author)<br>mutation.set_field(&#39;postBlog&#39;, blog_resolvers.resolve_post_blog) # new<br><br>schema = make_executable_schema(type_defs, mutation, query)</pre><p>Test the update:</p><pre>mutation{<br> postBlog(input:{<br>  authorUsername: &quot;TheAlchemist&quot;,<br>  title: &quot;My first blog&quot;<br>  content: &quot;This is my first blog, man&quot;<br> }){<br>  message<br>  blog{<br>   pk<br>   title<br>   content<br>   author{<br>    username<br>   }<br>  }<br> }<br>}</pre><p>The response would be:</p><pre>{<br> &quot;data&quot;: {<br>  &quot;postBlog&quot;: {<br>   &quot;message&quot;: &quot;Blog posted&quot;,<br>   &quot;blog&quot;: {<br>    &quot;pk&quot;: 1,<br>    &quot;title&quot;: &quot;My first blog&quot;,<br>    &quot;content&quot;: &quot;This is my first blog, man&quot;,<br>    &quot;author&quot;: {<br>     &quot;username&quot;: &quot;TheAlchemist&quot;<br>    }<br>   }<br>  }<br> }<br>}</pre><p>Having played with the mutation operation a little, let’s work on the query operation.</p><p>Make some changes to the author.blog.graphql file:</p><pre>type BlogsResponse{<br>  message: String<br>  blogs: [Blog]<br>}<br><br><br>type Query{<br>  getBlogs: BlogsResponse<br>}</pre><p>Create the resolver function for getting all blogs:</p><pre>def resolve_get_blogs(*_):<br>  blogs = Blog.objects.all()<br>  return {<br>    &quot;message&quot;: &quot;Blog-QL blogs&quot;,<br>    &quot;blogs&quot;: blogs<br>  }</pre><p>Attach the resolver function to the getBlogs field of the Query schema type:</p><pre>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType<br>from blog import resolvers as blog_resolvers<br><br>type_defs = load_schema_from_path(&quot;schemas&quot;)<br><br>query = QueryType()<br><br>mutation = MutationType()<br>mutation.set_field(&#39;createAuthor&#39;, blog_resolvers.resolve_create_author)<br>mutation.set_field(&#39;postBlog&#39;, blog_resolvers.resolve_post_blog)<br><br>query.set_field(&#39;getBlogs&#39;, blog_resolvers.resolve_get_blogs) # new<br><br>schema = make_executable_schema(type_defs, mutation, query)</pre><p>Test the update:</p><pre>query{<br> getBlogs{<br>  message<br>  blogs{<br>   pk<br>   title<br>   content<br>  }<br> }<br>}</pre><p>We would get the following response:</p><pre>{<br> &quot;data&quot;: {<br>  &quot;getBlogs&quot;: {<br>   &quot;message&quot;: &quot;Blog-QL blogs&quot;,<br>   &quot;blogs&quot;: [<br>    {<br>     &quot;pk&quot;: 1,<br>     &quot;title&quot;: &quot;My first blog&quot;,<br>     &quot;content&quot;: &quot;This is my first blog, man&quot;<br>    },<br>    {<br>     &quot;pk&quot;: 2,<br>     &quot;title&quot;: &quot;My second blog&quot;,<br>     &quot;content&quot;: &quot;This is my second blog, man&quot;<br>    }<br>   ]<br>  }<br> }<br>}</pre><p>What if we wanted to fetch a single blog? Just like the mutation operation, the query operation also works with arguments, but this time for data fetching.</p><pre>type Query{<br>  getBlogs: BlogsResponse<br>  getBlog(pk: Int): BlogResponse<br>}</pre><p>Create a resolver function for fetching a single blog article:</p><pre>def resolve_get_blog(*_, pk):<br>  try:<br>    blog = Blog.objects.get(id=pk)<br>    return{<br>      &quot;message&quot;: f&quot;Article {blog.id}&quot;,<br>      &quot;blog&quot;: blog<br>    }<br>  except Blog.DoesNotExist:<br>    raise Exception(&quot;Blog does not exist&quot;)</pre><p>Attach the resolver function to the getBlog field of the Query schema type:</p><pre>from ariadne import QueryType, make_executable_schema, load_schema_from_path, MutationType<br>from blog import resolvers as blog_resolvers<br><br>type_defs = load_schema_from_path(&quot;schemas&quot;)<br><br>query = QueryType()<br><br>mutation = MutationType()<br>mutation.set_field(&#39;createAuthor&#39;, blog_resolvers.resolve_create_author)<br>mutation.set_field(&#39;postBlog&#39;, blog_resolvers.resolve_post_blog)<br><br>query.set_field(&#39;getBlogs&#39;, blog_resolvers.resolve_get_blogs)<br>query.set_field(&#39;getBlog&#39;, blog_resolvers.resolve_get_blog) # new<br><br>schema = make_executable_schema(type_defs, mutation, query)</pre><p>Test the update:</p><pre>query{<br> getBlog(pk:2){<br>  message<br>  blog{<br>   title<br>   content<br>   author{<br>    username<br>   }<br>  }<br> }<br>}</pre><p>The response would be:</p><pre>{<br> &quot;data&quot;: {<br>  &quot;getBlog&quot;: {<br>   &quot;message&quot;: &quot;Article 2&quot;,<br>   &quot;blog&quot;: {<br>    &quot;title&quot;: &quot;My second blog&quot;,<br>    &quot;content&quot;: &quot;This is my second blog, man&quot;,<br>    &quot;author&quot;: {<br>     &quot;username&quot;: &quot;TheAlchemist&quot;<br>    }<br>   }<br>  }<br> }<br>}</pre><p><strong><em>Conclusion</em></strong></p><p>In this guide, we’ve journeyed through the integration of GraphQL in Django, exploring the fundamental concepts, setting up the environment, and showcasing a hands-on demo. As we wrap up, let’s recap the key points and emphasize the significance of GraphQL in modern API development with Django.</p><p><strong>Understanding the Shift to GraphQL</strong>: We’ve seen how GraphQL differs from traditional REST APIs, offering flexibility and efficiency in data retrieval. The ability to request only the required data empowers clients and optimizes performance.</p><p><strong>Practical Implementation</strong>: Through our demonstration, you’ve witnessed the practical side of incorporating GraphQL into a Django project. From defining schemas to executing queries and mutations, you now have a foundation for building robust APIs with Django and GraphQL.</p><p>To wrap up, combining Django with GraphQL brings a fresh breeze to API development. So, go ahead, infuse your Django projects with the GraphQL mojo, and watch as your coding efforts spark new innovations.</p><p>Happy coding, and may your projects be as smooth as a well-written line of code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=111d390c257e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Care Through Technology: Unveiling the Story Behind My Health Tech Project.]]></title>
            <link>https://princeigwe.medium.com/empowering-care-through-technology-unveiling-the-story-behind-my-health-tech-project-b1e6d7be61ea?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1e6d7be61ea</guid>
            <category><![CDATA[telemedicine]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[healthtech]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 14:38:59 GMT</pubDate>
            <atom:updated>2023-06-12T14:43:01.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txbHC_wyLu-qhDbRXpgueA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@an_ku_sh?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ankush Minda</a> on <a href="https://unsplash.com/s/photos/health-technology?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>With great power comes great responsibility — Uncle Ben</blockquote><p>Being a health care worker sure comes with great responsibility, and that comes with prestige, pride and honour. Like the normal parent-child relationship on the topic of education and career, as a little boy, my dad would always tell me that I would be a doctor, or suggest I study medicine in the university. Yep, I’m one of those children. However, he didn’t just suggest this career path to me, he gave me a reason as well, which was to save lives. So it was like, “save lives first, then you will be respected”. From then on, I would always tell myself I’d be a medical doctor, and I went through most of my time in junior secondary school wanting to practice medicine. Now I wasn’t the A-grade student, but I knew my basic science stuff.</p><p>That when on, until a major event happened in my life, as doctors tried to save me. This resulted to me losing one year of my life, before continuing with senior secondary school. After I recovered, I wasn’t so sure of becoming a medical doctor any longer, because of the images that were imprinted on my memory. I wasn’t sure I was emotionally strong enough to handle what I saw while in the hospital, as a medical doctor. So I was left without a plan for my career.</p><p>I went through senior secondary school as a science student, I still loved science subjects. During this time, I started developing interest in computers. As of then, this was strange for me, because I was not comfortable with computers during my earlier years in primary school; as I would always mess up whenever there was some type of class activity that involved computers. Funny enough, my senior school didn’t offer any curriculum on computers or IT, so I was left with no choice but to get a computer textbook and study on my own whenever there was a free period. The textbook mostly contained information on computer hardware parts, and some basic binary computations. Fast forward to some years later, I started developing interest in backend development with Django web framework in the university.</p><p>One of my first few projects built with the framework was similar to <a href="https://github.com/Princeigwe/Elixir.io">Elixir</a>, it was called “LifeBar”. At the time of writing this particular line, I looked up the private repo with the intention of laughing at it, but I was shocked to see that I really worked on it with my very little knowledge of programming at that time (sike😅). You know that saying that goes like, “that idea you have, 100 people have already worked on it”, that was the case here. I was building something that was related to the health-tech space, without realizing that applications like that even existed. I’m not even sure I knew the word “health-tech” existed, as of that time. <em>So when next you have that idea, just build it</em>. After some time, I closed up the project and left it, waiting for the next idea to hit me.</p><p>Fast forward to some time again, I picked up the Nest.js framework. I wanted to try something new. <em>By the way, if you want to read about my first experience with the framework, you can check it out </em><a href="https://princeigwe.medium.com/i-wrote-a-rest-api-with-typescript-heres-the-story-b1a0b5afdf27"><em>here</em></a>. During one of the breaks I had while building my first Nest.js project, I suddenly had a slight interest in the human physiology, that I just wanted to read up on it. <em>You may now say I started developing interest in medicine again… yeah, probably. </em>One time<em>,</em> while reading an article on physiology, I came across the word, “telemedicine”. At first glance, I thought it was a psychic super-hero ability, you know, like telepathy, telekinesis, teleportation and every other “tele-powers” you can think of.</p><p>After reading a little about the word and its field, I realized that LifeBar was in the health-tech space. However, I developed a strong interest in this space and became determined to create something even better. It was during this time, while working on my first Nest.js project, that the idea for <a href="https://github.com/Princeigwe/Elixir.io">Elixir.io</a> was conceived. Elixir is just an API, but initially, I wanted to build it as a complete software product, you know, with the backend and the frontend, and maybe a mobile app version. So I searched for people that would want to collaborate with me. I asked friends, close friends, strangers on LinkedIn, Slack communities, and Discord servers. I got response from some people, but nothing really happened after that. So I figured they were probably just busy with other areas of their lives, and I took the idea back to just becoming an API. At this point I felt like a failed startup founder 😅. With very limited knowledge on healthcare and health-tech, I made ChatGPT and Google my guides. I got better insights on areas I wasn’t so sure of, got ideas to try and work on, from healthcare companies that were making it in the space.</p><p><em>Now, I bring you to…</em></p><p><strong>ELIXIR.IO</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsciHAHjqkRrV077_oHgWg.png" /></figure><p>Elixir is an API that targets the healthcare industry, built with the patient’s experience in mind. Just as students tend to understand a topic faster if the teacher makes great effort in carrying them along, same way, patients may get to heal faster if medical providers carry them along, through the healing process.</p><p>Patient engagement creates room for effective communication between them and their healthcare providers, which allows the patient express their concerns, ask questions, and provide valuable insights about their health. It also allows healthcare providers to tailor their treatment approach to the patient’s specific needs. This can later build trust between the patient and their healthcare provider, easing the healing process. This is the idea behind Elixir.</p><p>In order to empower patient engagement and enhance the healthcare experience, Elixir provides a range of features designed to optimize communication and foster meaningful patient-provider interactions. To utilize these features, both parties would have to be registered on the API. While this API mainly involves both users, a third administrative user can also be registered to oversee the operations happening on the API. The administrator is also responsible for creating medical departments on the API, with which the details of the medical provider will be created and saved.</p><p>Elixir offers a real-time messaging capability that enables communication between patients and their healthcare providers. This allows patients to easily reach out to their providers, ask questions, share and updates all within a secure and private environment. In addition to messaging, the API offers appointment management functionalities, allowing patients to schedule, reschedule, cancel, or confirm appointments with ease. It provides automated notifications, ensuring timely and relevant updates are delivered to healthcare providers and patients alike, enhancing communication efficiency and facilitating informed decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*CvBRJE2kjs3mEb2cgeo2zg.jpeg" /><figcaption>SMS notification on rescheduled appointment</figcaption></figure><p>Additionally, the API offers a stream call feature, enabling virtual consultations between healthcare providers and patients. This feature allows real-time, face-to-face interactions regardless of geographical locations.</p><p>While interoperability with external systems is outside the scope of the Elixir project, it offers a secure solution for managing patient records within its EHR system. With Elixir, medical records, prescriptions, and progress notes are encrypted in the database, ensuring data privacy and protection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdjkA1riqhMAjl9Vqcpncw.png" /><figcaption>Encrypted medical record on database vs Decrypted data for authorized user</figcaption></figure><p>One feature of the API is the ability for patients to grant read access to specific healthcare providers on the platform. This means that patients have control over who can access their records, enabling them to share vital information with other healthcare professionals involved in their care. By selectively granting access, patients can facilitate collaboration and ensure comprehensive medical decision-making. Granting read access of a medical record to a healthcare provider automatically grants read access to other data in the EHR system.</p><p>If you’re interested in exploring Elixir further and diving into its capabilities, I invite you to visit the comprehensive documentation <a href="https://the-bubble.gitbook.io/elixir.io-documentation/">site</a>. There, you’ll find detailed information about the API’s features. A demo <a href="https://vimeo.com/835237320?share=copy">video</a> is provided as well.</p><p><strong>TECHNOLOGIES UTILIZED</strong></p><ol><li>Nest.js: A progressive Node.js framework for building efficient and scalable server-side applications.</li><li>Docker: A tool that allows you to build, package, and distribute your applications as containers, ensuring consistency across different environments.</li><li>CircleCI: A continuous integration and delivery platform that automates the build, test, and deployment processes of your application.</li><li>MongoDB: A popular NoSQL database that provides a flexible and scalable data storage solution for your application.</li><li><a href="http://socket.io/">Socket.io</a>: A library that enables real-time, bidirectional communication between the client and the server, allowing for instant updates and notifications.</li><li>Redis: An in-memory data structure store that can be used as a cache or a message broker, enhancing the performance and scalability of your application.</li><li>Vonage: A communication platform that provides APIs for sending SMS, making voice and video calls, and handling other communication functionalities in your application.</li><li>Daily: A service that offers real-time video and audio communication capabilities through WebRTC, allowing for seamless video conferencing and collaboration.</li><li>Auth0: A flexible and secure authentication and authorization platform that simplifies the implementation of user authentication and access control in your application.</li></ol><p><strong>PASSION ABOUT HEALTHCARE INNOVATION: TECHNOLOGY AS A CATALYST</strong></p><p>For me, this project was not an easy one. I must admit that there were days I wanted to give up on it and start a new one, you know, that’s what some programmers do, right? Some days I lost the motivation to write code, some days I was just busy with school and other things. Other days, I was stuck with bugs that made me feel lonely, as it was difficult to find solutions to them, but I knew what I was building. I knew the idea had value, so I couldn’t just give up on it like that, even after all the time I already spent on it.</p><p>Throughout my journey of developing the Elixir project, I have gained a deep appreciation for the immense value that technology can bring to the healthcare industry. It has ignited a passion within me for the intersection of technology and healthcare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*pMqEe8ySduksfyzDR4i1nQ.png" /></figure><p>While Elixir is a side project, its potential in the healthcare industry have sparked a passion within me for technology-driven healthcare innovation. Although it may not have the scale of a large-scale enterprise solution, its significance lies in the ideas and concepts it represents. Building this project has allowed me to explore the possibilities of leveraging technology to improve healthcare delivery and patient outcomes.</p><p>As a technologist with a keen interest in healthcare, I am eager to further explore opportunities to contribute to a larger healthcare ecosystem. If you share a similar passion for leveraging technology to drive healthcare innovation, I would be delighted to connect with you. Whether it’s discussing ideas, exploring collaborations, or simply exchanging insights.</p><p>Please feel free to reach out to me on <a href="https://www.linkedin.com/in/prince-igwenagha">LinkedIn</a> or <a href="https://twitter.com/IgwePrince0">Twitter</a>. See you next time.</p><p>Till then, keep building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1e6d7be61ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Integration and Continuous Delivery with CircleCI and NestJS]]></title>
            <link>https://princeigwe.medium.com/continuous-integration-and-continuous-delivery-with-circleci-and-nestjs-861544d316fc?source=rss-99759e6df3d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/861544d316fc</guid>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Prince Igwenagha]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 12:39:34 GMT</pubDate>
            <atom:updated>2023-03-25T18:55:03.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3oGQ2qQEUy2ALcXH0njKqA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mohammad Rahmani</a> on <a href="https://unsplash.com/photos/Y5yxdx2a4PI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote><em>“Investing in yourself is the best investment you will ever make. It will not only improve your life, it will improve the lives of all those around you.” — Robin S. Sharma</em></blockquote><p><em>A little storytelling…</em></p><p>As a software developer, I understand the importance of upskilling oneself, especially in a fast moving industry like the tech industry. I believe that once you stop learning, the world just leaves you behind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*86hZIZ_KlB76pEcEDhIw8g.png" /></figure><p>After I built my first project with the NestJS framework, I enjoyed what I had achieved to the point of writing an article about my experience. I won’t say the project is a fully developed API, but learning a new language and a framework was a win for me. If you’re interested in the article on the experience, here it is:</p><p><a href="https://princeigwe.medium.com/i-wrote-a-rest-api-with-typescript-heres-the-story-b1a0b5afdf27">I wrote a REST API with TypeScript… here’s the story.</a></p><p>After I was done with the project, I decided I was going to build another one with Nest that was a little bit more complex, and also learn at least one technology on the side. I’m working on that second project at the time of writing this article. So I have been hearing about this thing called CI/CD, even while I was writing the previous NestJS project.</p><p>Backend gurus were always talking about it on Twitter, YouTube, blog articles, and everywhere else. I decided I was going to learn it for my next project, which is my current one. I read some articles on the topic and learned that there are different platforms for CI/CD: Jenkins, TravisCI, CircleCI, and GitLab CI/CD.</p><p>The first platform I tried to learn was Jenkins. Did I succeed in learning it? Absolutely not. Jenkins looked so complicated to me; different articles told me different things when I started out with it. Some said I should install some packages in order to use it, and some gave different configurations. I was very confused; it was like learning Java, so I had to drop it and try another. I tried to learn Travis CI; I can’t really remember my experience with it, but I remember dropping it because I read somewhere that I had to pay for something. I can’t really remember what that was. For GitLab CI/CD, I figured I had to use GitLab to use its CI/CD feature, and I was using GitHub, so that was the end for GitLab.</p><p>CircleCI was my last option then, because I didn’t even think of GitHub Actions. I knew CircleCI was it when I watched their YouTube introductory video at that time. The animation and the voice of the presenter were soothing. Yeah, I judged a book by its cover. I was even more convinced to try CircleCI when I opened its documentation page; it was clean. I learned the basics and applied them to my project, and that’s what I’m about to share with you.</p><p>To follow along with this article, here are the requirements.</p><ul><li>CircleCI account</li><li>Git and GitHub account</li><li>Docker (Optional)</li><li>DockerHub account</li><li>NestJs</li><li>Jest</li></ul><p><strong>Introduction to CI/CD</strong></p><p>Before I give details on how to use CircleCI in your own Nest project, let’s go back to the basics. It all starts with the definition of CI/CD. CI/CD is the acronym for Continuous Integration/Continuous Delivery (or Deployment).</p><p>The &quot;CI&quot; part of it is a software development practice that integrates code changes to a repository on a frequent basis, meaning that a developer or group of developers continuously adds or edits code to get the defined software that is needed, to a repository that stores that code, until the “perfect” software is created. This practice involves the automated building and testing of source code once a commit is made to the repository.</p><p>For the “CD” part, there are two sides to it: Continuous Delivery and Continuous Deployment, so it depends on which one you choose to work with on your application. Continuous Delivery is simply the manual process of moving your code from the development environment to the staging or production environment, after successful builds and tests. This means that after you’ve added your code for whatever feature, you build and test it with a CI/CD platform. If all goes well, you will then take that software and manually configure it for a different environment that is not the development environment. Continuous Deployment is the exact opposite. While Continuous Delivery involves human interaction with a software for the production release, Continuous Deployment is totally automated. This means that once all tests are passed, it is automatically deployed to the production environment.</p><p><strong>Automating Tests with Nest and Jest</strong></p><p><em>sweet rhymes</em></p><p>Automated testing is the type of software testing that is done by running scripts to ensure that software meets its requirements and exhibits the behavior that’s needed from it. There are frameworks that can help one run automated tests, and this is based on the programming language that is being used to build your software. With Python, there are unittest and pytest. With JavaScript/Typescript, we have Jest, Mocha, and so many of them. For the nature of this article, we will be focusing of Jest.</p><p>For a framework like Nest, it comes with Jest out of the box, meaning that you do not have to install it in order to run automated tests. Jest automatically runs tests from files that have a suffix of <strong>.spec</strong> or <strong>.test</strong>. Running tests with Jest can be done with the command:</p><pre>npm run test</pre><p>However, if you want to run your test in watch mode, which automatically runs tests in real time as changes occur, you can use the command:</p><pre>npm run test:watch</pre><p><strong>Unit Test Demonstration:</strong></p><p>I created a dummy <a href="https://github.com/Princeigwe/Blog-Demo">blog API</a> to demonstrate this. The API is hooked up to a PostgreSQL database to create and read a single blog resource.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc7d7af60546675771116f48d8105e6/href">https://medium.com/media/4cc7d7af60546675771116f48d8105e6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9b39291ae3eff64fe578d7f395bfa33/href">https://medium.com/media/c9b39291ae3eff64fe578d7f395bfa33/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/475ec486ebd9e68c8914a9d99ed24480/href">https://medium.com/media/475ec486ebd9e68c8914a9d99ed24480/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZjBXqer6yRV2PoxopOT7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PN__QzOJMfRTKYwf29cdAQ.png" /></figure><p>One thing I love about Nest when it comes to testing, is that it automatically creates test files for your providers and controllers. That way, you don’t have to bother so much about structuring your tests. For the blog’s service and controller, there are “blog.service.spec.ts” and “blog.controller.spec.ts” files, respectively. Running the test command, you will get the following error messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFepvIAqq5QScnypMYypFg.png" /></figure><p>This is because both the service and controller classes have dependencies initialized in them, and these dependencies are not found in their respective test files. For the blog.controller.spec.ts file, we see that the blog service dependency is missing, and for the blog.service.spec.ts, we see that the blog repository dependency is missing. One of the best ways to fix this issue is by mocking those dependencies. This way, you provide fake versions of those dependencies without relying on the actual dependencies for your tests.</p><p>For the mocked repository dependency of <strong>blog.service.spec.ts</strong>, you can have something similar to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cffab3bd498cfdac57bdaef43d005b1a/href">https://medium.com/media/cffab3bd498cfdac57bdaef43d005b1a/href</a></iframe><p>And for the mocked service dependency of <strong>blog.controller.spec.ts</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9261b1b16c61fd73d9e48359e4f6cc0e/href">https://medium.com/media/9261b1b16c61fd73d9e48359e4f6cc0e/href</a></iframe><p>Running the test command again, you will see that all tests get passed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*TxYX88egqw5I2X8s_PJDSg.png" /></figure><p>With this little demonstration, one can add custom tests to the foundation already provided by the NestJS framework.</p><p><strong>The World of CircleCI</strong></p><p>In order to use CircleCI on your project, you should have at least a basic understanding of the platform. It is simply a tool that automates the build, test, and delivery/deployment processes. Yes, you can run your tests on your local machine, but it is also advisable to add tests to your CI/CD pipeline. CircleCI is made up of several components that help execute CI and CD processes. Some of the basic components includes:</p><ul><li>Pipeline</li><li>Jobs</li><li>Steps</li><li>Commands</li><li>Executors</li><li>Workflows</li></ul><p><strong>Pipeline:</strong> A pipeline is a set of automated development procedures that take place on a CI/CD platform. It is made of build, test, and delivery/deployment processes. The platform compiles the software into executable code so that tests can be run, and then deployed to a remote environment.</p><p><strong>Job: </strong>A job is a collection of steps that run required commands and scripts within a given executor and are orchestrated using workflows.</p><p><strong>Step:</strong> A step is simply the collection of executable commands.</p><p><strong>Executor:</strong> In CircleCI, an executor is an execution environment, in which jobs are executed. Different types of executors include:</p><ul><li>Docker</li><li>MacOS</li><li>Windows</li><li>Machine</li></ul><p>With the Docker executor, you can containerize your application and push it to any container registry of your choice, right from CircleCI.</p><p><strong>Workflow: </strong>The workflow is the component of CircleCI that orchestrates and manages jobs. With it, you can define the order in which you want jobs to be executed. Look at it as the Kubernetes of jobs.</p><p>There are a lot of CircleCI components, but with these very few, you can apply the CI/CD principle to your project.</p><p><strong>Setting up CircleCI</strong></p><p>Like I mentioned earlier, you will need a CircleCI account to use it on your project. This can be done by following this <a href="https://circleci.com/signup/">link</a>. It should take you to a page similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDNNCBbVetfq-Jp-yzfv-A.png" /></figure><p>Signing up with your favourite Git hosting service allows the CircleCI server to have access to the repositories it will be working with. This access is necessary for CircleCI to build and test your code, as well as to deploy it to a remote environment.</p><p>After creating an account, you should see a list of projects (repositories) from your Git hosting service. Choose the one you want to work with, and set up the project with CircleCI. In my case, it is “Blog-Demo”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PwCjwWHwNC0O3xzdZhgQw.png" /></figure><p>To define a CI/CD pipeline on CircleCI, you will need a <strong>config.yml</strong> file. This can be done in any of the 3 ways as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*aXcWV1f3kP7Zzp78kd3E_Q.png" /></figure><p>Personally I prefer a manual setup of a <strong>config.yml</strong> file, because CircleCI said it is the fastest way… yeah. But also because I can choose to set up my pipeline however I want, from scratch. You can choose whatever method you want, and it will work just fine.</p><p>If you choose the “fastest” way, you will need to create a <strong>config.yml </strong>in the root directory of your project. This is how it is done:</p><ol><li>Create a folder called <strong>.circleci </strong>in the root directory.</li><li>Create a file in that folder, and name it <strong>config.yml</strong></li></ol><p>The file structure should be similar to what is in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*ljLcnai5aGOpJI3yh73gdQ.png" /></figure><p>Here is an example of what your config.yml file can contain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9253c1336e636531055b01ebaf018715/href">https://medium.com/media/9253c1336e636531055b01ebaf018715/href</a></iframe><p>From the above configuration, we are working with CircleCI version 2.1. A job named “blog_demo_deployment_process” is created, and it uses the Docker executor with a Docker NodeJs image provided by CircleCI. This is similar to running an application in Docker with a NodeJs base image, in your local machine. You can see a list of all CircleCI Docker images by following the link below:</p><p><a href="https://circleci.com/developer/images">Images</a></p><p>The job then builds your application by git cloning the updated code repository into the CircleCI environment with the “checkout” property, every time you push a commit to the repository. The latest npm version is then installed in the environment with the “npm update” step.</p><pre>sudo npm install -g npm@latest</pre><p>All automated tests in the code repository are then executed with the “run automated tests” step.</p><pre>npm run test</pre><p>The <strong>workflows </strong>section contains the workflow named &quot;blog-demo&quot;, which lists the jobs it contains. In this case, it only has the “blog_demo_deployment_process” job.</p><p>The next step is to push the config file to the Git hosting service. Then go to the CircleCI projects dashboard again and set up the project. Choose the fastest option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*eg-1Vv4putpFb035-cQVkw.png" /></figure><p>From the image above, I created a CircleCI config file on the testing branch. It can be on whatever branch of your choice. Click set up project button.</p><p>You should see a page that looks like the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxyIFi6W2FmZx8FIV8RlXg.png" /></figure><p>One feature CircleCI has is that whenever a pipeline fails, maybe as a result of packages not being installed or failed tests, you get an email notification telling you that the pipeline failed.</p><p>Clicking on a failed pipeline, you can see that the process for running tests failed because the Jest framework is not installed in the CircleCI environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF5RrZN9nzwrchhGNvuXxg.png" /></figure><p>This may not be the same case for everyone, but to fix this issue, you will have to add the command that installs Jest, to the <strong>config.yml</strong> file. This is the version of the config.yml file that works out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37f6b9d72427ebc2116d78742c433353/href">https://medium.com/media/37f6b9d72427ebc2116d78742c433353/href</a></iframe><p>Create a commit, push it, and you should see a clean pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZyle_fEzNVNsQqN3-GKPg.png" /></figure><p>Here is one thing you should know: sometimes your pipeline may fail because of an error in the config file. With the CircleCI CLI, you can validate your pipeline configuration before pushing it to your Git hosting service. This can be done with the command:</p><pre>circleci config validate</pre><p>To install the CLI on your local machine, click the following link:</p><p><a href="https://circleci.com/docs/local-cli/">Installing the CircleCI local CLI - CircleCI</a></p><p>So far, our pipeline has only been able to build and test the blog-demo API, but we need it to deploy the code to a remote environment, for it to be complete. In this case, we’ll be delivering the code to DockerHub. Yeah, this is where you need a DockerHub account.</p><p>To containerize and push an application to DockerHub, one needs to build a Docker image of it, login to the DockerHub account from Docker, and push the image. But how can you do this? This is where another useful component of CircleCI comes in: <strong>Contexts</strong>.</p><p>Contexts provide a way to use environment variables in the <strong>config.yml</strong> file. These contexts are defined in the CircleCI web application and then called in the config file by using the context key in the workflow section, to be used in the build process on the CircleCI server. With context environment variables, you can add your DockerHub authentication credentials, which will enable CircleCI to push your image to DockerHub.</p><p><strong>Steps in Creating a Context</strong></p><ol><li>Right on the side navigation panel, you should see an “Organization Settings” label, click it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*vDTINARDijncX36-ftLBPg.png" /></figure><p>2. This should take you to another page that has “Contexts” also on the navigation panel. Click it.</p><p>3. Create a context by clicking the “Create Context” button, and use a unique name for it. After creating the context, you should see it in the Contexts list. Click it.</p><p>4. Click the Add Environment Variable button to add an environment variable to the context, provide the details, then click the Add Variable button to save. You will need to add two environment variables named <strong>DOCKERHUB_USERNAME</strong> and <strong>DOCKERHUB_PASSWORD</strong>, or however you want to name them. These are your DockerHub credentials.</p><p>Next you will have to update your CircleCI <strong>config.yml</strong> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865f6652cbe36ca70095d6d343ab05e7/href">https://medium.com/media/865f6652cbe36ca70095d6d343ab05e7/href</a></iframe><p>In the above configuration, we added our DockerHub credentials to the <strong>auth</strong> property of the NodeJS Docker image. Down at the bottom of the file, you are telling CircleCI the context in which it should read your credentials. Now that the credentials have been provided, you can now deploy to DockerHub.</p><p>Update your config file to look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba3a715b3dc7193770ed23341b7337d1/href">https://medium.com/media/ba3a715b3dc7193770ed23341b7337d1/href</a></iframe><p>In the above configuration, a new property, <strong>setup_remote_docker</strong>, was added. This is the property that helps you run Docker commands in the executor. This property has a child property, <strong>docker_layer_caching, </strong>which is set to <strong>true</strong>. With this property, your Dockerfile is cached in the job. This means that if there are no changes in the Dockerfile, the image will be rebuilt from the previous build thanks to cache. This minimizes the amount of time needed to build the image.</p><p>In the “Build and Push Docker Image” step, the image is built and tagged in the current directory. Docker logs in to your DockerHub account with the credentials you provided, and you push that image to your account.</p><p>Create a commit, push it, and you should see a clean pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1poKaVkNoB6cI3_axBqDKg.png" /></figure><p>Open your DockerHub account, and you should see your newly deployed image.</p><p>Following this article, I pushed the image from the <strong>testing</strong> branch. But what if you only wanted to build and run tests in the branch and then push the image from the main branch when you accepted a pull request? Is that possible? Yes, it is, with conditional branching.</p><p>This is how the config file should look, if you wanted to do something like that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/333c72651de65168a6c422d67517cf31/href">https://medium.com/media/333c72651de65168a6c422d67517cf31/href</a></iframe><p>In the above configuration, the image is built and pushed only if it was the <strong>main</strong> branch that triggered it, with <a href="https://circleci.com/docs/pipeline-variables/#pipeline-values"><strong>pipeline values and parameters</strong></a>.</p><p>Create a commit, push it, and you should see a result similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdrtmMYonHLn04_yAgBajQ.png" /></figure><p>You will see that the pipeline process stopped at running automated tests on the <strong>testing</strong> branch.</p><p>Create a pull request to the <strong>main</strong> branch and merge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*UbEfa4LwvuMU15RTiLK9yA.png" /></figure><p>This triggers the pipeline, and you should see your result, right on the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNFQEcAJEOaSHzd_EuuQHQ.png" /></figure><p>In conclusion, Continuous Integration and Continuous Delivery are practices that help teams streamline their software development process by automating the building, testing, and deployment of code changes. By doing so, teams can detect and fix issues early on, reduce the risk of errors in production, and deliver new features and updates faster and more reliably to users. With the help of tools like CircleCI and Docker, implementing these practices can be made easier and more efficient.</p><p>Please feel free to reach out to me on <a href="https://www.linkedin.com/in/prince-igwenagha">LinkedIn</a> or <a href="https://twitter.com/IgwePrince0">Twitter</a>. See you next time.</p><p>Till then, keep coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861544d316fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>