<?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 Baimam Boukar Jean Jacques on Medium]]></title>
        <description><![CDATA[Stories by Baimam Boukar Jean Jacques on Medium]]></description>
        <link>https://medium.com/@baimamboukar?source=rss-4b502c30518------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7kWKj5RtzcMkpWQplxe1fw.jpeg</url>
            <title>Stories by Baimam Boukar Jean Jacques on Medium</title>
            <link>https://medium.com/@baimamboukar?source=rss-4b502c30518------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:09:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baimamboukar/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[The Inevitable Cycle In Morality]]></title>
            <link>https://baimamboukar.medium.com/the-inevitable-cycle-in-morality-88fd38e08cc6?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/88fd38e08cc6</guid>
            <category><![CDATA[totalitarianism]]></category>
            <category><![CDATA[moral-relativism]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[philosophy-of-life]]></category>
            <category><![CDATA[moral-philosophy]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 06:10:21 GMT</pubDate>
            <atom:updated>2026-06-19T02:13:56.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8STTJiE8GqDMh9hEslzjw.png" /><figcaption>The Moral Pendulum</figcaption></figure><p><strong><em>People often begin by saying morality is relative, but when something deeply important to them is challenged, they suddenly appeal to moral absolutes.</em></strong></p><h3>TL;DR</h3><p>After many conversations about the most pressing debates in today’s Western world , I have come to realize how difficult it is for people to arrive at a shared moral ground. What is even more interesting is the paradox at the center of these exchanges. <strong>We often speak as like morality can be negotiated. But we defend our own moral convictions as if they were unquestionable universal truths.</strong></p><h3>1. We Are All Stuck In The Cycle</h3><p>So there are people who think that</p><p><strong>1. Everyone should believe in what they personally find morally acceptable, or what “pleases” them (1)</strong>. But this directly makes morality relative. What makes it complex is that, when our definition of morality becomes relative, we are giving everyone else the chance of disagreeing with our morale, and we should eventually accept it if they do disagree.</p><p><strong>2.⁠ ⁠But the moment they tell us that what we see as good is evil to them, we are shocked. We start defending our morality from the stand that they are wrong (2). </strong>In that moment, we effortlessly switch from a relative to an absolute definition of morale. And If we fail imposing our moral view because others are not willing to accept it, we resent. From there, this resentment grows, and</p><p><strong>3.⁠ ⁠This takes us back to the initial position </strong>(1)<strong>, </strong>the desire to let everyone have their own moral view. <strong>Then we find ourselves locked in a cycle. </strong>We move from relativism to absolutism, again, and again. It is difficult to realize it, but morality becomes like a pendulum.</p><p>This brings a more fundamental question at the center of the stage. <strong><em>Is the cycle itself the problem? Well, maybe, maybe not.</em></strong></p><h3>2. Perhaps The Cycle Is More Comfortable</h3><p>Maybe the problem is not that we keep moving between relativism and absolutism. Perhaps the real problem begins when the movement stops. In fact, looking at the complement of that cycle in the whole morality space can help us better understand the dynamics.</p><ol><li><strong>Without that cycle, there is obviously no going back to (1), from (3), which is typically the edge that closes the loop and maintain the cycle.</strong></li><li><strong>⁠And without going back to (1), we stand on our view that other people’s values or morality are wrong.</strong></li></ol><p>At that point, disagreement with our morality becomes almost unacceptable. We begin to think that our morality is the truth itself. And once our morality becomes the truth, anything that contradicts it begins to look like evil. Relative morale risks becoming our very own characterization of “what is evil”. Evil becomes everyone or everything that does not comply with our core moral or values. <strong>It sounds like “Your’s are wrong, mine are true, mine are the way. You are corrupted!”.</strong> This creates the conditions for what we might call a “<strong>moral dictatorship”. </strong>This is the belief in the absolute superiority of our own moral order.</p><p>Well, this claim can be heavily supported, historically speaking.</p><ol><li><strong>In the age of Imperialism,</strong> there was a dimension of belief that Imperialism has a beneficial effect on the subjects themselves. Domination was as a moral duty. Africans for example were seen as barbarous by fascists imperalists, and their imperial rule of domination was <strong>“civilizing”. </strong>Therefore, it was much needed. <strong>Fascist Italy’s invasion of Ethiopia followed this logic.</strong> On this, Mussolini Benito, the lead of the Italian nationalism and fascism at that time (1930) declared: “<strong><em>pour confirmer notre unité retrouvée, allons montrer à ces BARBARES que nous sommes forts, et puissants”</em></strong>. This sounds like <strong><em>“we are conquering you because our values are higher, our civilization is superior, and your way of life must be corrected”. </em></strong>This is typically moral dictatorship packaged as a salvation mission.</li><li>⁠<strong>In the age of Empires,</strong> conquests were battles of morales and values, beyond extending pure political domination. Conquests were also seen as an expansion of truth, law, and divine order. The most factual example is certainly the last of the <strong>Greatest Empires of all of times</strong>, the Arab empire. There was a perception of the absolute superiority of the islamic morale. This led to conquests and battles for “good”. During the Ottoman Empire’s total domination, when a non-islamic empire is defeated, they had non-negotiable options: <strong>(1) Accept and convert to Islam, and live peacefully, or (2) Become a vassal kingdom under the supreme Caliph</strong>. But even this arrangements have visible hierarchy. The islamic moral and religious order stood above the others. From this perspective, moral dictatorship sometimes, in rare cases, do tolerate differences, but only after placing it under itself. Like <strong><em>“You may exist, but under the authority of my truth.”</em></strong></li><li>If we retrograde further, then we fall in <strong>the Roman Empire age</strong>. <strong>They placed christianity at the center of their conquests and domination. </strong>In fact, Rome was not originally a christian empire, but its expansion started before christianity became the main imperial identity. At some point, religious beliefs became source of political and moral legitimacy. On this, Constantine’s vision before the Battle of the <strong>Milvian Bridge,</strong> which was associated with the legendary <strong>Chi-Rho symbol</strong>, gives us an idea of this fusion between divine approval and political victory. Furthermore, other battles like <strong>Battle of Frigidus</strong> have shown with clear evidence the conflict between competing religious values, as superior morality. In these moments, conquest and domination represented a divine will, and moral superiority.</li><li>We can keep retrograding until we reach the oldest civilization ever. The Greeks, Persians, Carthaginians, Phoenicians, all the way back to the Egyptians, we can see this recurring tendency where societies place their own gods, values, and ways of life above those of others. In this regard, domination can easily be justified as order, correction, civilization, or even salvation.</li></ol><p>From the examples above, we can see why moral dictatorship is not only a modern problem. <strong>Historically, when we become convinced of the absolute superiority of our moral order, we start to see domination as a duty, or a responsibility. </strong>This context take us to a main and fundamental political and societal question.</p><p><strong><em>If morally divergent people must live together, what kind of society can possibly integrate them without forcing them into complete moral agreement?</em></strong></p><h3>3. Still In The Cycle, Maybe We Need a Way Out</h3><p><strong>Some may directly think about religious values</strong>. Well, first thing is to admit that we are in a world with many religions, many cultures, and many competing moral traditions, all with a very low level of agreeableness among them. Beyond this, we have seen how religion and culture can become epicentral weapons in moral battles. So the topic remains on the table: <strong><em>can all religions and cultures truly agree on one common definition of morality ?</em></strong></p><p><strong>Okay, maybe the universal declaration of human rights, then ? </strong>This seems more promising. Isn’t it ? Because it tries to define a common moral and political language beyond religion and culture. Well, still debatable. Its universality is still debated. If some people see it not as universal truth, but as the projection of certain political, or cultural values, <strong>then does it risk becoming another form of moral imposition, this time not through classic conquests as we have seen in history, but trough a political alliance ?</strong></p><p><strong>Well, what about Humanism ? </strong>It sounds even more interesting, because humanism tries to build morality around what we have in common. But even humanism has a clear weakness. Reason is, humanism is heavily centered on empathy, which has its clear limits. It is comfortable to empathize with those whose values resemble ours, but without any form of delusion, it is also much harder to deeply empathize with people whose moral convictions disturb, or contradict us.</p><p>So maybe the way out is to create our own definition of morale, proper to us. Some ensemble of values we can live by, and live for. Values that originally defines us. Born from within, not influenced by religion, not inherited from culture. Yes, Maybe that is the optimal path.</p><p>But even then, we cannot escape the problem entirely. No matter how personal our morality becomes, we have to eventually bring it into contact with the external world. We will have to negotiate it with society, and with the people around us. And the moment we do that, <strong>we are brought back into the cycle, again!</strong></p><h3><strong>Outlook</strong></h3><p>So perhaps the conclusion is not that we must find a final escape from the moral pendulum. Maybe we should accept that, for generations to come, we may never fully escape it. But most importantly, as humans, we should at least allow ourselves to be deeply struck by the question itself. Not necessarily to choose a camp too quickly, but to understand the complexity of morality, to sit with its uncertainty, and to feel the emptiness that comes from not fully understanding what drives our lives at the most fundamental level. Only then can we truly ask ourselves the deepest questions about morality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88fd38e08cc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerating PyTorch workloads with the AWS S3 connector for Fast Data Loading and Model…]]></title>
            <link>https://baimamboukar.medium.com/accelerating-pytorch-workloads-with-the-aws-s3-connector-for-fast-data-loading-and-model-fcfdba067a4b?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcfdba067a4b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dataloader]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 08:53:26 GMT</pubDate>
            <atom:updated>2026-01-15T15:13:34.629Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accelerating PyTorch workloads with the AWS S3 connector for Fast Data Loading and Model Checkpointing</h3><p><em>This article is a complete practical guide to using the AWS S3 connector for PyTorch, a powerful open-source library designed to optimize data loading and checkpointing for deep learning workloads via S3.</em></p><figure><img alt="Accelerating Pytorch Workloads with AWS S3 Connector" src="https://cdn-images-1.medium.com/max/1024/1*Dgp-iaXpo8Qh-1IH_N0TTQ.png" /><figcaption>Accelerating Pytorch Workloads with AWS S3 Connector</figcaption></figure><p>When it comes to training deep learning models, <a href="https://pytorch.org/"><strong>PyTorch</strong></a> is the number one choice for researchers and engineers for its flexibility and ease of use. PyTorch makes building complex neural networks straightforward and intuitive. Developers love PyTorch because it integrates smoothly with the Python ecosystem and simplifies the debugging process. However, the real headache starts when you move from tutorials to production-grade data. Managing datasets that are too large to fit on a local disk is a challenge that every ML engineer faces eventually. <strong>In fact, Storing data on S3 is the industry standard, but getting that data into your GPU efficiently is a different story.</strong></p><blockquote><strong>Fun Fact! </strong>Saving machine learning training <strong>model checkpoints is up to 40% faster</strong> with the Amazon S3 Connector for PyTorch than saving to Amazon EC2 instance storage. It implements the <strong>CRT (Common Runtime)</strong> under the hood, which is the same high-performance asynchronous engine used by the AWS CLI to maximize throughput.</blockquote><h3>1. Why AWS S3 Connector, story time!</h3><p>—<em> If you don’t like stories, please skip this section </em>🤣</p><p>I was working on a semantic segmentation task involving high-resolution satellite imagery. The dataset was stored in an S3 bucket. Of course, I wrote a standard training loop and fired up my EC2 instance with a L100 GPU. My flow was stable, and everything seemed okay in theory, until I noticed that my training epochs were taking forever.</p><p>When I checked nvidia-smi. My GPU usage was dropping to 0% every few seconds. It wasn&#39;t computing; it was waiting. The training process was waiting for data because my data loader couldn&#39;t pull images from S3 fast enough to keep up with the GPU.</p><p>At this point, there are several ways to tackle the IO issue. The easiest approach is to simply download the entire dataset to the instance’s EBS volume before training starts. It works for moderate datasets, but it creates a delays before training actually begins. And the more serious problem in my opinion is that, <strong>you end up paying for expensive high-performance storage just to hold a duplicate of your data</strong>. But this is just a workaround… This solution falls apart when your dataset is larger than the disk space available on the training instance. In fact, <strong>storing data on S3 is the industry standard, but getting that data into your GPU efficiently is a different story</strong>.</p><p><strong><em>And This is where the S3 Connector comes in 🧨</em></strong></p><p>For demanding workflows, the S3 connector for PyTorch is the robust solution. It streams data directly from S3 into your training loop. In the next section of this tutorial, we will focus on setting up this connector to eliminate the <strong>“download phase” </strong>and keep our GPUs busy 😉.</p><h3>2. Understandting AWS S3 Connector</h3><p>The <strong>S3 Connector for PyTorch</strong> is an open-source library that provides implementations of PyTorch’s dataset primitives (Dataset and IterableDataset) that are purpose-built for S3 object storage.</p><p><a href="https://github.com/awslabs/s3-connector-for-pytorch">GitHub - awslabs/s3-connector-for-pytorch: The Amazon S3 Connector for PyTorch delivers high throughput for PyTorch training jobs that access and store data in Amazon S3.</a></p><p>From a technical perspective, it optimizes the read and list requests to S3. It streams the data directly into your training flow instead of downloading it to your local disk. This approach is particularly effective for training large models where the dataset size is quite heavy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6NlHCTqYax3F65pJKi3sA.png" /><figcaption>AWS S3 Connector Flow</figcaption></figure><p>The library sits between your S3 bucket and the PyTorch DataLoader. Instead of making standard HTTP requests via boto3, which can be slow in Python due to the GIL, the connector leverages the AWS CRT. This allows for</p><ol><li><strong>High Throughput as </strong>It saturates the network bandwidth of your EC2 instance.</li><li><strong>Backpressure Management by </strong>handling<strong> </strong>retries and connection pooling automatically.</li><li><strong>Direct Checkpointing by </strong>streaming model weights directly to S3 without writing to a local disk first.</li></ol><blockquote><strong>Fun Fact!</strong> The connector supports both map-style datasets (for random access) and iterable-style datasets (for streaming). This makes it flexible for both Computer Vision and NLP tasks.</blockquote><h3>3. Technical Implementation</h3><p>Getting started with the S3 Connector is really straightforward. It is really designed to feel native to PyTorch users. Getting this running requires understanding two main concepts: <strong>Map-style</strong> access and <strong>Iterable-style</strong> access. You can refresh your understanding or get to know about these data access styles in deep learning workflows here</p><p><a href="https://huggingface.co/docs/datasets/en/about_mapstyle_vs_iterable">Differences between Dataset and IterableDataset</a></p><p><strong>Prerequisites — </strong>Before writing code, ensure your environment is authorized. If you are running on EC2, the instance profile must have S3ReadOnlyAccess, for data loading and S3FullAccess, if you plan to write checkpoints to your S3 instance.</p><p>Installation is straightforward via pip with</p><pre>pip install s3torchconnector</pre><h4>1. Random Access with S3MapDataset</h4><p>If you are training a models like vision transformers or CNNs, you likely need to shuffle your data. The S3MapDataset implements the __getitem__ method that allows random access to objects by key.</p><pre>from s3torchconnector import S3MapDataset<br>from torch.utils.data import DataLoader<br><br># Initialize the Map Dataset<br># This allows random access (e.g., dataset[10]) without downloading the whole bucket<br>dataset = S3MapDataset.from_prefix(<br>    &quot;s3://deep-learning-benchmark-data/imagenet-train/&quot;,<br>    region=&quot;us-east-1&quot;<br>)<br><br># Then integrate with PyTorch DataLoader<br># The connector handles the concurrent fetching of objects<br>dataloader = DataLoader(<br>    dataset,<br>    batch_size=64,<br>    shuffle=True,  # This flag is crucial for training convergence<br>    num_workers=4  # To parallelize the network requests<br>)<br><br>print(&quot;Starting training loop...&quot;)<br>for images in dataloader:<br>    # &#39;images&#39; are now loaded directly from S3 into RAM 🔥<br>    train_step(images)</pre><p>In this snippet, from_prefix acts as a directory listing. When the DataLoader requests index 5, the connector fetches the specific object associated with that index directly from S3.</p><h4>2. Streaming with S3IterableDataset</h4><p>For models like Large Language Models (LLMs) or time-series models, data is often consumed sequentially. The S3IterableDataset is optimized for this throughput. <strong>This style is used when order matters, or when the dataset is too massive to map effectively in some cases.</strong></p><pre>from s3torchconnector import S3IterableDataset<br><br># Initialize the Iterable Dataset<br>dataset = S3IterableDataset.from_prefix(<br>    &quot;s3://deep-learning-benchmark-data/text-corpus/&quot;,<br>    region=&quot;us-east-1&quot;<br>)<br><br># Stream the data<br># No shuffling here; we consume data as it flows<br>for item in dataset:<br>    # item.read() returns the binary content of the S3 object<br>    content = item.read()<br>    process_text(content)</pre><h4>3. Optimized Model Checkpointing</h4><p>Saving the state of a large model can produce very heavy files. Writing this to a local disk and then uploading it to S3 is slow and risks disk-out-of-space errors. The S3Checkpoint class allows us to write the binary stream of the model weights directly to the S3 API.</p><pre>from s3torchconnector import S3Checkpoint<br>import torch<br>import torchvision<br><br># Setup model and checkpoint location<br>model = torchvision.models.resnet50()<br>checkpoint_uri = &quot;s3://my-model-artifacts/checkpoints/v1/&quot;<br>checkpoint_manager = S3Checkpoint(region=&quot;us-east-1&quot;)<br><br># Save directly to Cloud<br># We open a write stream to S3 and pass it to torch.save<br>with checkpoint_manager.writer(checkpoint_uri + &quot;best.model__epoch.28.pt&quot;) as writer:<br>    torch.save(model.state_dict(), writer)<br><br>print(f&quot;Checkpoint saved to {checkpoint_uri}&quot;)</pre><h4>Putting it All Together</h4><p>The AWS S3 Connector for PyTorch is a necessary evolution in MLOps. It abstracts away the complexity of high-performance cloud storage. This now allows builders to focus to train large models, leveraging cloud storage in the comfort of their classic training workflows.</p><p><strong>Thanks for reading ❤️‍🔥✨</strong></p><p>I hope this quick discovery of the S3 Connector helps you build faster pipelines. My name is Baimam Boukar. I am a Software Engineer, getting into AI research. I enjoy sharing my knowledge through blog posts. I write about Deep Learning, Software Development, and Serverless on AWS.</p><p><a href="https://baimamboukar.dev/">Let’s stay connected </a>💯</p><h3>References</h3><p>[1] <a href="https://aws.amazon.com/blogs/storage/improving-amazon-s3-throughput-for-the-aws-cli-and-boto3-with-the-aws-common-runtime/">“Accelerate Amazon S3 throughput with the AWS Common Runtime | AWS Storage Blog.”</a></p><p>[2] <a href="https://github.com/awslabs/s3-connector-for-pytorch"><em>awslabs/s3-connector-for-pytorch</em>. Amazon Web Services — Labs.</a></p><p>[3] <a href="https://huggingface.co/docs/datasets/en/about_mapstyle_vs_iterable">“Differences between Dataset and IterableDataset.”</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcfdba067a4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring Your ML Models to Production With FastAPI, AWS AppRunner and ECR.]]></title>
            <link>https://baimamboukar.medium.com/bring-your-ml-models-to-production-with-fastapi-aws-apprunner-and-ecr-272d6dcf72e4?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/272d6dcf72e4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aws-app-runner]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 14:07:09 GMT</pubDate>
            <atom:updated>2025-07-21T14:07:09.168Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a quick introduction to machine learning models deployment to AWS AppRunner using models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=272d6dcf72e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Self-Hosted GitHub Actions Runner on AWS Virtual Machines]]></title>
            <link>https://baimamboukar.medium.com/setting-up-a-self-hosted-github-actions-runner-on-aws-virtual-machines-17e68baf7fb9?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e68baf7fb9</guid>
            <category><![CDATA[continious-integration]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 17:04:46 GMT</pubDate>
            <atom:updated>2024-12-31T23:43:25.932Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is a step-by-step guide to configuring your Github Actions runners to work with “self-hosted” AWS EC2 VMs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viI1SZWobUcL9j1D8eWo2w.png" /></figure><p>When it comes to CI/CD tools, GitHub Actions is the number one choice for developers and small to medium teams for its ease and integrations with various software development tools. Github Actions is nothing like other traditional tools such as Jenkins that need complex setup and maintenance as it offers a more straightforward approach. Developers love GitHub Actions because it works smoothly with Github and makes workflow automation simple. Github Actions has an event-driven approach. It runs tasks when specific events happen, like when code is pushed, an issue is opened, or pull requests are created.</p><h4>Fun Fact 😉</h4><blockquote>Github Actions has a vast marketplace of <strong>over 15,000 pre-built actions </strong>which makes it easy to connect with various development tools and cloud services.</blockquote><p>Small to medium teams especially benefit from GitHub Actions due to its generous free tier offering <strong>2,000 minutes monthly for private repositories and unlimited usage for public ones.</strong></p><p>This sounds cool until you want to run large actions that need more than 10 GB of cache memory 😂.</p><figure><img alt="baimamboukar | Github Actions Default Offerings" src="https://cdn-images-1.medium.com/max/945/1*EQ4gRZHSXBFtsSGgHUW9-A.png" /><figcaption>Github Actions Default Offerings.</figcaption></figure><p>This offering is pretty cool for small tasks like automatic deployment or running tests for medium-sized software in the CI. But sometimes you may have heavy actions that require much more than the capacity provided by the free-tier GitHub actions.</p><h4>My personal story 😂</h4><p>I was working on benchmarking software, and I had set up these benchmarks to run automatically via GitHub Actions cron jobs. Everything seemed perfect in theory, but then my actions started failing.</p><p><strong><em>I spent a couple of times looking at my workflow configurations because I was convinced I must have messed up something in the setup 😂, Until I discovered the real problem. The benchmarks that I was trying running in the CI were quite heavy and needed more than 10 GB of cache storage and disk space to properly run.</em></strong></p><figure><img alt="Insufficient Disk Space Github Actions Runner" src="https://cdn-images-1.medium.com/max/1024/1*qkWKfOrY4Is6WWiHv804Qg.jpeg" /><figcaption>Insufficient Disk Space | Github Actions</figcaption></figure><blockquote>At this point, there are several ways to tackle the insufficient disk space issue in GitHub Actions. The simplest approach is using the <strong>maximize-build-space</strong> action.</blockquote><p><a href="https://github.com/marketplace/actions/maximize-build-disk-space">Maximize build disk space - GitHub Marketplace</a></p><blockquote>It can free up to <strong>32GB</strong> on Ubuntu runners by removing unnecessary preinstalled software like Android SDK, Haskell compiler, and Docker images. <strong>But this is just a workaround! </strong>This solution works for moderate space requirements, but it is still limited by the runner’s base disk capacity.</blockquote><h4>This is where AWS EC2 VMs come in!</h4><p>For more demanding workflows like heavy benchmarking, a more robust solution is setting up self-hosted runners on AWS EC2 instances. In the next section of this tutorial, we will focus on setting up a self-hosted GitHub Actions runner on AWS EC2 for a permanent solution to the disk space limitations while offering greater control over the execution environment 😉.</p><h3>Moving to Self-Hosted Runners.</h3><p>Well, first things first. We need to setup the AWS EC2 VM infrastructure on AWS.</p><h4>Infrastructure Setup and Runner Configuration</h4><p>For this, we need to sign in to our AWS account and create a new EC2 instance.</p><ul><li>From your dashboard, search EC2 in the search bar</li><li>And go to the dashboard page of your AWS EC2 service</li><li>From there, you will find an action to launch a new instance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXRmmBWUBRshNoJtGdOgFA.png" /><figcaption>Go to EC2 service Dashboard</figcaption></figure><p>When launching the new EC2 instance, selecting the right instance type is crucial for optimal performance. <a href="https://aws.amazon.com/blogs/aws/choosing-the-right-ec2-instance-type-for-your-application/">For most self-hosted runners, the General Purpose (T3 or M5) instances provide an excellent balance of compute, memory, and networking capabilities.</a></p><p><strong>Well, let’s walk through the setup configurations.</strong></p><p>Give a name that makes sense to our EC2 instance, and you may give a tag if you want. For the operating system image, we select Amazon Linux for the purpose of this demonstration.</p><figure><img alt="Launching a new EC2 instance on AWS" src="https://cdn-images-1.medium.com/max/1024/1*Zr4UAwy2RUvROQqOzEZRxA.png" /></figure><p>Well, as we mentioned earlier, the machine type will really depend on how heavy your Github Actions workflows are. You can select more capable machine types that can handle your workloads properly. You can use the following reference to find the best machine type that fits your needs.</p><p><a href="https://aws.amazon.com/ec2/instance-types/">Cloud Compute Instances - Amazon EC2 Instance Types - AWS</a></p><p>For the purpose of this tutorial, we will select the free-tier eligible T2 micro instance 🥱</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jx1xX-92o5Dh9hdLfh5dHQ.png" /></figure><p><strong>One last important thing in the configuration! </strong>We need to activate the SSH traffic in the network configuration to be able to connect to your EC2 from SSH. This will be crucial for the next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15LmTMGwt9OUMgz7o5Xd7A.png" /></figure><p>That’s all for the configuration! Next, we need to launch the instance and connect to it via SSH. From the dashboard of the EC2 service, locate your instance, open its page, and click on the connect button. From there, get its ID and connect to it via your cloudshell. The command to run is</p><pre>aws ec2-instance-connect ssh --instance-id i-8113YourInstanceIDhere</pre><p>One very last thing 😉! We need to download and install our github actions runner on the EC2 VM.</p><p>At this point, you need to open your github repository. For this purpose, I have prepared a small action that runs to check spell errors in the README file. You can fork the repository at</p><p><a href="https://github.com/baimamboukar/aws-ec2-github-actions-runners">GitHub - baimamboukar/aws-ec2-github-actions-runners</a></p><p>When you have your repository setup, go to Settings &gt; Actions &gt; Runners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhgLktgynQocgyute09onQ.png" /></figure><p>When you are on the Runners page, click on the New Self-Hosted Runner button to open the following configuration page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9iV810ZIm0IHRAYptVRmw.png" /></figure><p>Copy all these commands and run them on the previously opened SSH-connected EC2 VM instance.</p><blockquote>Well, in the process of running these commands, specifically the configuration script, you may encounter some issues. Fear not, it is a classic one. This thread is more than enough to fix it.</blockquote><p><a href="https://github.com/actions/runner/issues/2511">Runner (v2.303) not working on AmazonLinux2023 due to missing ICU package · Issue #2511 · actions/runner</a></p><p>After you successfully ran those commands, you should have something similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrcQgox7uCYQLrT5LmriBQ.png" /></figure><h4>Congratulations for making it up to this point. Let’s finalize it 🔥</h4><h4>Workflow Modification</h4><p>We are almost done. The only thing left is to reconfigure our workflow to run on <strong>Self-Hosted </strong>Runner. This is pretty easy; we just need to update the <strong>Runs-On </strong>key on the YAML workflow file to self-hosted.</p><figure><img alt="Self-hosted workflow update" src="https://cdn-images-1.medium.com/max/759/1*-xy8Tc4uVDAyHXgKXaxPEw.png" /></figure><h4>Workflow Trigger</h4><p>Our time is now! We should now trigger our github action to run on our self-hosted and custom VM. Saving our action workflow after the update or pushing the update if you modified it locally would trigger the workflow, and this time, it would run properly on our EC2 VM instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpKuEOLG3cdyVQDDolaFpg.png" /></figure><p><strong><em>Congratulations 🔥🎉. We have setup a custom and “self-hosted” Github Actions Runner on AWS using an EC2 VM instance.</em></strong></p><p>If you encountered an issue at any step, you can leave a comment below. I would be happy to help 🎊.</p><h3>Thanks for reading ❤️‍🔥✨</h3><p>My name is <a href="https://baimamboukar.dev/">Baimam Boukar</a>. I’m a software engineer, and I enjoy sharing my knowledge through blog posts. I write about serverless on AWS, Flutter, Machine Learning and sometines on random topics like space technologies. Let’s stay connected</p><ul><li>Find me on <a href="https://github.com/baimamboukar">Github</a></li><li>Let’s connect on <a href="https://github.com/in/baimamboukar">LinkedIn</a></li></ul><h3>References</h3><ul><li><a href="https://docs.github.com/en/actions">Github Actions Documentation</a></li><li><a href="https://github.com/marketplace">Github Actions Marketplace</a></li><li><a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2Fmarketplace%2Factions%2Fmaximize-build-disk-space">Maximize Build Github Action</a></li><li><a href="https://aws.amazon.com/ec2/instance-types/">Cloud Compute Instances — Amazon EC2 Instance Types — AWS</a></li><li><a href="https://github.com/actions/runner/issues/2511">Runner (v2.303) not working on AmazonLinux2023 due to missing ICU package #2511</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e68baf7fb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You may want to understand HuggingFace Transformers]]></title>
            <link>https://baimamboukar.medium.com/you-may-want-to-understand-huggingface-transformers-33260d484ed8?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/33260d484ed8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face-hub]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[hugging-face-tutorials]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 15:03:22 GMT</pubDate>
            <atom:updated>2024-10-19T19:19:35.239Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A graceful practical introduction to huggingface transfromers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ba0pNAB9xjB4LnrdbYDXdA.png" /><figcaption>Baimam Boukar | HuggingFace Transformers 101</figcaption></figure><p>In 2024, we find ourselves in the midst of the “AI scramble” era. In this dynamic, Hugging Face is changing the ML landscape by democratizing access to state-of-the-art machine learning models. This article aims to provide a practical introduction to Hugging Face Transformers, a technology that’s reshaping the AI landscape.</p><blockquote><strong>Fun Fact! The name “Hugging Face” was inspired by the hugging face emoji (🤗), chosen to convey a caring and friendly image to teenagers using their original chatbot.</strong></blockquote><h4>Wait, HuggingFace ?</h4><p>Hugging Face is the “<strong>brainchild</strong>” of three French entrepreneurs:<a href="https://www.linkedin.com/in/clementdelangue/"> Clément Delangue</a>, <a href="https://www.linkedin.com/in/julienchaumond">Julien Chaumond</a>, and <a href="https://www.linkedin.com/in/thom-wolf">Thomas Wolf</a>. They had a Eureka time: <strong>building a platform that not only showcases state-of-the-art ML but also makes it accessible and enjoyable for everyone.</strong></p><p>Interestingly, Hugging Face wasn’t always the AI platform we know today. Back in 2016, it started as a chatbot designed to entertain and support teenagers. The name, derived from the hugging face emoji (🤗), was chosen to appear caring and friendly to its young users. Read more here…</p><p><a href="https://techcrunch.com/2017/03/09/hugging-face-wants-to-become-your-artificial-bff/">Hugging Face wants to become your artificial BFF | TechCrunch</a></p><p>Fast forward to 2024, and Hugging Face has transformed into the go-to platform for all things ML. It hosts datasets, models, spaces, and daily trending ML papers. <strong>As of October 2024, the platform boasts more than 750,000 models, 300,000 datasets, and 150,000 spaces</strong> . It has become the ideal platform for AI engineers, practitioners, and enthusiasts, hosting latest models from tech giants like Google, IBM, Intel, Microsoft, Apple, Meta, and NVIDIA.</p><p><strong>Hugging Face secured $235 million in Series D funding in August 2023, raising its valuation to $4.5 billion.</strong></p><blockquote><strong>Not bad for a former emotional support chatbot 😅. Enough, let’s talk about HuggingFace Transformers now.</strong></blockquote><h4>Understanding Hugging Face Transformers</h4><p>Hugging Face Transformers is an open-source library that provides state-of-the-art machine learning models for various tasks. At its core, it is built on the <a href="https://www.datacamp.com/tutorial/how-transformers-work">transformer architecture</a>.</p><p>The library offers a large collection of pre-trained models for diverse tasks, from text classification and named entity recognition to question answering and text generation. These models are not just powerful; they are also incredibly easy to use.</p><p>From a technical perspective, Transformers leverage the power of attention mechanisms, allowing models to focus on different parts of the input when producing output. This approach has proven particularly effective in capturing long-range dependencies in data, a challenge that previous architectures struggled with. Read more about the original paper here…</p><p><a href="https://dl.acm.org/doi/10.5555/3295222.3295349">Attention is all you need | Proceedings of the 31st International Conference on Neural Information Processing Systems</a></p><blockquote><strong>Another Fact! The Transformers library supports over 100,000 pre-trained models as of October 2024 with tasks covered in 100+ languages.</strong></blockquote><h4>Advantages of Hugging Face Transformers</h4><p>Hugging Face Transformers offer several important advantages:</p><ul><li>Reduced infrastructure costs. Leveraging pre-trained models decreases computational resource requirements.</li><li><a href="https://news.climate.columbia.edu/2023/06/09/ais-growing-carbon-footprint/">Lower carbon footprint</a>. Fine-tuning existing models reduces energy consumption. The amount of carbon footprint will be far more significant if training a model from scratch.</li><li>Time savings. Building on existing models accelerates your work and enables faster development and deployment.</li><li>Resource conservation.</li></ul><p>One of the most powerful features of Transformers is their interoperability. They seamlessly integrate with popular deep learning frameworks like <strong>PyTorch, TensorFlow, and JAX</strong>. While PyTorch is the stable choice for all models, this flexibility allows developers to work within their preferred ecosystem.</p><blockquote><strong>Fun Fact! Hugging Face Transformers can be used for tasks beyond text processing, including image classification, speech recognition, and even protein folding prediction.</strong></blockquote><h4>Fine-tuning with Transformers</h4><p>Transformers excel at<a href="https://www.ibm.com/topics/fine-tuning"> fine-tuning</a>. This technique allows practitioners to use pre-existing pre-trained models and adapt them to specific tasks or domains. Fine-tuning involves taking a pre-trained model and further training it on a smaller, task-specific dataset. This process allows the model to adapt its general knowledge to the nuances of a particular application. For instance, a foundational model pre-trained on a large corpus of English text could be fine-tuned for sentiment analysis in product reviews.</p><p>This practice has many advantages, among which:</p><p>1. Reduced training time and computational resources<br>2. Improved performance on tasks with limited labeled data<br>3. Better generalization to new, unseen examples</p><blockquote><strong>Fun Fact!</strong><a href="https://github.com/huggingface/transformers"><strong> HuggingFace Transformers</strong></a><strong> has over 134,000 stars on GitHub. Only Google Tensorflow has more in the category of AI and ML libraries.</strong></blockquote><h4>Now, when to Use Hugging Face Transformers</h4><p>Hugging Face Transformers are particularly useful in scenarios where you need to leverage state-of-the-art machine learning without the resources to train models from scratch. I am sure it may help you in these common use cases:</p><p>1. Rapid prototyping of AI-powered applications in general<br>2. Building chatbots or conversational AI systems<br>3. Implementing text classification for sentiment analysis or content moderation<br>4. Creating translation and summarization systems<br>5. Developing question-answering systems for customer support or information retrieval<br>6. Generating human-like text for content creation or data augmentation</p><blockquote><a href="https://newsroom.ibm.com/2023-08-24-IBM-to-Participate-in-235M-Series-D-Funding-Round-of-Hugging-Face"><strong>Another Fact!</strong></a><strong> “IBM has contributed over 200 open models and datasets on Hugging Face, including the recent release of the Geospatial Foundation Model in partnership with NASA. It is the largest geospatial foundation model on Hugging Face and the first-ever open-source AI foundation model built in collaboration with NASA.”</strong></blockquote><h4>Getting Started with Hugging Face Transformers</h4><p>Getting started with Hugging Face is really straightforward. As we mentioned earlier, it is very easy to use.</p><p>1. Start by creating a free account on the Hugging Face website.<br>2. Install the Transformers library pip install transformers<br>3. Start experimenting with pre-trained models.</p><blockquote>That’s all you need for the setup! It is advised to use <a href="https://colab.research.google.com/">Google Collab</a> for this task.</blockquote><p>Now, let’s get our hands dirty by trying out transformers. Again, I will repeat it. The beautiful thing with transformers is their ease of getting started with. The <strong>pipeline()</strong> function is the easiest way to use transformers.</p><p>Let’s dive into these hands-on examples with Hugging Face Transformers.</p><ol><li><strong>Question Answering</strong></li></ol><p>Let’s start with the question-answering transformer.</p><pre>from transformers import pipeline<br><br># Question Answering example<br>qa_model = pipeline(&quot;question-answering&quot;)<br>context = &quot;Hugging Face was founded in 2016 as a chatbot for teenagers.&quot;<br>question = &quot;When was Hugging Face founded?&quot;<br>answer = qa_model(question=question, context=context)<br>print(f&quot;Answer: {answer[&#39;answer&#39;]}&quot;)<br>print(f&quot;Confidence Score: {answer[&#39;score&#39;]:.2f}&quot;)</pre><p>In this example, we’re using the `pipeline()` function. By specifying <strong><em>“question-answering”</em></strong> as the task, we are using a pre-trained model optimized for answering questions based on a given context. The model processes this information and returns an answer along with a confidence score. The output might look something like this.</p><pre>Answer: 2016<br>Confidence Score: 0.98</pre><p><strong>2. Sentiment Analysis</strong></p><p>Now, let’s explore the NLP capabilities with sentiment analysis</p><pre>from transformers import pipeline<br><br>classifier = pipeline(&quot;sentiment-analysis&quot;)<br>inputs = [&quot;The Beautiful Thing With Learning Is That No Once Can Take It Away From You!&quot;,<br>          &quot;HuggingFace Is cool&quot;, &quot;I want problems, always 🥷&quot;]<br>output = classifier(inputs)<br><br>for index, result in enumerate(output):<br>    print(f&quot;🟢 {inputs[index]} | label =&gt; {result[&#39;label&#39;]} | score =&gt; {round(result[&#39;score&#39;], 4)}&quot;)Here, we’re using a specific model for English to French translation. The `pipeline()` function allows us to specify the model we want to use, giving us fine-grained control over our NLP tasks.</pre><p><strong>3. Audio Classification</strong></p><p>Finally, let’s look at audio classification.</p><pre>from transformers import pipeline<br><br># Audio Classification Task<br>audio_classifier = pipeline(&quot;audio-classification&quot;)<br>audio_file = &quot;reference.mp3&quot;<br>results = audio_classifier(audio_file)<br>print(f&quot;Audio classification results for {audio_file}:&quot;)<br>for result in results[:3]:<br>    print(f&quot;- {result[&#39;label&#39;]} (Confidence: {result[&#39;score&#39;]:.2f})&quot;)</pre><p>With just these few lines of code, we have leveraged state-of-the-art models for question answering, sentiment analysis, and audio classification. Pretty cool! If you wish to explore more and practice with more example, I recommend the official documentation.</p><p><a href="https://huggingface.co/docs/transformers/pipeline_tutorial">Pipelines for inference</a></p><h4>Putting it All Together</h4><p>Hugging Face is revolutionizing the way we interact with AI models. It is arguably the fastest way to run inference on existing state-of-the-art models. By democratizing access to state-of-the-art ML models, Hugging Face Transformers are empowering AI researchers and curious beginners to leverage or build on top of various foundation models.</p><h4>Thanks for reading ❤️‍🔥✨</h4><p>I hope this introduction to Hugging Face and Transformers is cool. My name is <a href="https://baimamboukar.dev/">Baimam Boukar.</a> I’m a software engineer, and I enjoy sharing my knowledge through blog posts. I write about Machine Learning, Cloud, Research, and Software Development. Let’s stay connected</p><ul><li>I am on <a href="https://huggingface.co/baimamboukar">HuggingFace</a></li><li>Find me on <a href="https://github.com/baimamboukar">Github</a></li><li>Let’s connect on <a href="https://github.com/in/baimamboukar">LinkedIn</a></li></ul><h4><strong>References</strong></h4><ol><li><a href="https://huggingface.co/docs/transformers/index">Hugging Face🤗 | Transformers Documentation</a></li><li><a href="https://weam.ai/blog/guide/huggingface-statistics/">Weam AI | Every Hugging Face Statistics You Need to Know.</a></li><li><a href="https://www.similarweb.com/website/huggingface.co/">Similarweb | Huggingface.co Traffic Analytics, Ranking &amp; Audience</a></li><li><a href="https://dl.acm.org/doi/10.5555/3295222.3295349">Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). <strong><em>“Attention is all you need.”</em></strong>. Advances in Neural Information Processing Systems, 30.</a></li><li><a href="https://kitrum.com/blog/the-inspiring-journey-of-clement-delangue-hugging-faces-founder/">Vyshyvaniuk @ KITRUM | The Inspiring Journey of Clément Delangue, Hugging Face’s founder.</a></li><li><a href="https://news.climate.columbia.edu/2023/06/09/ais-growing-carbon-footprint/">State of the Planet | AI’s growing carbon footprint</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33260d484ed8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Hugging Face Models with AWS SageMaker]]></title>
            <link>https://baimamboukar.medium.com/deploying-hugging-face-models-with-aws-sagemaker-a782b4e2fe51?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/a782b4e2fe51</guid>
            <category><![CDATA[sagemaker-studio]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 14:59:10 GMT</pubDate>
            <atom:updated>2024-12-27T09:42:05.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quickly deploying Hugging Face Models to AWS SageMaker.</h3><p><em>A step-by-step guide to deploying HuggingFace models to AWS SageMaker and handling Inference endpoints.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwKp2K-42b4pJ1_Mph_uwg.png" /><figcaption>Baimam Boukar | Hugging Face Models to AWS SageMaker.</figcaption></figure><p>In this article, we will explore how to deploy the state-of-the-art hugging face models to AWS SageMaker effortlessly. More specifically, we will follow a step-by-step guide to achieve it and throw lights and more insights on the sub-steps involved.</p><p><strong>Let’s get started 🎉</strong></p><p>Well, if you’re reading at this point, it means this article sounds good to you. If you want to deploy some HugginFace models in an environment that you can control and monitor. Then AWS SM is kind of an excellent choice for this use case.</p><h3>SageMaker and HuggingFace 101</h3><p>Before diving into technical details, let’s have a quick understanding of hugging faces and the amazing AWS Sagemaker service.</p><p><a href="## From HF to AWS Sagemaker"><strong><em>You can jump to the next section if you already have a good understanding.</em></strong></a></p><blockquote>HuggingFace is a state-of-the-art ML platform that hosts datasets, models, spaces, and daily trending ML papers. As of October 2024, the platform boasts more than 750,000 models, 300,000 datasets, and 150,000 spaces. It has become the ideal platform for AI engineers, practitioners, and enthusiasts, hosting the latest models from tech giants like Google, IBM, Intel, Microsoft, Apple, Meta, and NVIDIA. Read more about HuggingFace in my last article</blockquote><p><a href="https://baimamboukar.medium.com/you-may-want-to-understand-huggingface-transformers-33260d484ed8">You may want to understand HuggingFace Transformers</a></p><blockquote><strong>AWS SageMaker is a fully managed service that simplifies the machine learning lifecycle. It handles everything from data preparation to model deployment. The service runs on a pay-as-you-go model with no upfront commitments. You only pay for the resources you actually use.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*60vs2SmFkhshOJdq.png" /><figcaption>AWS SageMaker Flow</figcaption></figure><p>AWS SageMaker stands out for three main advantages: scalability, cost-effectiveness, and security.</p><ul><li>It offers unmatched scalability to handle heavy workloads without infrastructure concerns.</li><li>It also provides comprehensive cost-effectiveness through its pay-as-you-go model.</li><li>Furthermore, it delivers built-in security and compliance features for enterprise deployments.</li></ul><p>For detailed information, including pricing, AWS provides a comprehensive pricing guide at</p><p><a href="https://aws.amazon.com/sagemaker/">The center for all your data, analytics, and AI - Amazon SageMaker - AWS</a></p><h3>From HuggingFace to AWS SageMaker</h3><p>Before we dive deep into the details, did you even know that you can directly deploy these models to HF spaces? So why do you even need a sagemaker?</p><p><strong><em>You can jump to the next section if you already have your answer 😅.</em></strong></p><p>AWS SageMaker offers distinct advantages that make it the perfect solution for many use cases. When compared to HuggingFace Spaces, SageMaker excels in three areas. It provides automatic scaling capabilities that adjust to your workload demands. The platform offers deep observability into your model’s performance and health. SageMaker also takes care of infrastructure management, letting you focus on your ML tasks.</p><h4><em>Hands-on Deployment</em></h4><p>For this practical demonstration, we will deploy the layoutLM-based model <strong>layoutlm-document-qa</strong>, a powerful multi-modal model designed for document question answering. This model excels at extracting information from documents by understanding both textual content and spatial layout. The model has been fine-tuned on SQuAD2.0 and DocVQA datasets.</p><p>First, ensure you have AWS credentials configured. You will need to setup these credentials. This official tutorial will be helpful in setting it up correctly.</p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html?source=post_page-----5a277042c1a1--------------------------------">Configuration and credential file settings in the AWS CLI</a></p><p>At this point, we have to install the various dependencies we need.</p><pre>pip install sagemaker boto3 transformers pillow torch</pre><p>Next, we need to configure our AWS SageMaker environment. You can use the official guide to quickly set it up.</p><p><a href="https://aws.amazon.com/de/awstv/watch/942d41855de/">Amazon SageMaker Studio Setup Guide - AWS</a></p><p>Next, we use the SageMaker SDK to define our HuggingFacemodel.</p><pre>from sagemaker.huggingface.model import HuggingFaceModel<br>import sagemaker<br><br>role = sagemaker.get_execution_role()<br>huggingface_model = HuggingFaceModel(<br>    transformers_version=&#39;4.26.0&#39;,<br>    pytorch_version=&#39;1.13.1&#39;,<br>    role=role,<br>    model_id=&#39;impira/layoutlm-document-qa&#39;,<br>    strategy=&#39;single-record&#39;<br>)</pre><p>For deployment, SageMaker offers various instance types to match your performance and cost requirements.</p><ul><li>The <strong>ml.m5.xlarge</strong> instance type works well for most general-purpose deployments.</li><li>For GPU-accelerated inference, the <strong>ML.g4dn.xlarge</strong> instance provides NVIDIA T4 GPUs.</li></ul><p>To deploy the model, we simply execute</p><pre>predictor = huggingface_model.deploy(<br>    initial_instance_count=1,<br>    instance_type=&quot;ml.g4dn.xlarge&quot;<br>)</pre><p>That’s it! The model has been deployed to AWS SageMaker. Now let’s test the deployed endpoint.</p><pre>import json<br>from PIL import Image<br>import base64<br>from io import BytesIO<br><br># Load and prepare the image<br>image = Image.open(&quot;flight_ticket.png&quot;)<br>buffered = BytesIO()<br>image.save(buffered, format=&quot;PNG&quot;)<br>image_str = base64.b64encode(buffered.getvalue()).decode()<br><br># Prepare the payload<br>payload = {<br>    &quot;inputs&quot;: {<br>        &quot;image&quot;: image_str,<br>        &quot;question&quot;: &quot;What is the ticket&#39;s unique ID?&quot;<br>    }<br>}<br><br># Send request to the endpoint<br>response = predictor.predict(json.dumps(payload))<br>print(f&quot;🟢OUTPUT =&gt;  {json.loads(response)}&quot;)</pre><p>Very important! If you’re doing this for only learning purposes, don’t forget to cleanup resources after testing. To do so, you will have to run</p><pre>predictor.delete_endpoint()</pre><p>In this guide, we learned how to take a Hugging Face model and deploy it on AWS SageMaker. We saw how simple it is to set up a model, test it, and keep track of how well it’s running</p><h3>Thanks for reading ❤️‍🔥🔥</h3><p>My name is <a href="https://baimamboukar.dev/">Baimam Boukar</a>. I’m a software engineer, and I enjoy sharing my knowledge through blog posts. I write about Serverless and Machine Learning on AWS, Flutter and sometines on random topics like Space Technologies. Let’s stay connected!</p><ul><li>Find me on <a href="https://github.com/baimamboukar">Github</a> and <a href="https://huggingface.com/baimamboukar">HuggingFace</a></li><li>Let’s connect on <a href="https://linkedin.com/in/baimamboukar">LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a782b4e2fe51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Retrieval Augmented Generation with AWS SageMaker.]]></title>
            <link>https://baimamboukar.medium.com/get-started-with-retrieval-augmented-genration-on-google-cloud-f01663bbf851?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/f01663bbf851</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 23:30:18 GMT</pubDate>
            <atom:updated>2025-03-10T06:57:21.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>$\to$ Large language models (LLMs) have taken the tech world by storm, capable of generating human-quality text, translating languages, and writing different kinds of creative content. But LLMs also have limitations. They can struggle with factual accuracy and lack access to real-time information. This is where Retrieval Augmented Generation (RAG) comes in.</p><p>RAG combines the power of LLMs with external knowledge retrieval, creating a more robust and informative AI experience. This blog post will guide you through getting started with RAG on Google Cloud.</p><h3>What is Retrieval Augmented Generation (RAG)?</h3><p>RAG is a powerful AI design pattern that leverages two key components:</p><ol><li><strong>Large Language Model (LLM):</strong> This is the engine that generates text, translates languages, and performs other creative writing tasks. Google Cloud offers various pre-trained LLMs or allows you to bring your own custom model.</li><li><strong>External Knowledge Retrieval:</strong> This component searches for relevant information from various sources like databases, documents, or even the web, to enrich the context for the LLM.</li></ol><p>By combining these elements, RAG allows LLMs to:</p><ul><li>Generate more accurate and factual responses.</li><li>Access and process real-time information.</li><li>Support complex conversational experiences.</li></ul><h3>Why Use RAG on Google Cloud?</h3><p>Google Cloud offers a compelling environment for building RAG applications. Here’s why:</p><ul><li><strong>Pre-trained LLMs:</strong> Get started quickly with pre-trained LLMs like the powerful Gemini family.</li><li><strong>Flexible Data Sources:</strong> Integrate RAG with various data sources like Cloud SQL, BigQuery, or even custom document repositories.</li><li><strong>Easy Deployment:</strong> Leverage Google Cloud’s infrastructure for efficient deployment and scaling of your RAG applications.</li><li><strong>Open-source Tools:</strong> Utilize Google’s open-source GenAI Databases Retrieval App as a starting point for your RAG development.</li></ul><h3>Getting Started with RAG on Google Cloud</h3><p>Here’s a basic roadmap for building a RAG application on Google Cloud:</p><ol><li><strong>Choose an LLM:</strong> Select a pre-trained LLM from Google Cloud or bring your own custom model.</li><li><strong>Prepare Your Data:</strong> Structure your data for efficient retrieval. This could involve storing documents in Cloud Storage or using Cloud SQL for relational data.</li><li><strong>Build the Retrieval Pipeline:</strong> Develop a system to search and retrieve relevant information based on user queries.</li><li><strong>Integrate with the LLM:</strong> Combine the retrieved information with the user query to create a comprehensive prompt for the LLM.</li><li><strong>Deploy and Monitor:</strong> Deploy your RAG application on Google Cloud and monitor its performance for further optimization.</li></ol><h3>Resources for Getting Started with RAG</h3><ul><li><strong>Google Cloud RAG with Databases:</strong> <a href="https://cloud.google.com/blog/products/ai-machine-learning/rag-with-databases-on-google-cloud">https://cloud.google.com/blog/products/ai-machine-learning/rag-with-databases-on-google-cloud</a></li><li><strong>GenAI Databases Retrieval App:</strong> <a href="https://github.com/topics/generative-ai">https://github.com/topics/generative-ai</a></li><li><strong>Multimodal Retrieval Augmented Generation (RAG) using the Vertex AI Gemini API:</strong> <a href="https://www.cloudskillsboost.google/focuses/85643?locale=fr_CA&amp;parent=catalog">https://www.cloudskillsboost.google/focuses/85643?locale=fr_CA&amp;parent=catalog</a></li></ul><h3>Conclusion</h3><p>RAG is a powerful technique to enhance the capabilities of LLMs. Google Cloud provides a comprehensive environment with tools and resources to get you started with building robust and informative RAG applications. Take advantage of pre-trained LLMs, flexible data sources, and easy deployment options to unlock the full potential of generative AI.</p><p>This blog post provides a starting point. As you delve deeper, explore the vast possibilities of RAG and how it can transform your AI-powered applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f01663bbf851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building feature-rich Flutter mobile apps using AWS Amplify.]]></title>
            <link>https://baimamboukar.medium.com/building-feature-rich-flutter-mobile-apps-using-aws-amplify-8ac7a3cc9c4b?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ac7a3cc9c4b</guid>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 23:44:30 GMT</pubDate>
            <atom:updated>2024-01-16T15:32:51.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im7O6zF_9jRurUP1hO7B0Q.png" /><figcaption>flutter and aws amplify</figcaption></figure><p><em>In this article, you will discover why AWS Amplify might be the perfect MBaaS solution for your next Flutter project. We’ll explore its serverless power and how to build feature-rich Flutter apps with remarkable speed and scale, with a focus on delivering remarkable user experiences.</em></p><h3>Functionality is not enough</h3><p>Building feature-rich, zero-downtime mobile apps that scale to millions requires more than just code. Today’s users demand seamless experiences, data-driven insights, and captivating interfaces. This creates a challenge for developers: <strong>balancing backend complexity with a smooth development experience.</strong></p><p>The solution? Choose the right platform and prioritize developing the application’s core features and ensuring an exceptional user experience.</p><p>This approach <strong>redirects</strong> their focus from the complexities of backend infrastructure development and maintenance to leaving the backend complexities to a platform with a rich ecosystem of tools and libraries designed for modern mobile app requirements and a delightful developer experience.</p><p><strong>By making this shift, developers can deliver exceptional apps faster and more efficiently. It’s time to prioritize user delight and developer joy in the mobile app revolution.</strong></p><h4>That’s exactly when AWS Amplify comes into play.</h4><h3>Exploring AWS Amplify</h3><blockquote><strong>AWS Amplify is a complete solution that lets frontend web and mobile developers easily build, connect, and host fullstack applications on AWS, with the flexibility to leverage the breadth of AWS services as your use cases evolve. Amplify provides the following products to build fullstack iOS, Android, Flutter, Web, and React Native apps</strong></blockquote><p>The synergy of AWS Amplify with Flutter creates an innovative approach to mobile app development. This powerful combination merges Flutter’s UI capabilities with AWS Amplify’s robust backend services, allowing developers to write scalable, full-featured, and feature-rich mobile applications with a seamless developer experience.</p><p>Amplify provides a suite of tools and excellent services, simplifying the creation of full-featured and feature-rich Flutter apps for developers.</p><p><strong>Let’s delve into these resources by exploring how Amplify can facilitate Flutter developers in effortlessly constructing comprehensive and feature-rich flutter apps.</strong></p><h4><strong>0. Developer Tools</strong></h4><ul><li><strong>Amplify CLI</strong>: A robust toolchain enabling the configuration and maintenance of your app’s backend directly from your local desktop. It facilitates the interactive setup of cloud functionality, including intuitive use cases such as authentication, storage, and API.</li><li><strong>Amplify Studio</strong>: A user-friendly visual interface accessible through a web dashboard. Amplify Studio allows you to seamlessly configure and manage your AWS Amplify services.1. Seamless Authentication:</li></ul><h4><strong>1. Seamless Authentication</strong></h4><p>Amplify Auth offers a user authentication interface that handles necessary authorization for other Amplify categories. It comes with default support for Amazon Cognito User Pool and Identity Pool, and the Amplify CLI aids in creating and configuring the authentication category with a provider.</p><ul><li><strong>Effortless Integration</strong>: Amplify provides pre-built UI widgets and APIs for social logins, multi-factor authentication, and secure user claims and directories.</li><li><strong>Customizable Experience</strong>: Amplify gives you full control over the authentication experience. Customize the UI widgets to match your app’s look and feel, or build your own from scratch. The choice is yours</li></ul><h4><strong>2. Amplify Storage</strong></h4><p>Amplify Storange is useful for storing user-generated content such as photos, videos, and other media files. It integrates seamlessly with Amazon S3, offering secure and scalable storage for any type of data.</p><p>The Amplify Flutter SDK gives you a friendly API for uploading, downloading, and managing your data with just a few lines of code.</p><h4><strong>3. Amplify Data</strong></h4><p>Amplify DataStore simplifies managing shared and distributed data in your app. It automatically syncs data between devices, offering offline capabilities without extra code. Designed to work with any backend data store, it’s optimized for serverless, real-time, and offline scenarios.</p><ul><li><strong>Offline-First</strong>: Keep your app running smoothly even when the internet is slow. Amplify DataStore lets you manage, sync, and query data locally, ensuring a seamless user experience regardless of connectivity.</li><li><strong>Flexible Data Modeling</strong>: Amplify DataStore lets you define your data model using a simple declarative syntax. It supports a variety of data types, including lists, maps, and nested objects.</li><li><strong>GraphQL Magic</strong>: Build flexible and efficient data APIs with GraphQL. Amplify simplifies API configuration and management, letting you focus on writing powerful queries and mutations to unlock your data’s full potential.</li></ul><h4><strong>4. Amplify Functions</strong></h4><ul><li>Amplify Functions empowers you to extend your application with custom business logic backed by Lambda functions and create powerful event-driven applications with minimal effort.</li><li>It allows you to write backend code in your preferred language (Node.js, Python, Java, or Go) and have it executed seamlessly in response to events from your app or other Amplify services.</li></ul><p>Think of Amplify Functions as a headache-free way of, for example, sending a welcome email to new users, processing a payment, or even running a machine learning model.</p><h4><strong>5. Beyond the Basics</strong></h4><ul><li><strong>Real-time Insights</strong>: Easily collect analytics data for your app with Pinpoint. Analytics data includes user sessions and other custom events that you want to track in your app. Amplify Analytics integrates with Amazon Pinpoint, giving you valuable insights into user behavior and app performance. Track user journeys, optimize features, and make data-driven decisions for an app that users love—a feature-rich one.</li><li><strong>Push Notifications</strong>: Keep users engaged and informed with targeted push notifications. Trigger push notifications to your app and record metrics in Pinpoint when users receive or open notifications.</li><li><strong>AI/ML at Your Fingertips</strong>: Powered by leading AWS services like Amazon Translate and Amazon Rekognition, Predictions lets you build intelligent, interactive apps without AI expertise. Amplify Predictions combines three powerful AI services to add amazing features to your apps:</li></ul><p>1. <strong>Identify</strong>: Find text, faces, objects, and landmarks in images.</p><p>2. <strong>Convert</strong>: Translate text, generate speech from text, or transcribe audio in real-time.</p><p>3. <strong>Interpret</strong>: Analyze text for sentiment, key phrases, entities, and language.</p><p>AWS Amplify emerges as an outstanding choice in the Flutter community, combining a rich feature set, seamless Flutter integration, developer-friendly tools, and the backing of AWS’s powerful infrastructure. While other solutions like Firebase and Appwrite have their merits, Amplify stands out as a comprehensive, extensible, and scalable platform for building exceptional Flutter apps.</p><h3>Next ?</h3><p>Having introduced AWS Amplify, let’s explore its seamless integration with Flutter. In the next article, we’ll navigate through a seamless integration process, complete with setting up Amplify and implementing secure authentication with best practices.</p><h3>Thanks for reading ❤️‍🔥✨</h3><p>My name is <a href="http://www.baimamboukar.dev/">Baimam Boukar</a>. I’m a software engineer and AWS Community Builder. I enjoy sharing my knowledge through blog posts. I write about Serverless and Go Cloud native applications in AWS, Flutter mobile app development, and Bitcoin development.</p><p>Let’s stay connected</p><ul><li>Find me on <a href="https://github.com/baimamboukar">Github</a></li><li>Follow me on <a href="https://medium.com/@baimamboukar">Medium</a></li><li>Let’s connect on <a href="https://linkedin.com/in/baimamboukar"><strong>LinkedIn</strong></a></li></ul><h3>References</h3><ul><li><a href="https://github.com/aws-amplify/amplify-flutter/">AWS Amplify flutter SDKs Github repository</a></li><li><a href="https://docs.amplify.aws/flutter/">AWS Amplify Dev Center</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ac7a3cc9c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Go Serverless REST APIs and Deploy to AWS using the Serverless Framework]]></title>
            <link>https://baimamboukar.medium.com/build-go-serverless-rest-apis-and-deploy-to-aws-using-the-serverless-framework-5a277042c1a1?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a277042c1a1</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 01:04:43 GMT</pubDate>
            <atom:updated>2024-01-03T01:04:43.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nA04eYDSpf9CXQDG1mNH6Q.png" /><figcaption>go serverless apis on aws</figcaption></figure><p><strong><em>Imagine your app scaling effortlessly, and you’re very far from the stress of server management. That’s how serverless `sounds` like, and Go is the perfect language to lead the charge.</em></strong></p><p>This article takes you on a hands-on journey where you’ll leverage Go’s powerful web framework GIN and the AWS Lambda GIN proxy to build efficient serverless APIs and seamlessly deploy them to the AWS Cloud using the magic of the Serverless Framework.</p><p><strong>Leeroy Jenkins! Let’s get started 🚀</strong></p><h3><strong>Let’s setup Gin</strong></h3><p>To spin up a web server for our REST APIs, we need Gin. Gin is a powerful web framework written in Go. It claims to be 40 times faster than Martini, a technology of the same genre. <strong><em>If you need blasting performance, get yourself some Gin</em></strong></p><ul><li>To install gin, go ahead and run</li></ul><pre>go get github.com/gin-gonic/gin</pre><ul><li>Now you can set up a minimal Gin router. For that, copy the example in the GIN documentation and paste it in the main.go file</li></ul><pre>// main.go<br>func main(){<br><br>r := gin.Default()<br><br>r.Get(&quot;/ping&quot;, (c *gin.Context){<br>c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Pong!&quot;})<br>})<br><br>r.Run(&quot;8000&quot;)<br><br><br>}</pre><ul><li>When you’re all good, you can now run the server</li></ul><pre>go run main.go</pre><ul><li>When you visit `<strong>localhost:8000/ping</strong>`, you should see expected response.</li></ul><h3><strong>Let’s setup the Serverless framework</strong></h3><p><strong>First thing first: What is `Serverless Framework` ?</strong></p><p>Serverless is a tool that makes it easy to deploy serverless applications to AWS.</p><blockquote><strong>Zero-Friction Serverless Apps on AWS Lambda: Deploy APIs, scheduled tasks, workflows and event-driven apps to AWS Lambda easily with the Serverless Framework.</strong></blockquote><p>It removes the hell related to deployment in so many ways. Yeah! `Zero-friction serverless development`, Indeed.</p><p>Why? Because:</p><ul><li><em>You define your applications as functions and events by declaring AWS Lambda functions and their triggers through </em><strong><em>simple abstract syntax in YAML.</em></strong></li><li><em>After deploying your serverless app in a single command, Lambda functions, triggers &amp; code will be </em><strong><em>deployed and wired together in the cloud, automatically.</em></strong></li><li><em>You can also extend your use cases by installing </em><strong><em>thousands of Serverless Framework Plugins.</em></strong></li></ul><p><strong>Installation of the Serverless Framework</strong></p><ul><li>To install the serverless framework, we need `nodejs`. If you don’t have Node.js installed, you can go ahead and install it from there:</li></ul><p><a href="https://nodejs.org/en/download">Node.js - Download Node.js®</a></p><ul><li>Simply run the command `<strong>npm install -g serverless</strong>` to get the serverless framework.</li><li>To make sure it has been installed, you can run <strong>serverles -v</strong>`. You should have a similar output.</li></ul><pre>Framework Core: 3.38.0<br>Plugin: 7.2.0<br>SDK: 4.5.1s</pre><p><strong>Let’s Express our serverless application</strong></p><p>Now that we have serverless installed, we can go ahead and define our serverless app.</p><p>As mentioned above, we define our application events and their triggers in a simple `YAML` file.</p><p><strong>Let’s do it 🎉</strong></p><p>In the root of the project, create a file named <strong>serverless.yaml</strong></p><pre>service: serverless-go<br>frameworkVersion: &#39;&gt;= 3.38.0&#39;<br>useDotenv: true<br>provider:<br>  name: aws<br>  runtime: go1.x<br>  region: us-east-1<br>  stage: ${opt:stage}<br><br>functions:<br>  api:<br>    memorySize: 3008<br>    timeout: 10<br>    handler: bin/main<br>    events:<br>      - http:<br>          path: /greetings<br>          method: GET<br><br>package:<br>  patterns:<br>    - bin/*</pre><p><strong>Let’s break this `YAML` configuration down.</strong></p><p>Let me break this configuration down. Think of it as a blueprint for our serverless app on AWS. <strong>Each configuration option in this file is like a piece of the puzzle that will make our serverless application work in the cloud.</strong></p><ul><li><strong>service</strong>: It’s like naming your project; here it’s called &quot;serverless-go.”.</li><li><strong>frameworkVersion:</strong> It specifies the serverless framework version you’re using, ensuring compatibility.</li><li><strong>dotenv</strong>: This tells Serverless to load environment variables from a file called &quot;.env,&quot; keeping secrets safe.</li></ul><p><strong>Provider</strong>:</p><ul><li><strong>name</strong>: “aws” means you’re deploying to Amazon Web Services.</li><li><strong>runtime</strong>: “go1.x” means your code is written in Go.</li><li><strong>region</strong>: “us-east-1” is where your app will live on AWS.</li><li><strong>stage</strong>: This allows different deployment environments (like &quot;dev,&quot; &quot;staging,&quot; and “prod”). Not that the use of <strong>${opt:xxx} </strong>specifies<strong> </strong>we will be passing the stage as an argument from the terminal, when we call the deployment command.</li></ul><p><strong>Functions</strong></p><ul><li><strong>api</strong>: This defines a single function called &quot;api”.</li><li><strong>memorySize</strong>: 3008 MB of memory is allocated for this function.</li><li><strong>timeout</strong>: 10 seconds is the maximum time it can run for each request.</li><li><strong>handler</strong>: “bin/main” tells Serverless where to find your Go code’s entry point.</li><li><strong>events</strong>: These define the triggers that will make your function execute:</li><li><strong>http</strong>: These events tie your function to API endpoints (like “/greetings”).</li></ul><p><strong>Package</strong></p><ul><li><strong>patterns</strong>: This tells Serverless which files to include when packaging your app for deployment.</li></ul><h3>Now we’re ready to deploy 🚀</h3><p>Before that, let’s setup a `Makefile` to avoid typing the same commands repeatedly.</p><p>Create a `<strong>Makefile</strong>` in the root of your project and paste this content.</p><pre>build:<br>env GOOS=linux go build -ldflags=&quot;-s -w&quot; -o bin/main main.go<br>deploy: build<br>serverless deploy - stage prod<br>clean:<br>rm -rf ./bin ./vendor Gopkg.lock ./serverless</pre><p><em>🚨 </em><strong><em>You’ll need to setup your `AWS` profile before deploying, if it’s not yet done. This can be helpful in setting up your account on the local machine.</em></strong></p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html">Configuration and credential file settings</a></p><p>After setting up your AWS account, you can go ahead and deploy the serverless app by running this command</p><pre>make deploy</pre><p>It will take a few minutes for `Serverless` to compile, package, and deploy the application. While waiting, stay calm, `fingers crossed`. (If you want, you can pray for it to work on your first try 😂😂😂). Anyways….</p><p>When the deployment is complete, a link will be generated for each API endpoint defined in the <strong>serverless.yaml</strong> file for you to test your APIs. You can click on that link and test the <strong>`/greetings` GET route</strong>. Normally, you should see a JSON response like this:</p><pre>{<br>  &quot;message&quot;: &quot;Hello friend 👋&quot;<br>}</pre><p><strong>But guess what? It will not work. Instead, you will receive a timeout , resulting in a server error.</strong></p><p>If this happens, there is a reason. Let me explain why.</p><h3>Why does the handler function time out?</h3><p>Well! The reason is that we’re not properly handling our requests. What happened is that the server has started and has emitted the request. But the request is not sent in a way that AWS requires it to be formatted.</p><p>The AWS documentation for the <strong>Lambda function handler in Go</strong> says:</p><p><em>The lambda function handler is the method in your function code that processes events. When your function is invoked, Lambda runs the handler method. Your function runs until the handler returns a response, exits, or times out.</em></p><p><em>A Lambda function written in Go is authored as a Go executable. In your Lambda function code, </em><strong><em>you need to include the `github.com/aws/aws-lambda-go/lambda` package, which implements the Lambda programming model for Go</em></strong><em>. In addition, you need to i</em><strong><em>mplement handler function code</em></strong><em> and a main() function.</em></p><h4>Indeed, we missed a lot of what the documentation says! Let’s fix this.</h4><h3><strong>Refactoring in AWS style</strong></h3><ul><li>First, we need to add the package mentioned in the documentation.</li></ul><pre>go get github.com/aws/aws-lambda-go/lambda</pre><ul><li>Including Gin proxy handler in main</li></ul><p>We now need to refactor our `<strong>main.go</strong>` file to:</p><p>1. Add the handler function code lamda function</p><p>2. Start the lambda server to listen to incoming requests</p><p>3. Wires the lambda function responses to our GIN server: This proxy will act like a bridge between our AWS Lambda functions and our GIN server</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br><br> &quot;github.com/aws/aws-lambda-go/events&quot;<br> &quot;github.com/aws/aws-lambda-go/lambda&quot;<br> ginadapter &quot;github.com/awslabs/aws-lambda-go-api-proxy/gin&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br><br>// AWS gin lambda adapter<br>var ginLambda *ginadapter.GinLambda<br><br>func init() {<br><br> //Set the router as the default one provided by Gin<br> router := gin.Default()<br><br>router.Get(&quot;/greetings&quot;, (c *gin.Context){<br>  c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Hello friend 👋&quot;})<br>})<br><br> <br> // Start and run the server<br> ginLambda = ginadapter.New(router)<br> //router.Run(&quot;:8000&quot;)<br><br><br>// AWS Lambda Proxy Handler<br>// This handler acts like a bridge between AWS Lambda and our Local GIn server<br>// It maps each GIN route to a Lambda function as handler<br>//<br>// This is useful to make our function execution possible.<br>func GinRequestHandler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {<br> return ginLambda.ProxyWithContext(ctx, request)<br>}<br><br>func main() {<br> // Starts Lambda server<br> lambda.Start(GinRequestHandler)<br><br>}</pre><p>After updating our `main.go` file, we can save the file and redeploy again.</p><p>When the deployment is successful, you should see a list of the endpoints with their URLs.</p><p>Go ahead and test the `/greetings` GET route. This time you should receive a success response.</p><pre>{<br>  &quot;message&quot;: &quot;Hello firned 👋&quot;<br><br>}</pre><h3>That’s it! It worked 🎉</h3><h3><strong>Wait! What happened under the hood?</strong></h3><p>To say it all in one, `Serverless` took care of everything for us.</p><p>In fact, serverless uses our expressions and configurations in the `serverless.yaml` file to create an `<strong>AWS Cloud Formation Stack`</strong>.</p><ul><li>After your application is compiled</li><li>Serverless takes the compilation binary and packages it up</li><li>The binary is then uploaded to an <strong>`AWS S3 Bucket`</strong></li><li>Then this binary code will be attached to a Lambda function as handler</li><li>The lambda function is triggered `on` an `AWS API Gateway` event</li></ul><p>All this has been handled by `Serverless`, based on our configuration file.</p><h3><strong>Bonus: What’s next?</strong></h3><p>This is a minimal example of creating serverless RESTful APIs using Go and AWS. You can do a few things to enhance the application. For example, connecting it to a database like Amazon DynamoDB and refactoring the project to add more API endpoints.</p><p>You can find the complete source code for this tutorial here:</p><p><a href="https://github.com/baimamboukar/go-serverless-api">GitHub - baimamboukar/go-serverless-api</a></p><h4>Thanks for reading ❤️‍🔥✨</h4><p>My name is Baimam Boukar. I’m a software engineer, and I enjoy sharing my knowledge through blog posts. I write about Serverless and Go Cloud native applications in AWS, Flutter mobile app development, and Bitcoin development. Let’s stay connected</p><ul><li>Find me on <a href="https://github.com/baimamboukar">Github</a></li><li>Let&#39;s connect on <a href="https://github.com/in/baimamboukar">LinkedIn</a></li></ul><h3><strong>References</strong></h3><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html">AWS Lambda function handler in Go</a></li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html">Environment variables to configure the AWS CLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a277042c1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple RESTful APIs Backend in Go using Gin Gorm and PostgreSQL]]></title>
            <link>https://baimamboukar.medium.com/building-a-simple-restful-apis-backend-in-go-using-gin-gorm-and-postgresql-e247f47c7168?source=rss-4b502c30518------2</link>
            <guid isPermaLink="false">https://medium.com/p/e247f47c7168</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Baimam Boukar Jean Jacques]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 05:31:24 GMT</pubDate>
            <atom:updated>2023-12-29T11:16:21.193Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article serves as a hands-on introduction to the powerful Gin web framework in Golang. You will learn to build a sleek RESTful APIs backend with a practical example.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SQ4l3-jj2kNwBWxGJ5X_g.png" /><figcaption>Build RESTful APIs using Go and Gin</figcaption></figure><p>This article is the first of a series of articles where we will dive deep into building a full-fledged, scalable Go backend! This series will guide you through crafting robust REST APIs with <strong>Gin</strong>, containerizing with <strong>Docker</strong>, monitoring with <strong>Grafana</strong> and <strong>Prometheus</strong>, scaling with <strong>Kubernetes</strong>, carrying load testing with <strong>Hey</strong> and <strong>k6s</strong>, documenting with <strong>Postman</strong>, and deploying to <strong>AWS</strong> (think <strong>Beanstalk</strong> or <strong>ECS</strong>).</p><p>In this article, we will start by introducing Gin and building simple RESTful APIs. We will build a simple RESTful API to manage startups. It sounds more fun than the classic TODO list API, right?</p><p><em>Leeroy Jenkins! Let’s get started 🚀</em></p><h3>Prerequisites</h3><p>Before we start, let’s make sure you have the basics covered:</p><ul><li>Golang installed on your machine</li><li>A Vercel account</li><li>Postman installed</li></ul><h3>Introducing the Go and Gin Duo</h3><blockquote><strong>Gin</strong> is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance — up to 40 times faster. If you need smashing performance, get yourself some Gin.</blockquote><ul><li><strong>Speed and Efficiency</strong>: Go’s built-in concurrency features make it a natural fit for handling multiple requests simultaneously, leading to lightning-fast performance and efficient server utilization.</li><li><strong>Simplicity and maintainability</strong>: Gin’s minimalist design and intuitive API are like a breath of fresh air. It promotes code that’s easy to read, understand, and maintain, reducing the likelihood of errors and simplifying future updates.</li><li><strong>Robust Error Handling</strong>: Gin provides a framework for graceful error handling, ensuring that exceptions are caught and handled appropriately, leading to more stable and reliable APIs.</li><li><strong>Intuitive API and Developer Experience</strong>: Both Go and Gin offer straightforward syntax and well-structured APIs, making development more intuitive and enjoyable, even for those new to the languages.</li></ul><h3>Setting up the Go and Gin project</h3><p>Let’s ignite our Go workspace and get Gin ready to roll!</p><ol><li>Create a project directory. You can name it go-gin-postgresql-backend</li><li>Initialize the Go module: Fire up your terminal within the project directory and execute this command to set up a Go module:</li></ol><pre>go mod init github.com/username/go-gin-postgresql-backend</pre><ul><li>Feel free to customize the package name. However, this package format has become the norm in the Go community since it is adopted by most Go developers.</li><li>This command will generate two vital files for the project: go.mod to manage dependencies and go.sum for dependency checksums.</li></ul><p>3. Construct the folder structure: Establish a well-organized foundation by creating the following directories:</p><pre>- root(go-gin-postgresql-backend)<br>  - go.mod<br>  - go.sum<br>  - Makefile<br>  - .env<br>  - src<br>    - middlewares<br>    - routes<br>    - models<br>    - utils</pre><p>4. We will need a make file that will contain all the common commands that we will be running for this project. Paste this as the content of the Makefile.</p><pre>run:<br>  go run main.go<br><br>install:<br>  go get -u github.com/gin-gonic/gin gorm.io/gorm gorm.io/driver/postgres</pre><p>5. Execute make install to get all required dependencies.</p><p><strong>With these steps complete, your Go workspace is all set for Gin API development.</strong></p><p><em>You can find the source code for this tutorial on Github.</em></p><p><a href="https://github.com/baimamboukar/go-gin-docker-k8s">GitHub - baimamboukar/go-gin-docker-k8s: Small backend example built using Go Gin Docker and K8s backend</a></p><h3>Let’s spin up the Gin Server</h3><p>Now, let’s set up the Gin router and serve a simple “Hello Gin” GET request.</p><pre>// main.go<br>package main<br><br>import &quot;net/http&quot;<br><br>import &quot;github.com/gin-gonic/gin&quot;<br><br><br>func main() {<br>    router := gin.Default()<br><br>    // Simple &quot;Hello Gin&quot; route<br>    router.GET(&quot;/gin&quot;, func(c *gin.Context) {<br>        c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Hello Gin!&quot;})<br>    })<br><br>    // serve and listen to localhost:8080<br>    router.Run(&quot;:8080&quot;)<br>}</pre><p><em>You can now run make run and send a GET request to </em><strong><em>localhost:8080/gin</em></strong><em>. You should receive the expected response.</em></p><h3>Setup CRUD Routers for Startups</h3><p>Let’s first enhance the clarity of our code by refactoring the <strong>main.go</strong> file. This involves setting up a group router specifically for handling Startups, configuring the <strong>.env</strong> file, and establishing the database connection.</p><pre>// main.go<br><br>package main<br><br>import (<br> &quot;github.com/username/go-gin-postgresql-backend/src/middlewares&quot;<br> &quot;github.com/username/go-gin-postgresql-backend/src/routes&quot;<br> &quot;github.com/username/go-gin-postgresql-backend/src/utils&quot;<br>&quot;github.com/username/go-gin-postgresql-backend/src/models&quot;<br>)<br><br>func main() {<br> utils.LoadEnv()<br> models.OpenDatabaseConnection()<br> models.AutoMigrateModels()<br> router := routes.SetupRoutes()<br> router.Run(&quot;:8080&quot;)<br><br>}</pre><p>To load <strong>.env</strong> file, we need to create a function LoadEnv(). This will be useful to store our database secrets.</p><pre>// src/utils/dotenv_loader.go<br><br>package utils<br><br>import (<br> &quot;log&quot;<br><br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>func LoadEnv() {<br> err := godotenv.Load(&quot;.env&quot;)<br> if err != nil {<br>  log.Fatal(&quot;---failed to load .env file---&quot;)<br> }<br>}</pre><h3>Setting up the PostgreSQL Database</h3><p>For the purpose of this article, we’ll use a Vercel-hosted <strong>PostgreSQL</strong> database. Head over to Vercel, create a new Storage, and set up a PostgreSQL DB. Once done, copy the corresponding secrets and paste them into the .env file. The content of the .env file should resemble the following:</p><pre># Database CREDS<br>POSTGRES_URL=&quot;postgres://default:xxxxxxxx/postgres.vercel-storage.com:5432/verceldb&quot;<br>POSTGRES_USER=&quot;default&quot;<br>POSTGRES_HOST=&quot;xxxxxx.postgres.vercel-storage.com&quot;<br>POSTGRES_PASSWORD=&quot;xxxxxxx&quot;<br>POSTGRES_DATABASE=&quot;xxxxxxx&quot;</pre><p>Let’s now set up our database connection using <a href="https://github.com/go-gorm/gorm">GORM</a>. With the database secrets stored in our `.env` file, we’ll seamlessly connect to PostgreSQL. Additionally, we’ll automate the migration of our database models, preparing the ground for model creation and alterations. This ensures smooth and evolving data schema integration.</p><pre>// src/models/db.go<br><br>package models<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br><br> &quot;gorm.io/driver/postgres&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br><br>var Database *gorm.DB<br><br>func OpenDatabaseConnection() {<br> var err error<br> host := os.Getenv(&quot;POSTGRES_HOST&quot;)<br> username := os.Getenv(&quot;POSTGRES_USER&quot;)<br> password := os.Getenv(&quot;POSTGRES_PASSWORD&quot;)<br> databaseName := os.Getenv(&quot;POSTGRES_DATABASE&quot;)<br> port := os.Getenv(&quot;POSTGRES_PORT&quot;)<br><br> dsn := fmt.Sprintf(&quot;host=%s user=%s password=%s dbname=%s port=%s sslmode=require TimeZone=Africa/Douala&quot;, host, username, password, databaseName, port)<br><br> Database, err = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br><br> if err != nil {<br>  panic(err)<br> } else {<br>  fmt.Println(&quot;🚀🚀🚀---ASCENDE SUPERIUS---🚀🚀🚀&quot;)<br> }<br>}<br><br>func AutoMigrateModels() {<br> Database.AutoMigrate(&amp;Startup{})<br>}</pre><p>With our database connection in place, it’s time to configure the routes. But before that, let’s kick things off by setting up our models.</p><pre>// src/models/startup.go<br><br>package models<br><br>import &quot;gorm.io/gorm&quot;<br><br>type Startup struct {<br> gorm.Model<br> Name             string  `json:&quot;name&quot; bson:&quot;name&quot;`<br> CEO              string  `json:&quot;ceo&quot; bson:&quot;ceo&quot;`<br> ValueProposition string  `json:&quot;value_proposition&quot; bson:&quot;value_proposition&quot;`<br> Industry         string  `json:&quot;industry&quot; bson:&quot;industry&quot;`<br> Founder          Founder `json:&quot;founder&quot; bson:&quot;founder&quot; gorm:&quot;embedded&quot;`<br>}<br><br>type Founder struct {<br> gorm.Model<br> Name       string `json:&quot;name&quot; bson:&quot;name&quot;`<br> Profession string `json:&quot;profession&quot; bson:&quot;profession&quot;`<br> Age        int    `json:&quot;age&quot; bson:&quot;age&quot;`<br>}<br><br>// Saves a startup to the database<br>func (startup *Startup) Save() (*Startup, error) {<br> err := Database.Model(&amp;startup).Create(&amp;startup).Error<br> if err != nil {<br>  return &amp;Startup{}, err<br> }<br> return startup, nil<br>}<br><br>// Fetches all startups from the database<br>func FetchAllStartups() (*[]Startup, error) {<br> var startups []Startup<br> err := Database.Find(&amp;startups).Error<br> if err != nil {<br>  return &amp;[]Startup{}, err<br> }<br> return &amp;startups, nil<br>}<br><br>// Fetches a startup from the database<br>func FetchStartup(id string) (*Startup, error) {<br> var startup Startup<br> err := Database.Where(&quot;id = ?&quot;, id).First(&amp;startup).Error<br> if err != nil {<br>  return &amp;Startup{}, err<br> }<br> return &amp;startup, nil<br>}<br><br>// Updates a startup in the database<br>func (startup *Startup) UpdateStartup(id string) (*Startup, error) {<br> err := Database.Model(&amp;Startup{}).Where(&quot;id = ?&quot;, id).Updates(startup).Error<br> if err != nil {<br>  return &amp;Startup{}, err<br> }<br> return startup, nil<br>}<br><br>// Deletes a startup from the database<br>func DeleteStartup(id string) error {<br> err := Database.Model(&amp;Startup{}).Where(&quot;id = ?&quot;, id).Delete(&amp;Startup{}).Error<br> if err != nil {<br>  return err<br> }<br> return nil<br>}</pre><p>Let’s configure our routes now. To efficiently manage startup requests, we’ll use a GIN group router, grouping them together under a unified umbrella. This approach enhances organization and simplifies the handling of startup-related requests.</p><pre>// src/routes/startups.go<br><br>package routes<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br>&quot;github.com/username/go-gin-postgresql-backend/src/routes&quot;<br>)<br><br>func startupsGroupRouter(baseRouter *gin.RouterGroup) {<br> startups := baseRouter.Group(&quot;/startups&quot;)<br><br> startups.GET(&quot;/all&quot;, controllers.GetAllStartups)<br> startups.GET(&quot;/get/:id&quot;, controllers.GetStartupByID)<br> startups.POST(&quot;/create&quot;, controllers.CreateStartup)<br> startups.PATCH(&quot;/update&quot;, controllers.UpdateStartup)<br> startups.DELETE(&quot;/delete/:id&quot;, controllers.DeleteStartup)<br>}<br><br><br>func SetupRoutes() *gin.Engine {<br> r := gin.Default()<br><br> versionRouter := r.Group(&quot;/api/v1&quot;)<br> startupsGroupRouter(versionRouter)<br><br> return r<br>}</pre><p>Declare the handlers within the controllers directory. As we handle routes, we’ll be linking them to the corresponding handlers in the controllers package. It’s time to bring these handlers to life and implement their functionality.</p><pre>// src/controllers/startups_controller.go<br>package controllers<br><br>import (<br> &quot;net/http&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>&quot;github.com/username/go-gin-postgresql-backend/src/models&quot;<br>)<br><br>func GetAllStartups(c *gin.Context) {<br> startups, err := models.FetchAllStartups()<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: err.Error()})<br>  return<br> }<br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Startups fetched successfully&quot;, &quot;status&quot;: &quot;success&quot;, &quot;data&quot;: startups})<br>}<br><br>func GetStartupByID(c *gin.Context) {<br> startupID := c.Param(&quot;id&quot;)<br> if startupID == &quot;&quot; {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Startup ID is required&quot;})<br>  return<br> }<br> startup, err := models.FetchStartup(startupID)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: err.Error()})<br>  return<br> }<br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Startup fetched successfully&quot;, &quot;status&quot;: &quot;success&quot;, &quot;data&quot;: startup})<br>}<br><br>func CreateStartup(c *gin.Context) {<br> var input models.Startup<br> if err := c.ShouldBindJSON(&amp;input); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;status&quot;: &quot;failed&quot;, &quot;message&quot;: err.Error(), &quot;data&quot;: nil})<br>  return<br> }<br> savedStartup, err := input.Save()<br><br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;status&quot;: &quot;failed&quot;, &quot;message&quot;: err.Error(), &quot;data&quot;: nil})<br>  return<br> }<br><br> c.JSON(http.StatusCreated, gin.H{&quot;status&quot;: &quot;success&quot;, &quot;message&quot;: &quot;Startup saved successfully&quot;, &quot;data&quot;: savedStartup})<br>}<br><br>func UpdateStartup(c *gin.Context) {<br> startupID := c.Param(&quot;id&quot;)<br><br> var updatedStartup *models.Startup<br> if err := c.ShouldBindJSON(&amp;updatedStartup); err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;status&quot;: &quot;failed&quot;, &quot;message&quot;: err.Error(), &quot;data&quot;: nil})<br>  return<br> }<br><br> updatedStartup, err := updatedStartup.UpdateStartup(startupID)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;status&quot;: &quot;failed&quot;, &quot;message&quot;: err.Error(), &quot;data&quot;: nil})<br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{&quot;status&quot;: &quot;success&quot;, &quot;message&quot;: &quot;Startup updated successfully&quot;, &quot;data&quot;: updatedStartup})<br>}<br><br>func DeleteStartup(c *gin.Context) {<br> startupID := c.Param(&quot;id&quot;)<br> if startupID == &quot;&quot; {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: &quot;Startup ID is required&quot;})<br>  return<br> }<br><br> err := models.DeleteStartup(startupID)<br> if err != nil {<br>  c.JSON(http.StatusBadRequest, gin.H{&quot;message&quot;: err.Error()})<br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{&quot;message&quot;: &quot;Startup deleted successfully&quot;, &quot;status&quot;: &quot;success&quot;, &quot;data&quot;: nil})<br>}</pre><h3>Bonus: Add Auth Middleware</h3><p>To enhance your RESTful Backend, we can add a minimal authentication middleware that will intercept the requests and resolve the execution of the handler function.</p><pre>// src/middlewares<br><br>package middlewares<br><br>import &quot;github.com/gin-gonic/gin&quot;<br><br>// This middleware authentication is minial<br>// It cehcks if the `x-api-key` heeader is empty.<br>// You can update the middleware and make it work with your own<br>// authentication philosophy<br><br>func AuthMiddleware() gin.HandlerFunc {<br> return func(c *gin.Context) {<br>  apiKey := c.GetHeader(&quot;x-api-key&quot;)<br>  if apiKey == &quot;&quot; {<br>   c.AbortWithStatusJSON(401, gin.H{&quot;error&quot;: &quot;Unauthorized to perform request. Please get a valid API key&quot;})<br>   return<br>  }<br>  c.Next()<br> }<br>}<br><br>// Register middleware on the base router<br>func RegisterMiddlewares(router *gin.Engine) {<br> router.Use(AuthMiddleware())<br>}</pre><p>When that’s done, go ahead and call the <strong>RegisterMiddlewares</strong> function in the main.go file.</p><pre>// main.go<br><br>package main<br><br>import (<br> &quot;github.com/username/go-gin-postgresql-backend/src/middlewares&quot;<br> &quot;github.com/username/go-gin-postgresql-backend/src/routes&quot;<br> &quot;github.com/username/go-gin-postgresql-backend/src/utils&quot;<br> &quot;github.com/username/go-gin-postgresql-backend/src/models&quot;<br>)<br><br>func main() {<br> utils.LoadEnv()<br> models.OpenDatabaseConnection()<br> models.AutoMigrateModels()<br> router := routes.SetupRoutes()<br> middlewares.RegisterMiddlewares(router)<br> router.Run(&quot;:8080&quot;)<br><br>}<br></pre><p>Hi, I’m <a href="https://baimamboukar.dev/">Baimam Boukar</a>, a Software Engineer. I write about Flutter mobile apps, AWS Serverless, and Cloud Native applications using Go. I enjoy building cool Open Source projects with these technologies. Let’s connect and grow together.</p><ul><li>Find me on <a href="https://github.com/baimamboukar">Github</a></li><li>Let’s connect on <a href="https://linkedin.com/in/baimamboukar">LinkedIn</a></li></ul><p>Congratulations ✨! Your RESTful API backend is now ready to roll. Give it a try by sending a POST request to create a new Startup using Postman or any other preferred tool.</p><p><strong><em>Stay tuned! In the next article of this series, we’ll dockerize our app and enhance it with logging and monitoring capabilities using Uber’s Zap, Prometheus, and Grafana. Happy Coding.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e247f47c7168" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>