<?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 Sidaoui Mohamed Amine on Medium]]></title>
        <description><![CDATA[Stories by Sidaoui Mohamed Amine on Medium]]></description>
        <link>https://medium.com/@msidaoui?source=rss-d0d27e298841------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zUWSfNh0BwbKohDEpTSFig.png</url>
            <title>Stories by Sidaoui Mohamed Amine on Medium</title>
            <link>https://medium.com/@msidaoui?source=rss-d0d27e298841------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:05:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msidaoui/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[Virtualization vs Containerization: Understanding the Differences and Choosing the Right Solution]]></title>
            <link>https://msidaoui.medium.com/virtualization-vs-containerization-understanding-the-differences-and-choosing-the-right-solution-cf6bc64d9333?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf6bc64d9333</guid>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 12:16:27 GMT</pubDate>
            <atom:updated>2026-07-07T12:16:27.876Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of modern computing, two technologies dominate when it comes to optimizing resources, deploying applications, and managing environments: <strong>virtualization and containerization</strong>. While both aim to improve efficiency and flexibility, they work differently, have different benefits, and are used in different cases.</p><p>In this article, we will explore these technologies, their differences, and how to choose the best one for your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*U4UDMkEsiG7EDt4tdYfs2Q.png" /></figure><h4>Purpose of This Article</h4><p>By the end of this article, you will be able to:</p><ul><li>Understand the core concepts of virtualization and containerization.</li><li>Learn how Virtual Machines (VMs) and Containers work.</li><li>Discover the role of Hypervisors, Docker, and Kubernetes.</li><li>Compare resource usage, startup time, portability, performance, and isolation.</li><li>Identify the advantages and limitations of each technology.</li><li>Understand when to choose virtualization, containerization, or a combination of both in real-world projects.</li></ul><p><strong>What is Virtualization?</strong></p><p>Virtualization is a technology that allows multiple operating systems to run on a single physical server by creating virtual machines (VMs).</p><p>Each VM operates as an independent computer with its own operating system, applications, and allocated resources (CPU, memory, storage).</p><p>These virtual machines are managed by a hypervisor, which acts as an interface between the physical hardware and the VMs, ensuring their isolation and efficient management.</p><h4>How Does It Work?</h4><p>Virtualization relies on a <strong>hypervisor</strong>, a software that manages virtual machines and allocates hardware resources. There are two types of hypervisors:</p><ul><li><strong>Type 1 Hypervisor (Bare-Metal):</strong> Runs directly on the hardware ( VMware ESXi, Microsoft Hyper-V, KVM).</li><li><strong>Type 2 Hypervisor:</strong> Runs on a host operating system (VirtualBox, VMware Workstation).</li></ul><p><strong>Examples of Virtualization Tools:</strong></p><ul><li><strong>VMware vSphere</strong></li><li><strong>Microsoft Hyper-V</strong></li><li><strong>Oracle VirtualBox</strong></li></ul><p>✅ <strong>Advantages of Virtualization</strong></p><ul><li><strong>Complete Isolation:</strong> Each VM operates independently, improving security and stability.</li><li><strong>Resource Optimization:</strong> Allows multiple systems to run on a single server.</li><li><strong>Compatibility:</strong> Supports different operating systems on the same machine.</li></ul><p>❌ <strong>Disadvantages</strong></p><ul><li><strong>High Resource Consumption:</strong> Each VM includes a full OS, using a lot of memory and storage.</li><li><strong>Relative Slowness:</strong> VMs are heavier than containers due to hardware virtualization.</li></ul><h3>What is Containerization?</h3><p>Containerization is a method that packages an application and all its dependencies (libraries, configuration files, etc.) into a single lightweight container.</p><p>Unlike virtualization, containers share the same host operating system kernel, making them lighter and faster to start.</p><p><strong>Examples of Containerization Tools:</strong></p><ul><li><strong>Docker</strong></li><li><strong>Kubernetes</strong> (for container orchestration)</li></ul><p>✅ <strong>Advantages of Containerization</strong></p><ul><li><strong>Lightweight and Fast:</strong> Containers start in just a few seconds.</li><li><strong>Optimal Resource Usage:</strong> Less resource waste.</li><li><strong>Portability:</strong> Containers can run on any compatible environment.</li><li><strong>Ideal for Modern Application and Microservices Deployment.</strong></li></ul><p>❌ <strong>Disadvantages of Containerization</strong></p><ul><li><strong>Less Isolation:</strong> Containers share the host system’s kernel, which can pose security risks.</li><li><strong>Management Complexity:</strong> Container orchestration (Kubernetes) can be difficult to set up.</li></ul><p><strong>Virtualization vs Containerization: Key Differences</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*Wnf1rqdevZMBtM_kJpLc5Q.png" /></figure><h3>When to Use Virtualization?</h3><p>Virtualization is ideal in the following cases:</p><ul><li>You need to run multiple operating systems on the same server.</li><li>You are working with legacy applications that require a specific environment.</li><li>You need complete isolation between environments for security or compliance reasons.</li></ul><h3>When to Use Containerization?</h3><p>Containerization is perfect for:</p><ul><li>Modern applications based on microservices.</li><li>DevOps environments where rapid deployment and portability are essential.</li><li>Projects requiring optimal resource usage and horizontal scalability.</li></ul><h3>Conclusion: How to Choose?</h3><p>The choice between virtualization and containerization depends on your specific needs:</p><ul><li>If you need complete isolation and the flexibility to run multiple OSs, virtualization is the solution.</li><li>If you’re looking to optimize resources, speed up deployments, and work with modern applications, containerization is the way to go.</li></ul><p>Finally, it’s important to note that these two technologies are not mutually exclusive. In many environments, they coexist to offer the best of both worlds. For example, you can use VMs to host containers, combining isolation and lightweight performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf6bc64d9333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles: From Theory to Clean Code with Spring Boot]]></title>
            <link>https://msidaoui.medium.com/solid-principles-from-theory-to-clean-code-with-spring-boot-6cef98955a91?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cef98955a91</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 12:03:43 GMT</pubDate>
            <atom:updated>2026-06-13T12:03:43.509Z</atom:updated>
            <content:encoded><![CDATA[<p>When developing a <strong>maintainable, testable, and scalable Java/Spring Boot application</strong>, we often hear about the <strong>SOLID principles</strong>.</p><p>But what do they really mean?</p><p>And more importantly, <strong>how can we apply them concretely in Spring Boot?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2_fHL5vnumKm9xVMX2-pag.png" /></figure><h3>Purpose of the Article</h3><ul><li><strong>Understand SOLID principles in general.</strong></li><li><strong>Apply SOLID principles in a Spring Boot context with real-world examples.</strong></li></ul><h3>Definition</h3><p>The <strong>SOLID principles</strong> are a set of <strong>best practices</strong> that help make code <strong>maintainable, scalable, and testable</strong>.<br>These principles are widely used in <strong>object-oriented programming (OOP)</strong> and are particularly useful in <strong>modern architectures such as Spring Boot</strong>.</p><p>The <strong>SOLID</strong> acronym stands for:</p><ul><li><strong>Single Responsibility Principle (SRP)</strong></li><li><strong>Open/Closed Principle (OCP)</strong></li><li><strong>Liskov Substitution Principle (LSP)</strong></li><li><strong>Interface Segregation Principle (ISP)</strong></li><li><strong>Dependency Inversion Principle (DIP)</strong></li></ul><h3>Why SOLID?</h3><ul><li>Avoid <strong>spaghetti code</strong></li><li>Make <strong>unit testing easier</strong></li><li>Improve <strong>reusability and readability</strong></li><li>Promote <strong>code extensibility</strong></li></ul><h3>1. Single Responsibility Principle (SRP)</h3><p>A class should have <strong>only one reason to change</strong>, meaning it should be responsible for <strong>only one task</strong>.</p><p>❌ <strong>Bad example</strong>:<br>A class that:</p><ul><li>Handles <strong>business logic</strong></li><li>Sends <strong>emails</strong></li><li>Accesses the <strong>database</strong></li></ul><p><strong>→ Too many responsibilities</strong></p><p>✅ <strong>Good example</strong>:</p><p><strong>Separate responsibilities:</strong></p><ul><li><strong>Business service</strong></li><li><strong>Repository</strong></li><li><strong>Notification service</strong></li></ul><h4>Advantages</h4><ul><li>Easier <strong>testing</strong></li><li>Fewer <strong>dependencies</strong></li><li>More <strong>understandable and readable</strong> code</li></ul><h4>Drawbacks</h4><p>❌ May <strong>increase the number of classes</strong>, making the project more complex</p><h3>2. Open/Closed Principle (OCP)</h3><p>A class should be <strong>open for extension but closed for modification</strong>.<br> This means new functionality should be added <strong>without changing existing code</strong>.</p><p>❌ <strong>Bad example</strong>:<br> Adding if conditions inside a method to support new payment types.</p><p>✅ <strong>Good example</strong>:<br>Using <strong>inheritance or interfaces</strong> to add new payment types <strong>without modifying the existing class</strong>.</p><h4>Advantages</h4><ul><li>Makes it easier to <strong>add new features</strong></li><li>Prevents <strong>breaking existing code</strong></li></ul><h4>Drawbacks</h4><p>❌ Can <strong>complicate the initial design</strong></p><h3>3. Liskov Substitution Principle (LSP)</h3><p>A <strong>subclass should be able to replace its parent class</strong> without affecting the behavior of the program.</p><p>❌ <strong>Bad example</strong>:<br> A Bird class with a fly() method, inherited by Penguin, which <strong>cannot fly</strong>.</p><p>✅ <strong>Good example</strong>:<br> Replace Bird with an <strong>Animal interface</strong> with sub-interfaces:</p><ul><li>FlyingAnimal</li><li>SwimmingAnimal</li></ul><h4>Advantages</h4><ul><li>More <strong>generic and reusable code</strong></li><li>Avoids <strong>bugs from incompatible subclasses</strong></li></ul><h4>Drawbacks</h4><p>❌ Requires a <strong>good understanding of inheritance</strong></p><h3>4. Interface Segregation Principle (ISP)</h3><p>An interface <strong>should not force a class to implement methods it does not use</strong>.</p><p>❌ <strong>Bad example</strong><br> An Employee interface with a mandatory code() method for an <strong>accountant</strong>.</p><p>✅ <strong>Good example</strong>:<br> Separate into multiple interfaces:</p><ul><li>Developer</li><li>Accountant</li></ul><h4>Advantages</h4><ul><li>Fewer <strong>unused methods</strong></li><li>Easier <strong>dependency management</strong></li></ul><h4>Drawbacks</h4><p>❌ May create <strong>many small interfaces</strong></p><h3>5. Dependency Inversion Principle (DIP)</h3><p>A class should <strong>not depend directly on a concrete implementation</strong>, but on an <strong>abstraction (interface)</strong>.</p><p>❌ <strong>Bad example</strong>:<br> A Car class that depends directly on DieselEngine.</p><p>✅ <strong>Good example</strong>:<br> A Car class that depends on an <strong>Engine interface</strong>, allowing injection of DieselEngine or ElectricEngine.</p><h4>c. Advantages</h4><ul><li>Makes it easier to <strong>change dependencies</strong></li><li>Makes the code more <strong>flexible</strong></li></ul><h4>d. Drawbacks</h4><p>❌ Can be <strong>harder to implement initially</strong></p><h3>SOLID Principles in Spring Boot</h3><p>Spring Boot is a <strong>Java-based framework built on the Spring architecture</strong>, which encourages <strong>best development practices</strong>, including the <strong>SOLID principles</strong>.<br>Let’s see how these principles are <strong>applied concretely</strong> in a Spring Boot application.</p><h4>1. Single Responsibility Principle (SRP)</h4><ul><li>A <strong>Controller</strong> should handle <strong>only HTTP requests</strong></li><li>A <strong>Service</strong> should contain the <strong>business logic</strong></li><li>A <strong>Repository</strong> should interact with the <strong>database</strong></li></ul><p><strong>Example:</strong></p><p>❌ <strong>Bad approach</strong>:<br> Everything is handled inside the <strong>controller</strong></p><p>✅ <strong>Good approach</strong>:<br> Clear <strong>separation of responsibilities</strong></p><h4>2. Open/Closed Principle (OCP)</h4><p><strong>In Spring Boot:</strong></p><p>Using <strong>interfaces</strong> and <strong>Spring annotations</strong> allows adding new features <strong>without modifying existing code</strong>.</p><p><strong>Example:</strong></p><p>Suppose we have a service that <strong>registers a customer</strong>, and we want to add a <strong>new email sending method</strong> without changing the original class.</p><p>❌ <strong>Bad approach</strong>:<br> Directly <strong>modifying the service class</strong></p><pre>public class ClientService {<br><br>    public void saveClient(Client client) {<br>        clientRepository.save(client);<br>        sendEmail(client); // Bad because we modify the existing class<br>    }<br>}</pre><p>✅ <strong>Good approach (using Spring Events):</strong></p><pre>@Service<br>public class ClientService {<br><br>    @Autowired<br>    private ApplicationEventPublisher eventPublisher;<br><br>    public void saveClient(Client client) {<br>        clientRepository.save(client);<br>        eventPublisher.publishEvent(new ClientCreatedEvent(client));<br>    }<br>}<br><br>@Component<br>public class EmailService {<br><br>    @EventListener<br>    public void onClientCreated(ClientCreatedEvent event) {<br>        sendEmail(event.getClient());<br>    }<br>}</pre><p><strong>Advantage</strong><br>We can add other <strong>listeners</strong> (such as SMSService, LoggingService, etc) <strong>without modifying the existing code</strong>.</p><h4>3. Liskov Substitution Principle (LSP)</h4><p><strong>In Spring Boot:</strong></p><p>A <strong>subclass must be able to replace its superclass</strong> without breaking the application’s behavior.</p><p><strong>Example:</strong></p><p>Suppose we have a PaymentService class and we want to add<br> CreditCardPaymentService and PaypalPaymentService.</p><p>❌ <strong>Bad approach</strong>:<br> Using instanceof checks</p><pre>public class PaymentService {<br>    public void processPayment(Object payment) {<br>        if (payment instanceof CreditCard) {<br>            // Credit card processing<br>        } else if (payment instanceof PayPal) {<br>            // Processing for PayPal<br>        }<br>    }<br>}</pre><p>✅ <strong>Good approach (using an interface):</strong></p><pre>public interface PaymentService {<br>    void processPayment();<br>}<br><br>@Service<br>public class CreditCardPaymentService implements PaymentService {<br>    public void processPayment() {<br>        System.out.println(&quot;Pay by credit card&quot;);<br>    }<br>}<br><br>@Service<br>public class PaypalPaymentService implements PaymentService {<br>    public void processPayment() {<br>        System.out.println(&quot;Payment via PayPal&quot;);<br>    }<br>}</pre><p><strong>Advantage:</strong><br> The code <strong>respects the Liskov Substitution Principle</strong> and allows adding <strong>new services without modifying the existing implementation</strong>.</p><h4>4. Interface Segregation Principle (ISP)</h4><p><strong>In Spring Boot:</strong></p><ul><li>Avoid <strong>large interfaces</strong> by creating <strong>specific, focused interfaces</strong>.</li></ul><p><strong>Example:</strong></p><p>❌ <strong>Bad approach</strong>:<br> An interface with <strong>too many unused methods</strong></p><pre>public interface ClientService {<br>    void saveClient(Client client);<br>    void deleteClient(Long id);<br>    void sendEmail(Client client);<br>    void generateReport();<br>}</pre><p>✅ <strong>Good approach (splitting into multiple interfaces):</strong></p><pre>public interface ClientService {<br>    void saveClient(Client client);<br>    void deleteClient(Long id);<br>}<br><br>public interface EmailService {<br>    void sendEmail(Client client);<br>}<br><br>public interface ReportService {<br>    void generateReport();<br></pre><p><strong>Advantage:<br></strong> Each class implements <strong>only what it needs</strong>, avoiding <strong>unnecessary dependencies</strong>.</p><h4>5. Dependency Inversion Principle (DIP) — Dependency Inversion</h4><p><strong>In Spring Boot:</strong></p><ul><li>Always depend on <strong>interfaces or abstractions</strong> rather than <strong>concrete classes</strong>.</li></ul><p><strong>Example:</strong></p><p>❌ <strong>Bad approach</strong>:<br> Depending on a <strong>specific implementation</strong></p><pre>public class ClientService {<br>    private EmailService emailService = new EmailService();<br>}</pre><p>✅ <strong>Good approach (dependency injection with Spring)</strong></p><pre>@Service<br>public class ClientService {<br><br>    private final EmailService emailService;<br><br>    @Autowired<br>    public ClientService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><p><strong>Advantage:</strong></p><ul><li>Easier <strong>unit testing</strong> ( you can inject a MockEmailService)</li><li>Easy to <strong>change implementation</strong> ( SmsService instead of EmailService)</li></ul><h3>Conclusion</h3><p><strong>SOLID principles</strong> are essential in software development, especially in <strong>Object-Oriented Programming (OOP)</strong>. They help create <strong>modular, reusable, and scalable</strong> code.</p><p>✅ <strong>Overall advantages:</strong><br> ✔ Improves code maintainability and readability<br> ✔ Facilitates unit testing<br> ✔ Reduces coupling between classes</p><p>❌ <strong>Overall disadvantages:</strong><br> ❌ Can be difficult to apply for beginners<br> ❌ May sometimes increase the initial complexity of a project</p><p>If you have any questions or want to connect, feel free to reach me on my LinkedIn profile: <a href="https://www.linkedin.com/in/sidaouimohamedamine/">Sidaoui Mohamed Amine</a></p><p>You can find more articles, projects, and source code on my <a href="https://msidaoui.medium.com/">technical blog</a> and <a href="https://github.com/sidaouiMohamedamine">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cef98955a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Apache Kafka and Spring Boot]]></title>
            <link>https://msidaoui.medium.com/getting-started-with-apache-kafka-and-spring-boot-c973868c37cd?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/c973868c37cd</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[asynchronouscommunication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-backend-development]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 21:59:38 GMT</pubDate>
            <atom:updated>2026-02-01T21:59:38.706Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Kafka is today one of the most widely used technologies in distributed and microservice architectures. Originally designed by LinkedIn, Kafka has become a highly scalable event-streaming system capable of handling millions of messages per second.</p><p>In this article, we will explore Kafka step by step, understand why it has become essential in modern systems, and then build a concrete example with Spring Boot to produce and consume messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0gF5TAtUlk_bAkgDihygg.png" /></figure><h3>Objectives of the Article</h3><p>By the end of this article, you will be able to:</p><ul><li>Understand the key concepts of Kafka: Topic, Partition, Broker, Producer, Consumer, Zookeeper/Kafka Controller.</li><li>Understand how Kafka improves communication between microservices.</li><li>Install Kafka locally.</li><li>Create a Producer and a Consumer in Spring Boot.</li><li>Test message sending and receiving.</li></ul><h3>Why Apache Kafka?</h3><p>Kafka is used by major modern companies (Uber, Spotify, Netflix) for several reasons:</p><h4>1. High Performance</h4><p>Kafka supports millions of messages per second, even with limited resources.</p><h4>2. Resilience and Fault Tolerance</h4><p>Kafka replicates data across multiple servers → if a Broker fails, the data remains available.</p><h4>3. Horizontal Scalability</h4><p>Need more throughput?<br>Add more Brokers or increase the topic partitions → no need to modify the application.</p><h4>4. Asynchronous Communication Between Microservices</h4><p>Kafka eliminates strong coupling between services:</p><ul><li>The Producer sends a message</li><li>The Consumer reads it later</li><li>No service needs to know the other</li></ul><h4>5. Persistent Event Storage</h4><p>Kafka stores messages on disk. It is not just a simple “message queue,” but an event store.</p><h3><strong>Apache Kafka Architecture</strong></h3><p>Here are the main components:</p><h4><strong>Broker</strong></h4><p>→ A Broker is a Kafka server.</p><p>→ A Kafka server that receives, stores, and forwards messages.</p><p>→ Multiple brokers form a cluster, ensuring scalability and fault tolerance.</p><p>→ Kafka often runs with at least 3 Brokers for high availability.</p><h4>Topic</h4><p>A topic is a channel or category in which producers send messages and consumers read messages.</p><p><strong>Main Role:</strong></p><ul><li>Organize messages by category or stream type.</li><li>Allow consumers to read only the messages that interest them.</li><li>Support scalability through partitions (each topic can be divided into multiple partitions).</li></ul><h4><strong>Partition</strong></h4><p>Each topic is divided into partitions.<br> Partitions allow you to:</p><ul><li>parallelize message processing</li><li>increase scalability</li><li>distribute data across multiple Brokers</li></ul><p>==&gt; A consumer reads only one partition at a time.</p><h4><strong>Offset</strong></h4><ul><li>The offset is a unique identifier for each message in a partition.</li><li>It indicates the position of the message within the partition.</li><li>Each message in a partition has an offset that increases sequentially.</li></ul><h4><strong>Producer</strong></h4><p>The Producer writes/sends messages to a topic.</p><h4>Consumer</h4><p>The Consumer reads messages from a topic.</p><h4><strong>Consumer Group</strong></h4><p>A consumer group allows load balancing.<br>Each message in a partition will be read only once within the group.</p><h4><strong>Kafka Controller (Zookeeper)</strong></h4><p>Zookeeper is a centralized coordination service used by Kafka to manage the cluster.</p><p><strong>Its main responsibilities:</strong></p><ul><li><strong>Broker tracking</strong>: know which brokers are active in the cluster.</li><li><strong>Partition leader management</strong>: determine which broker is responsible for each partition.</li><li><strong>Coordination and configuration</strong>: stores cluster configuration and ensures synchronization.</li></ul><p>Since Kafka 3.x, Zookeeper is no longer required.</p><p><strong>Before:<br></strong> Kafka = Brokers + Zookeeper (coordination)</p><p><strong>Now:<br></strong> Kafka = Brokers + internal Controller called <strong>KRaft</strong></p><p>So Kafka works on its own, without any external dependency.</p><h3><strong>Kafka in a Microservices Architecture</strong></h3><p>Kafka solves several problems:</p><h4>1. Tight Coupling → Asynchronous Communication</h4><p><strong>Without Kafka:</strong><br> Service A calls Service B directly → strong dependency.</p><p><strong>With Kafka:</strong><br> A sends an Event → Kafka → B reads the Event whenever it wants.</p><h4><strong>2. Reliability</strong></h4><p>Even if the consumer fails, Kafka retains the event → it can be read later.</p><h4><strong>3. Scalability</strong></h4><p>Kafka allows multiple microservices to consume the same event</p><h3><strong>Example</strong></h3><p>When a payment is validated, Kafka broadcasts an event:</p><ul><li><strong>Email Service</strong> → Sends an email</li><li><strong>Delivery Service</strong> → Prepares the order</li><li><strong>Analytics Service</strong> → Updates statistics</li></ul><p>All read the same message without affecting the producer.</p><h3><strong>Kafka Installation</strong></h3><p>First of all, go to the official Kafka website and download it using this link:<br>👉 <a href="https://kafka.apache.org/downloads">https://kafka.apache.org/downloads</a></p><p>Choose:</p><ul><li>Kafka 3.x</li><li>Scala 2.13</li><li>Binary version (.tgz or .zip)</li></ul><p>In my case, I am working on <strong>Windows as the operating system</strong></p><p>Then unzip it to C:/.</p><p>→ Since we installed Kafka 3.x, there is no need to install Zookeeper because it uses KRaft, the built-in controller.</p><h4>Generate the cluster ID</h4><p>then, Open a terminal in the Kafka folder to generate the cluster ID.</p><p>The <strong>Cluster ID</strong> is a unique identifier for your Kafka cluster.</p><pre>.\bin\windows\kafka-storage.bat random-uuid</pre><p>It allows Kafka to recognize and manage the cluster, especially in KRaft mode (without Zookeeper).</p><p>Each cluster has a single Cluster ID, which can be generated automatically or manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*mfJSSuz-jjh6PY9P-bL4tw.png" /></figure><h4>Format Kafka with the Cluster ID</h4><p>Formatting Kafka = preparing the storage folder (log.dirs) for KRaft.</p><p>Kafka creates the necessary internal files, including meta.properties.</p><p>The Cluster ID is provided to uniquely identify this Kafka cluster.</p><p><strong>In summary:</strong> it initializes the cluster storage before starting the KRaft broker.</p><pre>bin\windows\kafka-storage.bat format -t qLBlAiYvQTqAGc2CikjwgQ -c config\kraft\server.properties<br>Formatting metadata directory /tmp/kraft-combined-logs with metadata.version 3.9-IV0.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHUH36XA-kpU9Gn4YWCjRQ.png" /></figure><p>Then start Kafka by running this command:</p><pre>bin\windows\kafka-server-start.bat config\kraft\server.properties</pre><p>Open a new terminal to test, and create a new topic named <strong>test:</strong></p><pre>bin\windows\kafka-topics.bat --create --topic test --bootstrap-server localhost:9092</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHKrL-J8ikFtc1mu3H0v3w.png" /></figure><p>To get information about our topic, run this command:</p><pre>bin\windows\kafka-topics.bat --describe --topic test --bootstrap-server localhost:9092</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ojy-CzSdoyrvKUlJ4-jhag.png" /></figure><h3>Create a Spring Boot project</h3><p>First, go to <strong>Spring Initializr</strong> and generate the required dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S06Kb53POqHoSHZJHDWpvA.png" /></figure><p>Then unzip the project and open it with your preferred IDE.</p><p>Go to the <strong>application.properties</strong>, rename it to <strong>application.yml</strong>, and add the following configuration.</p><pre>spring:<br>  kafka:<br>    bootstrap-servers: localhost:9092<br>    consumer:<br>      group-id: my-group #Unique consumer group identifier<br>      auto-offset-reset: earliest # read messages from the beginning of the topic<br>      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer #Converts the binary message key into a Java type.String in our case<br>      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer #Converts the binary message value into a Java type<br>    producer:<br>      key-serializer: org.apache.kafka.common.serialization.StringSerializer #Converts the key into a binary format to send over Kafka<br>      value-serializer: org.apache.kafka.common.serialization.StringSerializer #Converts the message value into a binary format</pre><p>Next, create a new package <strong>config</strong> and then a class <strong>KafkaTopicConfig</strong>.</p><pre>package com.sid.spring_kafka_project.config;<br><br>import org.apache.kafka.clients.admin.NewTopic;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.kafka.config.TopicBuilder;<br><br>@Configuration<br>public class KafkaTopicConfig {<br><br>    @Bean<br>    public NewTopic createTopic() {<br>        return TopicBuilder.name(&quot;test-topic&quot;)<br>                .partitions(3)<br>                .replicas(1)<br>                .build();<br>    }<br>}</pre><p>This configuration class allows Spring Boot to automatically create a Kafka topic at startup.</p><ul><li><strong>NewTopic</strong> → represents a Kafka topic</li><li><strong>TopicBuilder</strong> → allows easy configuration</li><li><strong>partitions(3)</strong> → Kafka will create 3 partitions</li><li><strong>replicas(1)</strong> → for your local KRaft Kafka setup</li></ul><p>Next, create a <strong>service</strong> package to contain your services, and first create a <strong>producer service</strong>: <strong>MyProducer</strong></p><pre>package com.sid.spring_kafka_project.service;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.kafka.core.KafkaTemplate;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class MyProducer {<br><br>    @Autowired<br>    private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br><br>    public void sendMessage(String message) {<br>        kafkaTemplate.send(&quot;test-topic&quot;, message);<br>        System.out.println(&quot;Message sent: &quot; + message);<br>    }<br>}</pre><p>Then create the <strong>consumer service</strong>.</p><pre>@Service<br>public class MyConsumer {<br><br>    @KafkaListener(topics = &quot;test-topic&quot;, groupId = &quot;my-group&quot;)<br>    public void listen(String msg) {<br>        System.out.println(&quot;Received: &quot; + msg);<br>    }<br>}</pre><p>Now create our controller: create a new package named <strong>restController</strong>, and then create our REST controller named <strong>KafkaController</strong> inside it.</p><pre>package com.sid.spring_kafka_project.restController;<br><br>import com.sid.spring_kafka_project.service.MyProducer;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.PathVariable;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/kafka&quot;)<br>public class KafkaController {<br><br>    @Autowired<br>    private MyProducer producer;<br><br>    @GetMapping(&quot;/send/{msg}&quot;)<br>    public String send(@PathVariable String msg) {<br>        producer.sendMessage(msg);<br>        return &quot;Sent: &quot; + msg;<br>    }<br>}</pre><p>Now start the Spring Boot application, go to Postman, use this URL with the GET method, and you will see the result.</p><h4>Console Producer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*8qTIThbXSsBXXvi5QEJfkA.png" /></figure><h3>Console Consumer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WgYfWnwSaoEU9nXncszNw.png" /></figure><h3>Conclusion</h3><p>Integrating Apache Kafka with Spring Boot means:</p><ul><li>Enabling asynchronous communication between microservices</li><li>Improving system scalability and resilience</li><li>Simplifying event-driven architecture implementation</li></ul><p>We successfully set up Kafka in <strong>KRaft mode</strong>, created producers and consumers, and tested message flow in a Spring Boot application. Throughout this article, we covered the key steps: installing Kafka,test kafaka, configuring Spring Boot, creating topics manually and automatically, and following best practices for microservices.</p><p>You can access and clone the complete project using this link: <a href="https://github.com/sidaouiMohamedamine/springboot-kafka-project">https://github.com/sidaouiMohamedamine/springboot-kafka-project</a></p><p>If you have any questions or want to connect, feel free to reach me on my LinkedIn profile: <a href="https://www.linkedin.com/in/sidaouimohamedamine/">Sidaoui Mohamed Amine</a></p><p>Visit my personal website for more articles and projects: <a href="http://www.sidaouimohamedamine.com/">www.sidaouimohamedamine.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c973868c37cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration of Swagger into a Spring Boot project: Document your APIs clearly and professionally]]></title>
            <link>https://msidaoui.medium.com/integration-of-swagger-into-a-spring-boot-project-document-your-apis-clearly-and-professionally-b55edac1237b?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55edac1237b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[springdoc]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 20:29:41 GMT</pubDate>
            <atom:updated>2025-08-05T20:29:41.063Z</atom:updated>
            <content:encoded><![CDATA[<p>API documentation is just as essential as its development. It ensures that your endpoints are well understood, facilitates collaboration between teams, and improves the maintainability of your application.</p><p>In this article, we’ll explore how to integrate Swagger (via Springdoc OpenAPI) into a Spring Boot project to generate dynamic, interactive, and easy-to-maintain documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbxf3S9dD9jyboVsruJwfQ.png" /></figure><h3>Purpose of the Article</h3><p>By the end of this article, you will be able to:</p><ul><li>Easily integrate Swagger (Springdoc OpenAPI) into a Spring Boot project</li><li>Automatically generate complete and interactive API documentation</li><li>Customize the documentation with precise titles, descriptions, and examples</li><li>Document each endpoint with the appropriate annotations</li><li>Test and explore your APIs directly from Swagger UI</li><li>Export the documentation in JSON or YML format</li></ul><h3>Tools for the Project</h3><p>Before getting started, here’s what you need:</p><p>✅ Java installed (version 17 recommended)<br>✅ Maven installed and configured<br>✅ An IDE such as IntelliJ IDEA, Eclipse, or VS Code<br>✅ A simple REST API with at least one controller</p><h3>What is Swagger (Springdoc OpenAPI)?</h3><p>Swagger (now standardized under the name OpenAPI) is a set of open-source tools that allow you to describe, consume, test, and document a REST API in an interactive and standardized way.</p><p>In the context of Spring Boot, the most popular tool for integrating Swagger is Springdoc OpenAPI, which automates the generation of documentation from source code and annotations.</p><h3>Why use Swagger in a Spring Boot project?</h3><p>Here are the main advantages of using Swagger:</p><ul><li><strong>Automatic documentation</strong>: Endpoints are documented directly from the source code.</li><li><strong>Interactive interface (Swagger UI)</strong>: Allows you to test endpoints directly from a browser without using Postman.</li><li><strong>Readability</strong>: The API structure is clear and easy to understand for developers, testers, and clients.</li><li><strong>Improves coordination between front-end and back-end by providing reliable, real-time documentation.</strong></li><li><strong>Error handling, parameters, data schemas, response types</strong>: Everything is covered in the documentation.</li></ul><h3><strong>Step 1: Add Swagger to Your Spring Boot Project</strong></h3><p>Add the following dependency to your pom.xml file:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>    &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>    &lt;version&gt;2.3.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Then synchronize your project (Maven &gt; Reload Project).</p><h3><strong>Step 2: Access Swagger UI</strong></h3><p>Start your application, then open the following URL in your browser:</p><pre>http://localhost:8081/swagger-ui/index.html</pre><p>In my case, I’m using port <strong>8081</strong>, so make sure to adjust the port accordingly.</p><h3><strong>Step 3: Customize Swagger</strong></h3><p>Add the following to your application.properties file:</p><pre># Defines the URL to access the OpenAPI JSON documentation<br>springdoc.api-docs.path=/api-docs<br># Defines the URL to access the Swagger UI interface (web interface to test the documentation)<br>springdoc.swagger-ui.path=/swagger-ui/v1/employeeManagementSystem<br># Sorts route groups (tags) alphabetically in Swagger UI<br>springdoc.swagger-ui.tagsSorter=alpha<br># Sorts operations (endpoints) by HTTP method (GET, POST, PUT, DELETE)<br>springdoc.swagger-ui.operationsSorter=method</pre><p>Here is a screenshot of my application.properties file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPzdrrjRGIGEsBrB4JBDxw.png" /></figure><p>Then create a configuration class to enrich your documentation:</p><pre>package com.sid.employeeManagementSystemBackend.config;<br><br>import io.swagger.v3.oas.models.OpenAPI;<br>import io.swagger.v3.oas.models.info.Contact;<br>import io.swagger.v3.oas.models.info.Info;<br>import io.swagger.v3.oas.models.info.License;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class SwaggerConfig {<br><br>    @Bean<br>    public OpenAPI customOpenAPI() {<br>        return new OpenAPI()<br>                .info(new Info()<br>                        .title(&quot;Employee Management API&quot;)<br>                        .version(&quot;1.0.0&quot;)<br>                        .description(&quot;Employee Management API Documentation&quot;)<br>                        .contact(new Contact()<br>                                .name(&quot;Sidaoui Mohamed Amine&quot;)<br>                                .email(&quot;mssidaoui@gmail.com&quot;)<br>                                .url(https://medium.com/&quot;https://www.linkedin.com/in/sidaouimohamedamine/&quot;))<br>                        .license(new License()<br>                                .name(&quot;Apache 2.0&quot;)<br>                                .url(https://medium.com/&quot;http://springdoc.org&quot;)));<br>    }<br>}</pre><h3><strong>Step 4: Document the Endpoints</strong></h3><p>Add Swagger annotations to the controller:</p><pre>package com.sid.employeeManagementSystemBackend.controller;<br><br><br>import com.sid.employeeManagementSystemBackend.entity.Employee;<br>import com.sid.employeeManagementSystemBackend.service.EmployeeServiceImpl;<br>import io.swagger.v3.oas.annotations.Operation;<br>import io.swagger.v3.oas.annotations.media.Content;<br>import io.swagger.v3.oas.annotations.media.ExampleObject;<br>import io.swagger.v3.oas.annotations.media.Schema;<br>import io.swagger.v3.oas.annotations.responses.ApiResponse;<br>import io.swagger.v3.oas.annotations.tags.Tag;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br><br>@CrossOrigin(&quot;*&quot;)<br>@RestController<br>@RequestMapping(&quot;api/employee/&quot;)<br>@Tag(name = &quot;Employee&quot;, description = &quot;Employee Operations&quot;)<br>public class EmployeeRestController {<br><br>        @Autowired<br>        private EmployeeServiceImpl employeeService;<br><br>        @Operation(<br>                summary = &quot;Create new employee&quot;,<br>                description = &quot;Create a new employee in the database&quot;,<br>                responses = {<br>                        @ApiResponse(responseCode = &quot;200&quot;, description = &quot;Employee created successfully&quot;),<br>                        @ApiResponse(responseCode = &quot;400&quot;, description = &quot;Invalid Request&quot;)<br>                }<br>        )<br><br>        @PostMapping(&quot;addEmployee&quot;)<br>        public ResponseEntity&lt;Employee&gt; createEmployee(<br>                @io.swagger.v3.oas.annotations.parameters.RequestBody(<br>                        description = &quot;Employee data&quot;,<br>                        required = true,<br>                        content = @Content(<br>                                schema = @Schema(implementation = Employee.class),<br>                                examples = @ExampleObject(<br>                                        value = &quot;&quot;&quot;<br>                    {<br>                      &quot;firstName&quot;: &quot;sidaoui&quot;,<br>                      &quot;lastName&quot;: &quot;Mohamed Amine&quot;,<br>                      &quot;email&quot;: &quot;mssidaoui@gmail.com&quot;<br>                    }<br>                    &quot;&quot;&quot;<br>                                )<br>                        )<br>                )<br>                @RequestBody Employee employee<br>        ) {<br>                return ResponseEntity.ok(employeeService.addEmployee(employee));<br>        }<br><br>        @Operation(summary = &quot;Retreive all employee&quot;)<br>        @GetMapping(&quot;getAllEmployee&quot;)<br>        public List&lt;Employee&gt; getAllEmployee(){<br>            return employeeService.getAllEmployee();<br>        }<br><br>        @Operation(summary = &quot;Retreive an employee by Id&quot;)<br>        @GetMapping(&quot;getEmployeeById/{id}&quot;)<br>        public Employee getEmployeeById(@PathVariable(&quot;id&quot;) Long id){<br>                return employeeService.getEmployeeById(id);<br>        }<br><br>        @Operation(summary = &quot;Update an employee&quot;)<br>        @PutMapping(&quot;updateEmployee/{id}&quot;)<br>        public Employee updateEmployee(@PathVariable(&quot;id&quot;) Long id,@RequestBody Employee employee){<br>                return  employeeService.updateEmployee(id,employee);<br>        }<br>        @Operation(summary = &quot;Delete an employee&quot;)<br><br>        @DeleteMapping(&quot;deleteEmployee/{id}&quot;)<br>        public ResponseEntity&lt;Void&gt; deleteEmployee(@PathVariable Long id){<br>                return employeeService.deleteEmployee(id);<br>        }<br><br>        @Operation(summary = &quot;Get Employee Number&quot;)<br>        @GetMapping(&quot;getEmployeeNumber&quot;)<br>        public Integer getEmployeeNumber(){<br>                return employeeService.getEmployeeNumber();<br>        }<br><br><br><br><br>}</pre><p><strong>@Tag </strong>— Used by Swagger to categorize endpoints<br><strong>@Operation</strong> — Documents a REST method in Swagger<br><strong> @ApiResponse</strong> — Defines the expected response codes</p><p><strong>Now, you can finish the other controllers in the same way</strong></p><h3>Step 5: Test Endpoints in Swagger UI</h3><p>Swagger offers you:</p><ul><li>A detailed description of each endpoint</li><li>Input and output parameters</li><li>A “Try it out” button to execute API calls directly</li><li>Expected HTTP response codes</li></ul><h3>Step 6: Export Your Documentation</h3><p>Swagger exposes your API in the following formats:</p><ul><li>📄 <strong>JSON</strong>: <a href="http://localhost:8080/api-docs">http://localhost:8081/api-docs</a></li><li>📄 <strong>YAML</strong>: <a href="http://localhost:8080/api-docs.yaml">http://localhost:8081/api-docs.yaml</a></li></ul><p>These formats can be used with:</p><ul><li><strong>Swagger Codegen</strong> (to generate API clients)</li><li><strong>Postman</strong> (for automatic import)</li><li><strong>Redoc</strong> (as an alternative way to display the documentation)</li></ul><h3><strong>Conclusion</strong></h3><p>Integrating Swagger into your Spring Boot project means:</p><ul><li>Gaining clarity and professionalism</li><li>Facilitating collaboration between teams</li><li>Speeding up front-end testing and integration</li></ul><p>We successfully integrated Swagger into a Spring Boot project to automatically document our REST APIs. Throughout this article, we covered the key steps: adding dependencies, customizing the Swagger UI interface, documenting endpoints, and exporting files.</p><p>You can access and clone the complete project using this link(<a href="https://github.com/sidaouiMohamedamine/employee-management-backend"><strong>https://github.com/sidaouiMohamedamine/employee-management-backend</strong></a>).</p><p>If you have any questions, feel free to contact me through my LinkedIn profile.<a href="https://www.linkedin.com/in/sidaouimohamedamine/"><strong>https://www.linkedin.com/in/sidaouimohamedamine/</strong></a></p><p><a href="http://www.sidaouimohamedamine.com/"><strong>http://www.sidaouimohamedamine.com/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55edac1237b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Keycloak with Angular and Spring Boot: Complete Guide]]></title>
            <link>https://msidaoui.medium.com/integrating-keycloak-with-angular-and-spring-boot-complete-guide-222fc5663e38?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/222fc5663e38</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[keycloak-integration]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 21:08:19 GMT</pubDate>
            <atom:updated>2025-06-11T21:21:13.113Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will guide you through the step-by-step process of configuring and integrating Keycloak with both Angular and Spring Boot applications. Each section includes clear explanations, helpful screenshots, and the relevant source code. By the end of this guide, you will have a solid understanding of how to implement Keycloak authentication in your full-stack applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*j-26ZWj5A8b0EvMy5jyMmQ.jpeg" /></figure><h3><strong>Purpose of This Article</strong></h3><p>This article aims to guide you through the process of setting up and integrating Keycloak for authentication and authorization in a Spring Boot and Angular application. We will cover the following steps:</p><ol><li><strong>What is Keycloak and Why Use It</strong><br>Understand the concept of Keycloak, its features, and why it’s a preferred solution for managing authentication and authorization in modern web applications.</li><li><strong>Install Keycloak through Docker</strong><br>Learn how to quickly set up a Keycloak instance using Docker, enabling a local identity and access management service for development.</li><li><strong>Configure Keycloak</strong><br>Step-by-step instructions on how to configure Keycloak, including setting up realms, clients, and roles to support secure access control.</li><li><strong>Integrate Keycloak in Spring Boot</strong><br>Integrate Keycloak with your Spring Boot application to manage user authentication and authorization seamlessly.</li><li><strong>Integrate Keycloak with Angular</strong><br>Learn how to integrate Keycloak with your Angular frontend to ensure secure authentication, including login and access control.</li><li><strong>Test the Full Application</strong><br>Verify the complete authentication flow between the Angular frontend, Spring Boot backend, and Keycloak, ensuring everything works as expected.</li></ol><p>By the end of this article, you will have a fully functional application secured by Keycloak, with authentication handled in both the backend (Spring Boot) and the frontend (Angular).</p><h3>Tools to Be Used in This Project:</h3><ul><li><strong>Docker</strong>: To run Keycloak as a container.</li><li><strong>Existing Spring Boot or Angular Project</strong>: If you don’t have one, you can use the following existing projects:</li><li><strong>Frontend</strong>: <a href="https://github.com/sidaouiMohamedamine/employeemanagementfrontend">Employee Management Frontend</a></li><li><strong>Backend</strong>: <a href="https://github.com/sidaouiMohamedamine/employee-management-backend">Employee Management Backend</a></li></ul><h3>What is keycloak</h3><p>Keycloak is an open-source Identity and Access Management (IAM) solution that provides authentication and authorization for applications and services. It is widely used to handle Single Sign-On (SSO), identity management, and user federation in modern applications. Keycloak supports protocols like OAuth 2.0, OpenID Connect, and SAML, making it a robust solution for securing your web and mobile applications. Essentially, it allows you to manage user identities and access control across multiple applications without needing to implement your own authentication system.</p><h3><strong>Why using keycloak</strong></h3><p>Here are some key reasons why you might choose to use Keycloak in your applications:</p><ol><li><strong>Single Sign-On (SSO)</strong>: Users can authenticate once and gain access to multiple applications, improving user experience.</li><li><strong>Federated Identity</strong>: It integrates with third-party identity providers (like Google, Facebook, LDAP, etc.), so users can log in with their existing credentials.</li><li><strong>Social Login</strong>: You can easily add social login (using Google or GitHub) to your application.</li><li><strong>Authorization</strong>: Keycloak allows fine-grained authorization, meaning you can control which users or groups can access certain resources.</li><li><strong>Easy Integration</strong>: Keycloak offers libraries for various programming languages, making it easy to integrate with your apps (like React, Angular, Spring Boot, etc.).</li></ol><h3>Install keycloak</h3><p>To install and run Keycloak 24.0.4 in a Docker container with a single command, you can use the following:</p><pre>docker run -d --name keycloak -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin -p 8080:8080 quay.io/keycloak/keycloak:24.0.4 start-dev</pre><p>tap this command to verify that keycloak is up and running</p><pre>docker ps</pre><p>Once Keycloak is up and running, go to <a href="http://localhost:8080/">http://localhost:8080</a> in your browser, and log in with the admin credentials (admin/admin ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_ZE145lrOGsyFmjZJiSwA.png" /></figure><h3>What is a Realm?</h3><p>A <strong>Realm</strong> in Keycloak is a space where you manage users, roles, clients, and other resources. It’s like a separate environment with its own isolated configurations. Each realm has its own clients, users, and groups, allowing for distinct authentication and authorization rules across different applications or environments.</p><h3>How to Create a Realm</h3><p>Once logged into Keycloak</p><ul><li>In the top-left corner, you should see a dropdown that defaults to <strong>Master</strong> (the default admin realm).</li><li>Select <strong>Create Realm</strong> from the dropdown menu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d3SwH5Dqp54lRi1ligB63Q.png" /></figure><ul><li>Enter a name for your new realm; in my case, I named it <strong>project</strong>.</li><li>Click <strong>Create</strong> to finalize.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9W3ibo_vDzvFUvrvFghbQ.png" /></figure><p>You’ll now be directed to the new realm, where you can start adding clients, users, roles, and other configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT7tpWjwIYmtmAXnWoeDbw.png" /></figure><h3><strong>What is a Client?</strong></h3><p>A <strong>Client</strong> in Keycloak represents an application that Keycloak secures, such as a web or mobile app. The client is responsible for interacting with Keycloak to authenticate users and obtain tokens that allow access to resources.</p><p>Clients define<strong> which applications can use the realm for authentication</strong>. Creating a client allows Keycloak to manage:</p><ul><li>Login flows</li><li>Token issuance (JWTs, for instance) for user authentication</li><li>Permissions and roles that the application (client) can access</li></ul><h3>Relationship Between Realm and Client</h3><ul><li><strong>Realm</strong>: Holds and isolates multiple clients, users, roles, and configurations.</li><li><strong>Client</strong>: Exists within a realm and relies on the realm’s configuration for authentication. Each client is tied to a specific realm, meaning it only has access to users, roles, and settings within that realm.</li></ul><p>By creating a realm and its clients, Keycloak enables secure, managed access to multiple applications within an organized, isolated structure.</p><h3>Create a Client in Keycloak</h3><p>Once the realm is created, click on “Clients” in the left menu.</p><p>Fill in the required fields:</p><ul><li><strong>Client type</strong>: Choose the protocol for the client. Typically, it’s <strong>openid-connect</strong> .</li><li><strong>Client ID</strong>: This is the unique identifier for your client (in my case, i named it <strong>angularspring</strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPKtDZJzld3gc07G4i9Xzw.png" /></figure><p>After the client is created, you will be directed to the <strong>Settings</strong> tab where you can configure the client:</p><ul><li>In the next step, leave it as the default.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDZ-m7IRgZCZl6Hq2ozVNg.png" /></figure><h4><strong>URL Settings</strong>:</h4><ul><li><strong>Root URL</strong>: This is the base URL of your app ( http://localhost:4200). Keycloak uses this as a reference for constructing other URLs if they’re set to be relative.</li><li><strong>Home URL</strong>: This URL is your app’s main landing page (<a href="http://localhost:4200/*">http://localhost:4200/*</a>). If no specific redirect URI is provided after a successful login, Keycloak will default to this page.</li><li><strong>Valid Redirect URIs</strong>: These are URLs to which Keycloak can securely redirect users after successful authentication. You can use wildcards (http://localhost:4200/*) to allow redirects to different routes within your app.</li><li><strong>Valid Post Logout Redirect URIs</strong>: Specifies where users can be redirected after logging out from Keycloak(<a href="http://localhost:4200/*">http://localhost:4200/*</a>). This is a security feature to ensure users are only redirected to trusted URLs after logout.</li><li><strong>Web Origins</strong>: Defines allowed origins for CORS (Cross-Origin Resource Sharing). CORS ensures that your app can securely communicate with Keycloak, enabling requests to authenticate users from the specified origin (*).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSwLGsN6PvQqeLNR0yw5zQ.png" /></figure><h4>Creating Roles</h4><p>We will now create two roles in our client: <strong>user and admin.</strong></p><p>In your selected client, navigate to the <strong>Roles</strong> tab. Here, you can create and manage roles specific to this client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cJTgOt0AYsv_9os2S12OA.png" /></figure><h3>Create a user in keycloak</h3><p>In the left sidebar, click on <strong>Users</strong>.</p><h4><strong>Create a User</strong>:</h4><ul><li>In the left sidebar, go to <strong>Users.</strong></li><li>Click on the <strong>Create new user</strong> in the middle.</li><li>Fill in the required fields (like <strong>Username</strong>). You can also add <strong>Email</strong>, <strong>First Name</strong>, and <strong>Last Name</strong> if desired.</li><li>Make sure to turn on <strong>Email Verified</strong>.</li><li>Click <strong>Create</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3PkQqWqkAdyvnQQmY936g.png" /></figure><h4><strong>Set a Password</strong></h4><ul><li>After creation, go to the <strong>Credentials</strong> tab.</li><li>Set a password for the user, disable <strong>Temporary Password, </strong>and click <strong>Set Password</strong>.</li></ul><h3><strong>Integrate keycloak with angular</strong></h3><p>To integrate Keycloak with an Angular application, you can use the keycloak-angular library, which simplifies working with Keycloak in Angular applications.</p><p><strong>First, install the required packages</strong>. If you’re using a different version of Keycloak, visit the official npm website <a href="https://www.npmjs.com/package/keycloak-js/v/24.0.4?activeTab=versions">here</a>, select the desired version, and install it. In my case, I’m using version 24.0.4.</p><pre>npm i keycloak-js@24.0.4</pre><p>Now, in the terminal, run this command to create a Keycloak service that will contain all the necessary Keycloak functionalities.</p><pre>ng g s services/keycloak</pre><p>Next, include this code in the service.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import Keycloak from &#39;keycloak-js&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class KeycloakService {<br> // Declaring a private variable to hold the Keycloak instance<br> private keycloakAuth: any;<br><br> constructor() {} <br><br> // Method to initialize Keycloak and return a promise indicating if authentication was successful<br> init(): Promise&lt;any&gt; {<br>   // Configuration object for Keycloak, containing the server URL, realm, and client ID<br>   const keycloakConfig = {<br>     url: &#39;http://localhost:8080&#39;, // URL of the Keycloak server<br>     realm: &#39;project&#39;,             // Name of the Keycloak realm<br>     clientId: &#39;angularspring&#39;,     // Client ID registered in Keycloak<br>   };<br><br>   // Initializing a new Keycloak instance with the specified configuration<br>   this.keycloakAuth = new Keycloak(keycloakConfig);<br><br>   // Returning a promise that will resolve if Keycloak initializes successfully<br>   return new Promise((resolve, reject) =&gt; {<br>     // Initiating the Keycloak authentication process with configuration options<br>     this.keycloakAuth.init({ onLoad: &#39;login-required&#39;, checkLoginIframe: false }).then(<br>       (authenticated: boolean) =&gt; {<br>         // Logs successful initialization with the authentication status<br>         console.log(&#39;Keycloak initialized&#39;, authenticated);<br>         resolve(authenticated); // Resolves the promise if authenticated<br>       },<br>       (error: any) =&gt; {<br>         // Logs any error that occurs during initialization<br>         console.error(&#39;Keycloak initialization failed&#39;, error);<br>         reject(error); // Rejects the promise if there was an error<br>       }<br>     );<br>   });<br> }<br><br> // Method to start the Keycloak login process<br> login(): void {<br>   this.keycloakAuth.login(); // Triggers the Keycloak login<br> }<br><br> // Method to log the user out and redirect them to the application&#39;s home page<br> logout(): void {<br>   this.keycloakAuth.logout({ redirectUri: window.location.origin }); // Triggers Keycloak logout with a redirect<br> }<br><br> // Method to get the current authentication token<br> getToken(): string {<br>   return this.keycloakAuth.token || &#39;&#39;; // Returns the token if available, otherwise an empty string<br> }<br><br> // Method to check if the user is authenticated<br> isAuthenticated(): boolean {<br>   return !!this.keycloakAuth.token; // Returns true if there is a token, indicating user is authenticated<br> }<br><br> // Method to get the username of the currently authenticated user<br> getUsername(): string {<br>   return this.keycloakAuth.tokenParsed?.preferred_username || &#39;&#39;; // Returns the username from the token if available<br> }<br><br> // Method to get the roles assigned to the user<br> getRoles(): string[] {<br>   return this.keycloakAuth.tokenParsed?.realm_access?.roles || []; // Returns an array of roles if available<br> }<br>}</pre><p>Now, open app.module.ts and update it as follows.</p><pre>import { APP_INITIALIZER, NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br><br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { CreateEmployeeComponent } from &#39;./components/create-employee/create-employee.component&#39;;<br>import { EmployeeListComponent } from &#39;./components/employee-list/employee-list.component&#39;;<br>import { UpdateEmployeeComponent } from &#39;./components/update-employee/update-employee.component&#39;;<br>import { NavbarComponent } from &#39;./components/navbar/navbar.component&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import {  HttpClientModule } from &#39;@angular/common/http&#39;;<br>import { KeycloakService } from &#39;./services/keycloak.service&#39;;<br><br>export function initializeKeycloak(keycloakService: KeycloakService) {<br>  return (): Promise&lt;any&gt; =&gt; keycloakService.init();<br>}<br><br>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    CreateEmployeeComponent,<br>    EmployeeListComponent,<br>    UpdateEmployeeComponent,<br>    NavbarComponent,<br>  ],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    FormsModule,<br>    HttpClientModule<br>  <br>  ],<br>  providers: [<br>    {<br>      provide: APP_INITIALIZER,<br>      useFactory: initializeKeycloak,<br>      deps: [KeycloakService],<br>      multi: true,<br>    },<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>Here is a screenshot of mine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQm9xENkjaZ5QYunLPuJ6w.png" /></figure><h4>Protect the route</h4><p>Now, you need to protect routes and only allow access when the user is authenticated with Keycloak. You can create a <strong>Keycloak Guard</strong> for route protection.</p><p><strong>Create the Keycloak Guard</strong>: Create a guard file keycloak.guard.ts to manage route access based on authentication.so go to the terminal and press this command:</p><pre>ng generate guard services/keycloak </pre><p>And include the code as shown below.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { KeycloakService } from &#39;./keycloak.service&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class KeycloakGuard implements CanActivate {<br>  constructor(private authService: KeycloakService, private router: Router) {}<br><br>  async canActivate(): Promise&lt;boolean&gt; {<br>    const isAuthenticated = await this.authService.isAuthenticated();<br>    if (!isAuthenticated) {<br>      this.router.navigate([&#39;/login&#39;]); // Redirect to the login page<br>      return false;<br>    }<br>    return true;<br>  }<br>  <br>}<br></pre><p>Next, navigate to the app-routing.module file, and update the routes</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { EmployeeListComponent } from &#39;./components/employee-list/employee-list.component&#39;;<br>import { CreateEmployeeComponent } from &#39;./components/create-employee/create-employee.component&#39;;<br>import { UpdateEmployeeComponent } from &#39;./components/update-employee/update-employee.component&#39;;<br>import { KeycloakGuard } from &#39;./services/keycloak.guard&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;employees&#39;, component: EmployeeListComponent , canActivate: [KeycloakGuard],},<br>  { path: &#39;add-employee&#39;, component: CreateEmployeeComponent, canActivate: [KeycloakGuard], },<br>  { path: &#39;update-employee/:id&#39;, component: UpdateEmployeeComponent, canActivate: [KeycloakGuard], },<br>  { path: &#39;&#39;, redirectTo: &#39;/employees&#39;, pathMatch: &#39;full&#39;},<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>Now, go to the navbar component’s TypeScript file, and add the following code.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { KeycloakService } from &#39;src/app/services/keycloak.service&#39;;<br><br>@Component({<br>  selector: &#39;app-navbar&#39;,<br>  templateUrl: &#39;./navbar.component.html&#39;,<br>  styleUrls: [&#39;./navbar.component.css&#39;]<br>})<br>export class NavbarComponent {<br>  constructor(public keycloakService: KeycloakService) {}<br><br>  login() {<br>    this.keycloakService.login();<br>  }<br><br>  logout() {<br>    this.keycloakService.logout();<br>  }<br>}</pre><p>Then, update the HTML file</p><pre>&lt;nav class=&quot;navbar navbar-expand-lg bg-body-tertiary&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>      &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Employee&lt;/a&gt;<br>      &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarScroll&quot; aria-controls=&quot;navbarScroll&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;<br>        &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>      &lt;/button&gt;<br>      &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarScroll&quot;&gt;<br>        &lt;ul class=&quot;navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll&quot; style=&quot;--bs-scroll-height: 100px;&quot;&gt;<br>          &lt;li class=&quot;nav-item&quot;&gt;<br>            &lt;a routerLink=&quot;employees&quot;  class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Employee List&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li class=&quot;nav-item&quot;&gt;<br>            &lt;a routerLink=&quot;add-employee&quot; class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Add Employee&lt;/a&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;form class=&quot;d-flex&quot; role=&quot;search&quot;&gt;<br>          &lt;button class=&quot;btn btn-outline-danger&quot; (click)=&quot;logout()&quot;&gt;logout&lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/nav&gt;</pre><h3>Integrate keycloak with Spring Boot</h3><p>Next, we will integrate Keycloak with Spring Boot. Begin by opening the pom.xml file in your Spring Boot project and adding the OAuth2 dependency, which provides a standardized way to manage secure access to resources via token-based authentication.</p><pre> &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-oauth2-resource-server&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><p>Next, right-click on the pom.xml file and reload the project.</p><p>Then, go to the application.properties file and add the following lines.</p><pre># The URI of the authorization server&#39;s issuer. This is the base URL of the Keycloak realm.<br>spring.security.oauth2.resourceserver.jwt.issuer-uri = http://localhost:8080/realms/project<br></pre><p>Create a new folder named configuration in your project. Inside this folder, add two classes: KeycloakJwtAuthenticationConverter and SecurityConfig.</p><p>Then, add the following code inside the KeycloakJwtAuthenticationConverter and SecurityConfig classes to configure Keycloak JWT authentication in your Spring Boot application.</p><pre>package com.sid.employeeManagementSystemBackend.configuration;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;<br>import org.springframework.web.cors.CorsConfiguration;<br>import org.springframework.web.cors.UrlBasedCorsConfigurationSource;<br>import org.springframework.web.filter.CorsFilter;<br><br>import java.util.Arrays;<br>import java.util.Collections;<br><br>import static org.springframework.security.config.Customizer.withDefaults;<br><br>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>@EnableMethodSecurity(securedEnabled = true)<br>public class SecurityConfig {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>                .cors(withDefaults())<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .authorizeHttpRequests(req -&gt;<br>                        req.requestMatchers(<br>                                        &quot;/api/**&quot;,<br>                                        &quot;/v2/api-docs&quot;,<br>                                        &quot;/v3/api-docs&quot;,<br>                                        &quot;/v3/api-docs/**&quot;,<br>                                        &quot;/swagger-resources&quot;,<br>                                        &quot;/swagger-resources/**&quot;,<br>                                        &quot;/configuration/ui&quot;,<br>                                        &quot;/configuration/security&quot;,<br>                                        &quot;/swagger-ui/**&quot;,<br>                                        &quot;/webjars/**&quot;,<br>                                        &quot;/swagger-ui.html&quot;<br>                                )<br>                                .permitAll()<br>                                .anyRequest()<br>                                .authenticated()<br>                )<br>                .oauth2ResourceServer(auth -&gt;<br>                        auth.jwt(token -&gt; token.jwtAuthenticationConverter(new KeycloakJwtAuthenticationConverter())));<br><br><br>        return http.build();<br>    }<br><br><br>    @Bean<br>    public CorsFilter corsFilter() {<br>        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>        final CorsConfiguration config = new CorsConfiguration();<br>        config.setAllowCredentials(true);<br>        config.setAllowedOrigins(Collections.singletonList(&quot;http://localhost:4200&quot;));<br>        config.setAllowedHeaders(Arrays.asList(<br>                HttpHeaders.ORIGIN,<br>                HttpHeaders.CONTENT_TYPE,<br>                HttpHeaders.ACCEPT,<br>                HttpHeaders.AUTHORIZATION<br>        ));<br>        config.setAllowedMethods(Arrays.asList(<br>                &quot;GET&quot;,<br>                &quot;POST&quot;,<br>                &quot;DELETE&quot;,<br>                &quot;PUT&quot;,<br>                &quot;PATCH&quot;<br>        ));<br>        source.registerCorsConfiguration(&quot;/**&quot;, config);<br>        return new CorsFilter(source);<br><br>    }<br>}</pre><pre>package com.sid.employeeManagementSystemBackend.configuration;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;<br>import org.springframework.web.cors.CorsConfiguration;<br>import org.springframework.web.cors.UrlBasedCorsConfigurationSource;<br>import org.springframework.web.filter.CorsFilter;<br><br>import java.util.Arrays;<br>import java.util.Collections;<br><br>import static org.springframework.security.config.Customizer.withDefaults;<br><br>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>@EnableMethodSecurity(securedEnabled = true)<br>public class SecurityConfig {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {<br>        http<br>                .cors(withDefaults())<br>                .csrf(AbstractHttpConfigurer::disable)<br>                .authorizeHttpRequests(req -&gt;<br>                        req.requestMatchers(<br>                                        &quot;/api/**&quot;,<br>                                        &quot;/v2/api-docs&quot;,<br>                                        &quot;/v3/api-docs&quot;,<br>                                        &quot;/v3/api-docs/**&quot;,<br>                                        &quot;/swagger-resources&quot;,<br>                                        &quot;/swagger-resources/**&quot;,<br>                                        &quot;/configuration/ui&quot;,<br>                                        &quot;/configuration/security&quot;,<br>                                        &quot;/swagger-ui/**&quot;,<br>                                        &quot;/webjars/**&quot;,<br>                                        &quot;/swagger-ui.html&quot;<br>                                )<br>                                .permitAll()<br>                                .anyRequest()<br>                                .authenticated()<br>                )<br>                .oauth2ResourceServer(auth -&gt;<br>                        auth.jwt(token -&gt; token.jwtAuthenticationConverter(new KeycloakJwtAuthenticationConverter())));<br><br><br>        return http.build();<br>    }<br><br><br>    @Bean<br>    public CorsFilter corsFilter() {<br>        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();<br>        final CorsConfiguration config = new CorsConfiguration();<br>        config.setAllowCredentials(true);<br>        config.setAllowedOrigins(Collections.singletonList(&quot;http://localhost:4200&quot;));<br>        config.setAllowedHeaders(Arrays.asList(<br>                HttpHeaders.ORIGIN,<br>                HttpHeaders.CONTENT_TYPE,<br>                HttpHeaders.ACCEPT,<br>                HttpHeaders.AUTHORIZATION<br>        ));<br>        config.setAllowedMethods(Arrays.asList(<br>                &quot;GET&quot;,<br>                &quot;POST&quot;,<br>                &quot;DELETE&quot;,<br>                &quot;PUT&quot;,<br>                &quot;PATCH&quot;<br>        ));<br>        source.registerCorsConfiguration(&quot;/**&quot;, config);<br>        return new CorsFilter(source);<br><br>    }<br>}</pre><p><strong>Advanced Keycloak configurations</strong></p><p>Now, we’ll enhance our application with advanced Keycloak configurations, such as adding a <strong>user registration page</strong>, implementing a <strong>Forgot Password</strong> feature, and <strong>enabling email verification</strong>.</p><p>In the left sidebar, navigate to <strong>Realm Settings</strong>, then click on the <strong>Login</strong> tab. Enable <strong>User Registration</strong>, <strong>Forgot Password</strong>, and <strong>Login with Email</strong> to enhance login and account management features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79iSja62ILd0KBOXjQpbUw.png" /></figure><p>Login page before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skkJsQBE0dVD9TT14pXlHA.png" /></figure><p>you can notice the difference between the previous screenshot and the current one after enabling the new configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7xgf9GRBwXS-tuLNOWY2w.png" /></figure><p>Now, as you can see, the login page title is set to the default name of the realm. We will customize it to fit our needs.</p><p>So navigate to general, and put the name you want in the section <strong>Display name </strong>and click on<strong> save</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxKDnPl2e058Nplu1_W92g.png" /></figure><p>And here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTsbQa1BtZZGnprItDg77A.png" /></figure><h3>Conclusion</h3><p>Finally, we have successfully integrated Keycloak with both Angular and Spring Boot. We covered the installation, configuration, and integration steps for both frameworks. You can access and clone the project using this link(<a href="https://github.com/sidaouiMohamedamine/angular-springboot-keycloak">https://github.com/sidaouiMohamedamine/angular-springboot-keycloak</a>) to personalize it according to your needs.</p><p>If you have any questions, feel free to contact me through my LinkedIn profile.<a href="https://www.linkedin.com/in/sidaouimohamedamine/"><strong>https://www.linkedin.com/in/sidaouimohamedamine/</strong></a></p><p><a href="http://www.sidaouimohamedamine.com/"><strong>http://www.sidaouimohamedamine.com/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222fc5663e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON Web Token (JWT): Everything You Need to Know About Securing Web Services]]></title>
            <link>https://msidaoui.medium.com/json-web-token-jwt-everything-you-need-to-know-about-securing-web-services-8786707971d7?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/8786707971d7</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[jwt-token]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 12:26:23 GMT</pubDate>
            <atom:updated>2025-02-04T12:53:19.302Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore everything you need to know about JWTs, from their structure to best practices for use, providing you with the tools to effectively secure your web services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*FS8ppWURmQiZp52h.jpeg" /></figure><p>As modern web applications become more interactive and require increased security, authentication and session management play a central role. JSON Web Token (JWT) has emerged as an essential standard for securing APIs and web services.</p><h3>What is a JSON Web Token (JWT)?</h3><p>A JWT is a security token in JSON format that allows secure information exchange between two parties. This token contains data in the form of key-value pairs and is typically digitally signed to ensure its integrity. JWTs are widely used for authentication in web applications because they are easy to use, lightweight, and secure.</p><h3>JWT Structure</h3><p>A JWT consists of three distinct parts, each encoded in Base64 and separated by periods (.) :</p><pre>&lt;Header&gt;.&lt;Payload&gt;.&lt;Signature&gt;</pre><h3>Header</h3><p>The header of the JWT specifies two main pieces of information:</p><ul><li><strong>Typ</strong>: The type of the token, which is typically JWT.</li><li><strong>Alg</strong>: The algorithm used to sign the JWT, such as HS256 (HMAC with SHA-256), RS256 (RSA with SHA-256), etc.</li></ul><h3>Example of JSON Header</h3><pre>{<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;alg&quot;: &quot;HS256&quot;<br>}</pre><p>Once the header is defined, it is serialized into JSON and then encoded in Base64URL.</p><h3>Payload</h3><p>The JWT payload contains the information you want to transmit, known as claims. Claims are statements that make assertions about an entity (usually the user) and metadata related to that entity.</p><p>There are three types of claims:</p><ul><li><strong>Registered claims</strong>: Standardized and recommended claims in JWT, such as:</li><li><strong>iss (Issuer)</strong>: The issuer of the token.</li><li><strong>sub (Subject)</strong>: The subject of the token (usually the user ID).</li><li><strong>aud (Audience)</strong>: The audience for which the token is intended.</li><li><strong>exp (Expiration Time)</strong>: The token’s expiration date (in seconds since the epoch).</li><li><strong>nbf (Not Before)</strong>: The date before which the token should not be accepted.</li><li><strong>iat (Issued At)</strong>: The date the token was issued.</li><li><strong>Public claims</strong>: Custom claims defined by the user, but they may cause conflicts if not uniquely defined.</li><li><strong>Private claims</strong>: Custom claims used in specific, private contexts and not shared publicly.</li></ul><h3>Example of JSON Payload</h3><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Ramez&quot;,<br>  &quot;iat&quot;: 1516239022<br>}</pre><p>The payload is also serialized in JSON, then encoded in Base64URL.</p><h3>Signature</h3><p>The signature <strong>allows the recipient of the JWT</strong> <strong>to verify that the sender is who they claim to be</strong> and that the message has not been tampered with during transmission.</p><p>The signature is used to verify the integrity of the token and to ensure that the party generating the JWT is who it claims to be. To create the signature, you need to use the header and the payload, along with a secret key. The process varies depending on the signing algorithm chosen in the header:</p><ul><li><strong>For the HMAC SHA-256 algorithm (HS256)</strong>, the signature is generated using the secret key.</li><li><strong>For the RSA SHA-256 algorithm (RS256)</strong>, the signature is generated using a private RSA key.</li><li>The signature is calculated as follows:</li></ul><pre>HMACSHA256(base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),secret)</pre><h3>Summary of the role of each part</h3><ul><li><strong>Header</strong>: Contains information about the type of token and the signing algorithm.</li><li><strong>Payload</strong>: Contains the information to be transmitted in the form of claims.</li><li><strong>Signature</strong>: Ensures the integrity and authenticity of the JWT by verifying that it has not been altered.</li></ul><h3>Usage of JWT</h3><p>JWTs are used in various contexts, but their primary use cases are in authentication and authorization:</p><ul><li><strong>Authentication: </strong>When a user logs in, the server generates a JWT and sends it back to the client (often in cookies or HTTP headers). The client then sends this JWT with subsequent requests to prove their identity.</li><li><strong>Authorization:</strong> The JWT can include information about the user’s roles and permissions, allowing the server to control access to resources based on this data.</li></ul><h3>Why Use JWT for Authentication?</h3><p>JWT is commonly used to replace session cookies in modern API-based architectures. Here are some benefits:</p><ul><li><strong>Stateless</strong>: The server does not need to maintain session state, which improves scalability. Each request is independent, as all the necessary information is stored in the JWT itself.</li><li><strong>Flexibility</strong>: JWTs can be used with any frontend and backend technology, making them versatile and easy to integrate across different systems and platforms.</li><li><strong>Secure Transport</strong>: By using secure protocols like HTTPS, the data carried within the JWT remains confidential during transmission, protecting it from eavesdropping or tampering.</li></ul><h3>Best Practices for Using JWT Securely</h3><ul><li><strong>Use Robust Signing Algorithms</strong>: Prefer secure signing algorithms like RS256. Avoid HS256 if security is critical, as it relies on a shared secret key.</li><li><strong>Limit Token Lifetime</strong>: Set a short expiration time (exp) for the token to reduce the risk in case the token is compromised.</li><li><strong>Transmit the Token Securely</strong>: Ensure JWTs are transmitted only over HTTPS connections to prevent interception.</li><li><strong>Store JWT Securely</strong>: Avoid storing JWTs in localStorage, as it is vulnerable to XSS attacks. Instead, use httpOnly cookies when possible for better security.</li><li><strong>Revoke Tokens</strong>: Although JWT is stateless, implement a mechanism to revoke compromised tokens. A “blacklist” can be used to invalidate certain tokens before they expire.</li></ul><h3>Using JWT for Authentication</h3><ol><li><strong>User Authentication</strong>: The user provides their credentials (username and password) to log in to the application.</li><li><strong>JWT Generation</strong>: Once the user is authenticated, the server generates a JSON Web Token (JWT) that contains information about the user and their access rights.</li><li><strong>Storing the JWT</strong>: The token is then sent back to the client and is typically stored in the browser’s localStorage or cookies, allowing the client to use it for future requests.</li><li><strong>Using JWT for Accessing Secure Resources</strong>: When a request is made to access a protected resource, the client includes the JWT in the HTTP request header as follows:</li></ol><pre>Authorization: Bearer &lt;jwt_token&gt;</pre><p>This mechanism allows the server to validate the authenticity of the token and decide whether to grant access to the requested resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*OLB6vxUWXd4S1EUC.jpeg" /></figure><h3>Limitations of JWT</h3><p>Despite its many advantages, JWT has some drawbacks. Once a JWT is issued, it remains valid until its expiration, even if the user logs out or their permissions change. As a result, it is necessary to combine JWT with revocation mechanisms to ensure enhanced security.</p><h3>Conclusion</h3><p>JSON Web Token (JWT) is an excellent tool for enhancing the security of web services by enabling efficient authentication and session management. However, proper usage and stringent security measures are essential to avoid vulnerabilities. By following best practices, JWT can significantly contribute to protecting your users’ data and ensuring the security of your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8786707971d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Angular (CRUD )]]></title>
            <link>https://msidaoui.medium.com/getting-started-with-angular-crud-e50393c24ab8?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/e50393c24ab8</guid>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[full-stack-development]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 00:37:36 GMT</pubDate>
            <atom:updated>2025-01-01T00:37:36.217Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will build our Angular application step by step. Each stage includes clear explanations, helpful screenshots and source code. By the end, you’ll have a solid foundation in Angular development and the confidence to create your own applications from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HXCJCOpzKdmQI33ZrEIlg.png" /></figure><h3>Purpose of This Article</h3><p>In this article, we will cover the following objectives:</p><ol><li><strong>Understanding Angular</strong>: What is Angular and why is it widely used for building dynamic web applications?</li><li><strong>Installing and Building an Angular Application</strong>: A step-by-step guide on setting up your Angular environment and creating your first project.</li><li><strong>Integrating Bootstrap 5 with Angular</strong>: How to enhance your UI with Bootstrap 5, making it responsive and visually appealing.</li><li><strong>Using FontAwesome for Icons</strong>: How to integrate FontAwesome into your Angular project to enhance the UI with scalable vector icons.</li><li><strong>Creating Dynamic Components</strong>: Learn how to create reusable and dynamic components to build your application’s interface.</li><li><strong>Working with Template-Driven Forms for Validation</strong>: We will implement Angular template-driven forms to manage user input and perform validation seamlessly.</li><li><strong>Creating and Consuming CRUD APIs with Spring Boot</strong>: We will work with an existing backend project (<a href="https://github.com/sidaouiMohamedamine/employee-management-backend">https://github.com/sidaouiMohamedamine/employee-management-backend</a>) to build and consume APIs for handling CRUD operations.</li></ol><h3>Technical Requirements</h3><p>To get the most out of this article, you should have the following prerequisites:</p><ol><li><strong>Basic Web Development Knowledge</strong>: A foundational understanding of how the web works and the structure of web applications.</li><li><strong>Basic Skills in HTML and CSS</strong>: Familiarity with HTML for structuring content and CSS for styling components to create responsive and visually appealing pages.</li><li><strong>Knowledge of JavaScript or TypeScript</strong>: Basic understanding or experience with JavaScript or TypeScript, as Angular is built with TypeScript, and a good grasp of it will help you follow along effectively.</li></ol><h3>Tools for This Project</h3><ul><li>NodeJS version ≥18 (easily downloadable via this link: <a href="https://nodejs.org/fr/download/prebuilt-installer">https://nodejs.org/fr/download/prebuilt-installer</a>)</li><li><strong>An IDE (Integrated Development Environment)</strong> like IntelliJ (shareware; you can use the student pack if you are a student) or Visual Studio Code. In my case, I will use Visual Studio Code (download it via this link: <a href="https://code.visualstudio.com/download">https://code.visualstudio.com/download</a>).</li><li>Install Angular CLI version 15</li></ul><h3>What is angular ?</h3><p>Angular is an open-source TypeScript framework developed and maintained by Google. It is primarily used for building dynamic and high-performance single-page applications (SPAs).</p><p>Angular offers a comprehensive set of tools and structures to manage business logic, render user interfaces, handle component communication, and manage data effectively. Its modular architecture allows developers to create scalable applications while ensuring maintainability and performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhR0WFC2uJDRp4ZBNfv6Tg.png" /></figure><h3><strong>Advantages of using Angular</strong></h3><ul><li>Application performance.</li><li>Use of the MVVM model (Model, View, View-Model).</li><li>Benefits from TypeScript advantages: rigor and flexibility.</li><li>Testability.</li><li>Rich documentation and a significant community.</li><li>Constant and regular improvements.</li></ul><h3><strong>Installing and Building our Angular Application</strong></h3><p>First, verify that Node.js is properly installed, then proceed to install your specified Angular version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*-nT29uH7q6rAO1mKQpwiuw.png" /></figure><p>Finally, verify that Angular is properly installed by entering this command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*IXju8N9xY0Z_y5gO3Z_Ujg.png" /></figure><h3><strong>Creating Our Angular Project</strong></h3><p>Now, let’s create our Angular project:</p><ol><li><strong>Create an Empty Folder</strong><br>Begin by creating an empty folder on your computer where you want to store your Angular project. You can name the folder whatever you like. In my case, I named it employee-management-frontend.</li><li><strong>Open the Folder in VS Code</strong>:<br>Once the folder is created, open it in Visual Studio Code.</li><li><strong>Run the Angular CLI Command</strong>:<br>Inside Visual Studio Code’s terminal, run the following command to generate a new Angular project:</li></ol><pre>ng new angular-app-name</pre><ul><li>In my case, i named my angular project employeemanagementfrontend</li></ul><pre>ng new employeemanagementfrontend</pre><ul><li>When prompted, select <strong>Yes</strong> for Angular routing.</li><li>Choose <strong>CSS</strong> as the stylesheet format and press <strong>Enter</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfDHnTuVT1m6QkAeqaEtug.png" /></figure><h3>Installing and Integrating Bootstrap 5 and Font Awesome with Angular</h3><p>Now after creating our project, we will install bootstrap by running this command in the terminal.</p><ul><li><strong>Install Bootstrap via npm</strong>: Open your terminal in the Angular project directory and run:</li></ul><pre>npm install bootstrap@5</pre><ul><li><strong>Install Font Awesome:</strong> Use npm to install the @fortawesome/fontawesome package, which provides a collection of icons to enhance the visual design of your application.</li></ul><pre>npm install @fortawesome/fontawesome-free</pre><ul><li>Open the angular.json file.</li><li>Locate the &quot;styles&quot; array under the build options, and add the following paths:</li></ul><pre>&quot;styles&quot;: [<br>           &quot;node_modules/bootstrap/dist/css/bootstrap.min.css&quot;,<br>           &quot;src/styles.css&quot;,<br>           &quot;node_modules/@fortawesome/fontawesome-free/css/all.css&quot;],</pre><p>This will integrate Bootstrap and Font Awesome styles into your project.</p><p><strong>Save and restart your development server</strong>: Now, Bootstrap and font Awesome<strong> </strong>should be integrated into your Angular application. You can verify it by adding Bootstrap classes to your components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtWFF9RUwVINR4xB6Vz0GQ.png" /></figure><p>Now<strong>, right-click on the </strong><strong>app folder</strong>, create a new folder named components. This folder will contain all our components.</p><ul><li><strong>Create the components</strong>: In the components folder, create four components for managing employees by running the following commands in the terminal:</li></ul><pre>ng g  c components/navbar<br>ng g  c components/createEmployee<br>ng g  c components/employeeList<br>ng g  c components/updateEmployee</pre><p>These commands will create the navbar,createEmployee, employeeList, and updateEmployee components inside the components folder.</p><ul><li><strong>navBar</strong>: This component will contain the source code for our navigation bar, providing easy navigation across the app.</li><li><strong>createEmployee</strong>: This component will contain a form to add a new employee to the system.</li><li><strong>employeeList</strong>: This component will display a table listing all employees, providing an overview of the existing employees in the system.</li><li><strong>updateEmployee</strong>: This component will feature a form pre-filled with an employee’s existing information, enabling users to update the details as needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0Ps9kBIm1QJqmUi3N6nuA.png" /></figure><p>Now, right-click and create the following two folders:</p><ol><li><strong>services</strong> — this folder will contain all our service files.</li><li><strong>models</strong> — this folder will hold all our data models.</li></ol><ul><li><strong>Services</strong>: In Angular, services facilitate communication with a Spring backend by sending HTTP requests, handling business logic, and processing data for the app’s components.</li><li><strong>Models</strong>: Define structured data types, ensuring consistency and type safety for data throughout the app.</li></ul><h3><strong>Adding Routing</strong></h3><p>Now, we’ll set up routing in the AppRoutingModule file to enable navigation between components.</p><p>To add routing to navigate between components in the AppRoutingModule, follow these steps:</p><ol><li>Open the<strong> </strong><strong>app-routing.module.ts </strong>file in your Angular project.</li><li>Import the components you want to add routes for:</li></ol><pre>import { CreateEmployeeComponent } from &#39;./components/create-employee/create-employee.component&#39;;<br>import { EmployeeListComponent } from &#39;./components/employee-list/employee-list.component&#39;;<br>import { UpdateEmployeeComponent } from &#39;./components/update-employee/update-employee.component&#39;;</pre><ul><li><strong>Define the routes</strong> for each component in the Routes array:</li></ul><pre>const routes: Routes = [ <br>  { path: &#39;employees&#39;, component: EmployeeListComponent },<br>  { path: &#39;add-employee&#39;, component: CreateEmployeeComponent }, <br>  { path: &#39;update-employee/:id&#39;, component: UpdateEmployeeComponent },<br>  { path: &#39;&#39;, redirectTo: &#39;/employees&#39;, pathMatch: &#39;full&#39; },<br> ];</pre><ul><li>employees: Displays the employee list.</li><li>add-employee: Opens the form to add a new employee.</li><li>update-employee/:id: Opens the form to update an existing employee&#39;s information (using an employee id as a parameter).</li><li>Default route (&#39;&#39;): Redirects to the employee list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2s8BmfGxco5DSu3sA6zvw.png" /></figure><h3><strong>Build the Navigation Bar (navBar)</strong></h3><ul><li>Now, in the HTML file of the navBar component, add the following code:</li></ul><pre>&lt;nav class=&quot;navbar navbar-expand-lg bg-body-tertiary&quot;&gt;<br>    &lt;div class=&quot;container-fluid&quot;&gt;<br>      &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Employee&lt;/a&gt;<br>      &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-bs-toggle=&quot;collapse&quot; data-bs-target=&quot;#navbarScroll&quot; aria-controls=&quot;navbarScroll&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;<br>        &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>      &lt;/button&gt;<br>      &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarScroll&quot;&gt;<br>        &lt;ul class=&quot;navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll&quot; style=&quot;--bs-scroll-height: 100px;&quot;&gt;<br>          &lt;li class=&quot;nav-item&quot;&gt;<br>            &lt;a routerLink=&quot;employees&quot;  class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Employee List&lt;/a&gt;<br>          &lt;/li&gt;<br>          &lt;li class=&quot;nav-item&quot;&gt;<br>            &lt;a routerLink=&quot;add-employee&quot; class=&quot;nav-link active&quot; aria-current=&quot;page&quot; href=&quot;#&quot;&gt;Add Employee&lt;/a&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;form class=&quot;d-flex&quot; role=&quot;search&quot;&gt;<br>          &lt;button class=&quot;btn btn-outline-danger&quot; &gt;logout&lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/nav&gt;</pre><ul><li>Here is a screenshot of my project up to this point.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2bmfPNKV3XNedZfcpzOSw.png" /></figure><p>If you need to make any changes, simply go to the Bootstrap navbar component — it’s easy to customize.(<a href="https://getbootstrap.com/docs/5.3/components/navbar/#nav">https://getbootstrap.com/docs/5.3/components/navbar/#nav</a>)</p><p>Now, open the app.component.html file, remove the existing code, and add the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmdz5-v0k6XWSEvQO8uYRw.png" /></figure><p>In Angular, the <strong>router-outlet</strong> serves as a container to dynamically display components based on the active route. It is used for navigation between different views of the application.</p><p>Now, to run the project, type the following command:</p><pre>ng serve --open </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W57Cw8WJlBPCLd4oE7lLiA.png" /></figure><h3>Creating an Employee in the system</h3><p>The first step is to create a form that allows us to add a new employee to the database, complete with validation checks.</p><p><strong>Define the Employee Model</strong></p><p>Right-click on the <strong>models</strong> folder and create a new file named Employee.ts.<br>This file will define the data structure for an employee, ensuring consistent typing and seamless interaction with employee data throughout the application.</p><pre>// employee.model.ts<br>export class Employee {<br>    id:number<br>    firstname:string <br>    lastname:string <br>    email:string<br>    birthDate: Date<br>    phoneNumber: string<br>    address: string<br>    salary: number<br>  }</pre><p>Now, open <strong>app.module.ts</strong> and add the following two lines to the imports section:</p><pre>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { HttpClientModule } from &#39;@angular/common/http&#39;;</pre><pre>imports: [<br> FormsModule,<br> HttpClientModule,<br>]</pre><ul><li><strong>FormsModule</strong>: Provides support for template-driven forms in Angular, enabling two-way data binding and basic form control functionalities.</li><li><strong>HttpClientModule</strong>: Allows the application to communicate with backend services (SpringBoot) over HTTP, providing methods to perform HTTP requests (GET, POST, PUT, DELETE) and handle responses.</li></ul><p>Here is a screenshot of my app.module.ts file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpIMYOmKDqE_nWHtyHTcXQ.png" /></figure><p>Now, in the terminal, run the following command to generate a service that will handle communication with the Spring Boot backend.</p><p>This command will create a service named employee.service.ts, which you can use to send HTTP requests to the Spring Boot backend.</p><pre>ng g s services/employee</pre><p>In the <strong>employee.service.ts</strong> file, add the following code:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { Employee } from &#39;../models/employee&#39;; // Make sure to import your Employee model<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class EmployeeService {<br>  <br>  // URL of the API to add an employee<br>  private apiUrl = &#39;http://localhost:8081/api/employee&#39;; <br><br>  constructor(private http: HttpClient) {}<br><br>  // Method to add a new employee<br>  addEmployee(employee: Employee): Observable&lt;Object&gt; {<br>    return this.http.post(`${this.apiUrl}/addEmployee`, employee);<br>  }<br>}</pre><p>This code defines the <strong>EmployeeService</strong> with a method to send a POST request to the Spring Boot backend for adding a new employee.</p><p>Here is a screenshot of my EmployeeService file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeJdDHb5UDaBmw_MK8tVHQ.png" /></figure><p>Here’s how you can define the form in the <strong>CreateEmployeeComponent</strong> HTML file, including validations for capturing employee details:</p><pre>&lt;div class=&quot;container mt-5&quot;&gt;<br>    &lt;div class=&quot;row d-flex justify-content-center&quot;&gt;<br>      &lt;div class=&quot;col-7 &quot;&gt;<br>        &lt;div class=&quot;border border-1 p-5 m-5&quot;&gt;<br>          &lt;h1 class=&quot;text-center mb-5&quot;&gt;Register a New Employee&lt;/h1&gt;<br>          &lt;form (ngSubmit)=&quot;onSubmit()&quot; #employeeForm=&quot;ngForm&quot;&gt;<br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;firstname&quot; class=&quot;form-label&quot;&gt;Firstname&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;firstname&quot;<br>                name=&quot;firstname&quot;<br>                [(ngModel)]=&quot;employee.firstname&quot;<br>                required<br>                minlength=&quot;2&quot;<br>                #firstname=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;firstname.invalid &amp;&amp; firstname.touched &quot;&gt;<br>                &lt;div *ngIf=&quot;firstname.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Firstname is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;firstname.errors?.[&#39;minlength&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Minimum length is 2 characters.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;lastname&quot; class=&quot;form-label&quot;&gt;Lastname&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;lastname&quot;<br>                name=&quot;lastname&quot;<br>                [(ngModel)]=&quot;employee.lastname&quot;<br>                required<br>                minlength=&quot;2&quot;<br>                #lastname=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;lastname.invalid &amp;&amp; lastname.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;lastname.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Lastname is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;lastname.errors?.[&#39;minlength&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Minimum length is 2 characters.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email&lt;/label&gt;<br>              &lt;input<br>                type=&quot;email&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;email&quot;<br>                name=&quot;email&quot;<br>                [(ngModel)]=&quot;employee.email&quot;<br>                required<br>                email<br>                #email=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;email.invalid &amp;&amp; email.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;email.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Email is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;email.errors?.[&#39;email&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Please enter a valid email.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;birthDate&quot; class=&quot;form-label&quot;&gt;Birth Date&lt;/label&gt;<br>              &lt;input<br>                type=&quot;date&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;birthDate&quot;<br>                name=&quot;birthDate&quot;<br>                [(ngModel)]=&quot;employee.birthDate&quot;<br>                required<br>                #birthDate=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;birthDate.invalid &amp;&amp; birthDate.touched&quot;&gt;<br>                &lt;div class=&quot;alert alert-danger mt-1&quot;&gt;Birth date is required.&lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;phoneNumber &quot; class=&quot;form-label&quot;&gt;Phone Number&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;phoneNumber&quot;<br>                name=&quot;phoneNumber&quot;<br>                [(ngModel)]=&quot;employee.phoneNumber&quot;<br>                required<br>                pattern=&quot;^[0-9]{8}$&quot;<br>                #phoneNumber=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;phoneNumber.invalid &amp;&amp; phoneNumber.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;phoneNumber.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot; &gt;<br>                  Phone number is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;phoneNumber.errors?.[&#39;pattern&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Please enter a valid phone number (8 digits).<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;address&quot; class=&quot;form-label&quot;&gt;Address&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;address&quot;<br>                name=&quot;address&quot;<br>                [(ngModel)]=&quot;employee.address&quot;<br>                required<br>                #address=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;address.invalid &amp;&amp; address.touched&quot;&gt;<br>                &lt;div class=&quot;alert alert-danger mt-1&quot;&gt;Address is required.&lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;salary&quot; class=&quot;form-label&quot;&gt;Salary&lt;/label&gt;<br>              &lt;input<br>                type=&quot;number&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;salary&quot;<br>                name=&quot;salary&quot;<br>                [(ngModel)]=&quot;employee.salary&quot;<br>                required<br>                min=&quot;0&quot;<br>                #salary=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;salary.invalid &amp;&amp; salary.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;salary.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Salary is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;salary.errors?.[&#39;min&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Salary must be a positive number.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary justify-content-center d-flex w-100&quot; [disabled]=&quot;employeeForm.invalid&quot;&gt;<br>              Submit<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><h3>Explanation:</h3><ol><li><strong>Form Setup</strong>: The form is wrapped with #employeeForm=&quot;ngForm&quot; to reference it for validation.</li><li><strong>Employee Fields</strong>:</li></ol><ul><li><strong>First Name</strong> and <strong>Last Name</strong> fields are required and have a minimum length of 2 characters.</li><li><strong>Email</strong> field is required and must be a valid email format.</li></ul><p><strong>3. Validation Messages</strong>: Error messages display only when the respective field is invalid and has been touched by the user.</p><p><strong>4. Submit Button</strong>: Disabled if the form is invalid.</p><p>This form captures employee details with basic validation and is ready to interact with the EmployeeService to submit data to the backend.</p><p>Now to the create-employee.component.ts, and add the following code</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { NgForm } from &#39;@angular/forms&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { Employee } from &#39;src/app/models/Employee&#39;;<br>import { EmployeeService } from &#39;src/app/services/employee.service&#39;;<br><br>@Component({<br>  selector: &#39;app-create-employee&#39;,<br>  templateUrl: &#39;./create-employee.component.html&#39;,<br>  styleUrls: [&#39;./create-employee.component.css&#39;]<br>})<br>export class CreateEmployeeComponent {<br>  employee: Employee = new Employee();<br><br>  constructor(private employeeService: EmployeeService, private router:Router) {}<br><br>  // Method that is called when the form is submitted<br>  onSubmit(){<br>    this.employeeService.addEmployee(this.employee).subscribe(data=&gt;{<br>     console.log(&#39;data&#39;,this.employee);<br>     this.router.navigate([&#39;/employees&#39;])<br>   },<br>     error=&gt;console.log(&#39;erreur&#39;)<br>     )<br> }<br>  // Method to check if the form is valid (can be used to disable the submit button)<br>  employeeFormValid(): boolean {<br>    return !!(<br>      this.employee.firstname &amp;&amp;<br>      this.employee.lastname &amp;&amp;<br>      this.employee.email &amp;&amp;<br>      this.employee.birthDate &amp;&amp;<br>      this.employee.phoneNumber &amp;&amp;<br>      this.employee.address &amp;&amp;<br>      this.employee.salary<br>    );<br>  }<br><br><br>}</pre><h3>Explanation:</h3><ol><li><strong>onSubmit()</strong>:</li></ol><ul><li>This method is triggered when the form is submitted.</li><li>It calls addEmployee() from EmployeeService to send the employee data to the backend.</li><li>Upon successful submission, it logs the employee data and navigates to the /employees route (list of employees).</li><li>If there’s an error, it logs the error message.</li></ul><ol><li><strong>employeeFormValid()</strong>:</li></ol><ul><li>This method checks if the employee object has all required fields filled.</li><li>It returns true if all fields are valid, which can be used to enable/disable the submit button.</li></ul><p>This completes the logic for handling form submission and validation for adding an employee.</p><p>Now, test it in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvU6CeNP_o2Mrhi-Ulc4xw.png" /></figure><p>After successfully adding the employee, you will be redirected to the employee list page.</p><h4>CORS Error Message</h4><p>If you submit the form and see this message in the logs,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*4ubWwULiA9FX8CD2cifSPg.png" /></figure><p>go to your Spring Boot project and add this annotation above the controller</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9-9WiLhrf9EbV69QS6IYA.png" /></figure><h3><strong>Display the complete list of employees</strong></h3><p>Now, we will retrieve all existing employees from the database. First, go to our service and add the following method to fetch all employees from the database.</p><pre>getAllEmployee():Observable&lt;Employee[]&gt;{<br>return this.http.get&lt;Employee[]&gt;(`${this.apiUrl}/getAllEmployee`)<br>}</pre><p>Now, go to EmployeeListComponent.ts and add the following code to retrieve all employees from the database and display them in the component:</p><pre>import { Component } from &#39;@angular/core&#39;; <br>import { Router } from &#39;@angular/router&#39;;<br>import { Employee } from &#39;src/app/models/Employee&#39;;<br>import { EmployeeService } from &#39;src/app/services/employee.service&#39;;<br><br>@Component({<br>  selector: &#39;app-employee-list&#39;,<br>  templateUrl: &#39;./employee-list.component.html&#39;,<br>  styleUrls: [&#39;./employee-list.component.css&#39;]<br>})<br>export class EmployeeListComponent {<br>  employees: Employee[] ;  // Define an array to hold employees<br><br>  constructor(private employeeService: EmployeeService, private router: Router) { }<br><br>  ngOnInit(): void {<br>    this.getAllEmployees();<br>  }<br><br>  getAllEmployees(): void {<br>    this.employeeService.getAllEmployee().subscribe(data =&gt; {<br>      this.employees = data;  // Assign the fetched data to the employees array<br>      console.log(data);  // Optionally log the data to check the response<br>    });<br>  }<br>}</pre><p>This code sets up the EmployeeListComponent to retrieve a list of employees when the component is initialized (ngOnInit) and displays them using the getAllEmployee() method from the EmployeeService.</p><p>Now, open the HTML template file and insert the following code:</p><pre>&lt;div class=&quot;container mt-5&quot;&gt;<br>    <br>      &lt;table  class=&quot;table table-striped table-hover&quot;&gt;<br>        &lt;caption class=&quot;fw-bold&quot;&gt;Employee List&lt;/caption&gt;<br>        &lt;thead&gt;<br>          &lt;tr&gt;<br>            &lt;th scope=&quot;col&quot;&gt;First Name&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Last Name&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Email&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Birth Date&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Phone Number&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Address&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Salary&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot;&gt;Actions&lt;/th&gt;<br><br>          &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          &lt;tr *ngFor=&quot;let emp of employee&quot;&gt;<br>            &lt;td&gt;{{ emp.firstname }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.lastname }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.email }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.birthDate | date }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.phoneNumber }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.address }}&lt;/td&gt;<br>            &lt;td&gt;{{ emp.salary | currency }}&lt;/td&gt;<br>            &lt;td&gt;<br>                &lt;button type=&quot;button&quot; class=&quot;btn btn-danger ms-1&quot;&gt;&lt;i class=&quot;fas fa-pen&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>               <br>                &lt;button type=&quot;button&quot; class=&quot;btn btn-danger ms-1&quot;&gt;&lt;i class=&quot;fas fa-trash&quot;&gt;&lt;/i&gt;&lt;/button&gt;<br>            &lt;/td&gt;<br>          &lt;/tr&gt;<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>  <br>   <br>  &lt;/div&gt;</pre><p>Here’s how to view the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwFvGi6PpFzmHttVQipEoQ.png" /></figure><h3>Updating an Employee</h3><p>In this section, we will implement the functionality to update a specific employee when the pen button is clicked.</p><p>First, navigate to our service and add the following two methods:</p><pre>  getEmployeeById(id:number):Observable&lt;Employee&gt;{<br>    return this.http.get&lt;Employee&gt;(`${this.apiUrl}/getEmployeeById/${id}`)<br>  }<br><br><br>   updateUser(id:number,employee:Employee):Observable&lt;Object&gt;{<br>     return this.http.put(`${this.apiUrl}/updateEmployee/${id}`,employee);<br>  }</pre><p>Now, open the EmployeeListComponent.ts file and add the following method:</p><pre>updateEmployee(id:number){<br>    this.router.navigate([&#39;/update-employee&#39;,id])<br>  }</pre><p>In the HTML file, update the pen button by adding the following code:<br>(click)=&quot;updateEmployee(emp.id)&quot;<br>This will pass the specific employee&#39;s ID to the updateEmployee method.</p><pre>&lt;button <br>type=&quot;button&quot;<br>class=&quot;btn btn-danger ms-1&quot;<br>(click)=&quot;updateEmployee(emp.id)&quot;&gt;&lt;i class=&quot;fas fa-pen&quot;&gt;&lt;/i&gt;&lt;/button&gt;</pre><p>Now, go to the UpdateEmployeeComponent.ts and insert the following code:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { ActivatedRoute, Router } from &#39;@angular/router&#39;;<br>import { Employee } from &#39;src/app/models/Employee&#39;;<br>import { EmployeeService } from &#39;src/app/services/employee.service&#39;;<br><br>@Component({<br>  selector: &#39;app-update-employee&#39;,<br>  templateUrl: &#39;./update-employee.component.html&#39;,<br>  styleUrls: [&#39;./update-employee.component.css&#39;]<br>})<br>export class UpdateEmployeeComponent {<br>  id: number;  // Variable to store the ID of the employee to be updated<br>  employee: Employee = new Employee();<br><br>  // Inject dependencies: EmployeeService for API calls, ActivatedRoute to get route parameters, Router for navigation<br>  constructor(<br>      private employeeService: EmployeeService, <br>      private activatedRoute: ActivatedRoute, <br>      private router: Router<br>  ) { }<br><br>  ngOnInit(): void {<br>      // On component initialization, get the employee ID from the route<br>      this.id = this.activatedRoute.snapshot.params[&#39;id&#39;];  // Capture the employee ID from the URL<br>      this.getEmployeeById();  // Call method to fetch the employee details by ID<br>  }<br><br>  // Method to fetch employee data by ID<br>  getEmployeeById(): void {<br>      this.employeeService.getEmployeeById(this.id).subscribe(data =&gt; {<br>          this.employee = data;  // Populate the employee object with data fetched from the API<br>          console.log(this.employee);  // Log the employee data for debugging purposes<br>      }, error =&gt; console.log(&quot;Error fetching employee details&quot;));  // Handle errors while fetching the data<br>  }<br><br>  // Method to handle the form submission<br>  onSubmit(): void {<br>      // Call the service method to update the employee data in the database<br>      this.employeeService.updateEmployee(this.id, this.employee).subscribe(<br>          data =&gt; {<br>              console.log(data);  // Log the response from the update operation<br>              this.employee = new Employee();  // Reset the employee object after successful update<br>              this.router.navigate([&#39;/employees&#39;]);  // Navigate back to the employee list page<br>          },<br>          error =&gt; console.log(error)  // Log errors if the update operation fails<br>      );<br>  }<br><br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6VsIbOIv6BGqnqs0wnqmA.png" /></figure><p>Now, add the following source code to the HTML file for the update employee form.</p><pre>&lt;div class=&quot;container mt-5&quot;&gt;<br>    &lt;div class=&quot;row d-flex justify-content-center&quot;&gt;<br>      &lt;div class=&quot;col-7 &quot;&gt;<br>        &lt;div class=&quot;border border-1 p-5 m-5&quot;&gt;<br>          &lt;h1 class=&quot;text-center mb-5&quot;&gt;Update an Employee&lt;/h1&gt;<br>          &lt;form  (ngSubmit)=&quot;onSubmit()&quot; #employeeForm=&quot;ngForm&quot;&gt;<br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;firstname&quot; class=&quot;form-label&quot;&gt;Firstname&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;firstname&quot;<br>                name=&quot;firstname&quot;<br>                [(ngModel)]=&quot;employee.firstname&quot;<br>                required<br>                minlength=&quot;2&quot;<br>                #firstname=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;firstname.invalid &amp;&amp; firstname.touched &quot;&gt;<br>                &lt;div *ngIf=&quot;firstname.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Firstname is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;firstname.errors?.[&#39;minlength&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Minimum length is 2 characters.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;lastname&quot; class=&quot;form-label&quot;&gt;Lastname&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;lastname&quot;<br>                name=&quot;lastname&quot;<br>                [(ngModel)]=&quot;employee.lastname&quot;<br>                required<br>                minlength=&quot;2&quot;<br>                #lastname=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;lastname.invalid &amp;&amp; lastname.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;lastname.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Lastname is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;lastname.errors?.[&#39;minlength&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Minimum length is 2 characters.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email&lt;/label&gt;<br>              &lt;input<br>                type=&quot;email&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;email&quot;<br>                name=&quot;email&quot;<br>                [(ngModel)]=&quot;employee.email&quot;<br>                required<br>                email<br>                #email=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;email.invalid &amp;&amp; email.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;email.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Email is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;email.errors?.[&#39;email&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Please enter a valid email.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;birthDate&quot; class=&quot;form-label&quot;&gt;Birth Date&lt;/label&gt;<br>              &lt;input<br>                type=&quot;date&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;birthDate&quot;<br>                name=&quot;birthDate&quot;<br>                [(ngModel)]=&quot;employee.birthDate&quot;<br>                required<br>                #birthDate=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;birthDate.invalid &amp;&amp; birthDate.touched&quot;&gt;<br>                &lt;div class=&quot;alert alert-danger mt-1&quot;&gt;Birth date is required.&lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;phoneNumber &quot; class=&quot;form-label&quot;&gt;Phone Number&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;phoneNumber&quot;<br>                name=&quot;phoneNumber&quot;<br>                [(ngModel)]=&quot;employee.phoneNumber&quot;<br>                required<br>                pattern=&quot;^[0-9]{8}$&quot;<br>                #phoneNumber=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;phoneNumber.invalid &amp;&amp; phoneNumber.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;phoneNumber.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot; &gt;<br>                  Phone number is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;phoneNumber.errors?.[&#39;pattern&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Please enter a valid phone number (8 digits).<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;address&quot; class=&quot;form-label&quot;&gt;Address&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;address&quot;<br>                name=&quot;address&quot;<br>                [(ngModel)]=&quot;employee.address&quot;<br>                required<br>                #address=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;address.invalid &amp;&amp; address.touched&quot;&gt;<br>                &lt;div class=&quot;alert alert-danger mt-1&quot;&gt;Address is required.&lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;div class=&quot;mb-3&quot;&gt;<br>              &lt;label for=&quot;salary&quot; class=&quot;form-label&quot;&gt;Salary&lt;/label&gt;<br>              &lt;input<br>                type=&quot;number&quot;<br>                class=&quot;form-control&quot;<br>                id=&quot;salary&quot;<br>                name=&quot;salary&quot;<br>                [(ngModel)]=&quot;employee.salary&quot;<br>                required<br>                min=&quot;0&quot;<br>                #salary=&quot;ngModel&quot;<br>              /&gt;<br>              &lt;div *ngIf=&quot;salary.invalid &amp;&amp; salary.touched&quot;&gt;<br>                &lt;div *ngIf=&quot;salary.errors?.[&#39;required&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Salary is required.<br>                &lt;/div&gt;<br>                &lt;div *ngIf=&quot;salary.errors?.[&#39;min&#39;]&quot; class=&quot;alert alert-danger mt-1&quot;&gt;<br>                  Salary must be a positive number.<br>                &lt;/div&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>  <br>            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary justify-content-center d-flex w-100&quot; [disabled]=&quot;employeeForm.invalid&quot;&gt;<br>              Update<br>            &lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;</pre><h3>Delete an Employee</h3><p>In this section, we will implement the functionality to delete an employee. Here’s how you can do it step by step:</p><p>First, go to our service and add the following method to delete an employee from the database.</p><pre>  deleteEmployee(id:number):Observable&lt;Object&gt;{<br>    return this.http.delete(`${this.apiUrl}/deleteEmployee/${id}`);<br><br>  }</pre><p>Now, go to the EmployeeListComponent.ts file and add the following code:</p><pre>deleteEmployee(id:number){<br>    this.employeeService.deleteEmployee(id).subscribe(data=&gt;{<br>      console.log(data)<br>     <br>       window.location.reload();<br><br>    })<br>}</pre><p>Here is an overview of all the code in the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bA_5XPIUDLmIwYXGAAboYA.png" /></figure><p>Finally, go to the HTML file and add this code to the trash button, like this:</p><pre>&lt;button<br>  type=&quot;button&quot;<br>  class=&quot;btn btn-danger ms-1&quot;<br>  (click)=&quot;deleteEmployee(emp.id)&quot;&gt;&lt;i class=&quot;fas fa-trash&quot;&gt;&lt;/i&gt;&lt;/button&gt;</pre><p>Here is an overview of all the code in the HTML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnxYcJ2fyHN_TAE99cup2w.png" /></figure><h3>Conclusion</h3><p>We have now completed our Angular CRUD application. Throughout the process, we integrated Bootstrap for styling, FontAwesome for icons, created essential components, implemented form validations, and established communication between the frontend and the backend.</p><p>Here is the GitHub link for the project: <a href="https://github.com/sidaouiMohamedamine/employeemanagementfrontend"><strong>https://github.com/sidaouiMohamedamine/employeemanagementfrontend</strong></a></p><p>If you have any questions, feel free to contact me through my LinkedIn profile.<a href="https://www.linkedin.com/in/sidaouimohamedamine/"><strong>https://www.linkedin.com/in/sidaouimohamedamine/</strong></a></p><p><a href="http://www.sidaouimohamedamine.com/"><strong>http://www.sidaouimohamedamine.com/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e50393c24ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a CRUD GraphQL API with Spring Boot]]></title>
            <link>https://msidaoui.medium.com/building-a-crud-graphql-api-with-spring-boot-30c00f784cff?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c00f784cff</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 08:05:30 GMT</pubDate>
            <atom:updated>2024-12-01T08:57:20.271Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll provide a step-by-step guide to understanding GraphQL and how it compares to REST APIs. We’ll also build a CRUD API using Spring Boot to demonstrate GraphQL in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*3YDQzLW02qU67UxcHvNHIg.png" /></figure><h3>Purpose of This Article</h3><p>In this article, we’ll explore:</p><ul><li>What GraphQL is and its key advantages.</li><li>Why you might choose GraphQL over a REST API.</li><li>A comparison between GraphQL and REST APIs.</li><li>How to implement CRUD operations with GraphQL using Spring Boot.</li></ul><h3>Tools for This Project</h3><ul><li><strong>JDK </strong>(Java Development Kit)<strong>≥17</strong></li><li><strong>An IDE (Integrated Development Environment)</strong> like <strong>IntelliJ</strong> (shareware; you can use the student pack if you are a student), <strong>STS</strong> (Spring Tool Suite), or Eclipse.</li><li><strong>MySQL </strong>as the DBMS (Database Management System).</li><li><strong>Postman </strong>will be used for testing the API we will create.</li></ul><h3><strong>What is graphQL</strong></h3><p>GraphQL,<strong> </strong>short for<strong> Graph Query Language</strong>, is a versatile query language and runtime for building APIs. Initially developed by Facebook in 2012 and open-sourced in 2015, GraphQL offers a modern approach to API design.</p><h4><strong>Here’s what makes GraphQL unique:</strong></h4><ul><li>It operates through a single HTTP endpoint, streamlining communication.</li><li>It enhances both performance and flexibility by allowing clients to specify precisely the data they need.</li><li>The API’s response structure is <strong>defined by a schema</strong>, which outlines a network ( graph) of data types.</li></ul><h3><strong>Why Choose GraphQL Over REST API</strong></h3><p>GraphQL offers an efficient solution to many challenges commonly encountered with REST:</p><ul><li><strong>Addressing Over-fetching</strong>: With REST, you may retrieve more data than necessary. GraphQL allows the client to request exactly the data it needs, reducing unnecessary data transfer.</li><li><strong>Solving Under-fetching</strong>: In REST, multiple requests are often required to gather all necessary information (multiple URIs). GraphQL allows fetching all the data in a single query, simplifying network calls.</li><li><strong>Data Selectivity</strong>: Unlike REST, where data is predefined by endpoints, GraphQL enables the client to precisely specify which data to receive, providing more control and efficiency.</li></ul><h3><strong>Comparing GraphQL and REST APIs</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqFJCgKdRW0qUNmjXTolRg.png" /></figure><h4><strong>GraphQL Methods</strong></h4><ul><li><strong>query</strong>: Used to retrieve data (equivalent to GET in REST).</li><li><strong>mutation</strong>: Used to perform data modification operations (equivalent to POST, PUT, or DELETE in REST).</li><li><strong>subscription</strong>: Allows subscribing to events and receiving real-time updates (no direct equivalent in REST).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*PzXbM0XMbTyFxIyrOC942w.jpeg" /></figure><h3><strong>Implementing GraphQL CRUD with Spring Boot</strong></h3><p>Now, let’s start by creating our Spring Boot GraphQL project. Go to <a href="https://start.spring.io/">Spring Initializr</a>, configure the project settings, and add the required dependencies, including <strong>Spring Web</strong> and <strong>GraphQL</strong>. Once everything is set up, generate the project files and download them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCYDk2BOsLZoqAje1NCDMA.png" /></figure><p>Next, open the application.properties file and add the following database configuration along with the GraphQL schema path:</p><pre>spring.application.name=springboot-graphql<br><br># MySQL database configuration<br>spring.datasource.url=jdbc:mysql://localhost:3306/databasename<br>spring.datasource.username= [username]<br>spring.datasource.password= [password]<br>spring.jpa.hibernate.ddl-auto=update<br><br># GraphQL schema path configuration<br>spring.graphql.graphql-location=classpath:graphql/</pre><p>Now, right-click and create a class named Employee. Then, create an interface called EmployeeRepository (make sure it extends JpaRepository). In the Employee class, add the following code:</p><pre>package com.sid.springboot_graphql;<br><br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import lombok.AllArgsConstructor;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>import java.util.Date;<br><br>@Entity<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Data<br>public class Employee {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String firstname;<br>    private String lastname;<br>    private String email;<br>    private String phoneNumber;<br>    private Double salary;<br>}</pre><p>In the EmployeeRepository interface:</p><pre>package com.sid.springboot_graphql;<br><br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br><br>@Repository<br>public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt; {<br>}</pre><p>Next, right-click and create a new service class named EmployeeService.</p><p>In the EmployeeServiceclass, add the following code:</p><pre>package com.sid.springboot_graphql;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br>import java.util.Optional;<br><br>@Service<br>public class EmployeeService {<br><br>    private final EmployeeRepository employeeRepository;<br><br>    @Autowired<br>    public EmployeeService(EmployeeRepository employeeRepository) {<br>        this.employeeRepository = employeeRepository;<br>    }<br><br>    public List&lt;Employee&gt; getAllEmployees() {<br>        return employeeRepository.findAll();<br>    }<br><br>    public Optional&lt;Employee&gt; getEmployeeById(Long id) {<br>        return employeeRepository.findById(id);<br>    }<br><br>    public Employee createEmployee(Employee employee) {<br>        return employeeRepository.save(employee);<br>    }<br><br>    public Employee updateEmployee(Long id, Employee employee) {<br>        if (employeeRepository.existsById(id)) {<br>            employee.setId(id);<br>            return employeeRepository.save(employee);<br>        }<br>        return null;<br>    }<br><br>    public boolean deleteEmployee(Long id) {<br>        if (employeeRepository.existsById(id)) {<br>            employeeRepository.deleteById(id);<br>            return true;<br>        }<br>        return false;<br>    }}</pre><p>Now, let’s create the resolver.</p><p><strong>A GraphQL resolver functions</strong> similarly to a controller in a traditional application. It handles queries, interacts with services to retrieve or manipulate data, and returns the results to the client. Essentially, a resolver manages the business logic for each field in the GraphQL schema.</p><p>In the EmployeeResolverclass, add the following code:</p><pre>package com.sid.springboot_graphql;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.graphql.data.method.annotation.Argument;<br>import org.springframework.graphql.data.method.annotation.MutationMapping;<br>import org.springframework.graphql.data.method.annotation.QueryMapping;<br>import org.springframework.stereotype.Component;<br>import org.springframework.stereotype.Controller;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.List;<br>import java.util.Optional;<br><br>@RestController<br>public class EmployeeResolver {<br>   <br>    @Autowired<br>    private  EmployeeService employeeService;<br><br><br>    // Query mapping for fetching all employees from the service<br>    @QueryMapping<br>    public List&lt;Employee&gt; getAllEmployees() {<br>        return employeeService.getAllEmployees();<br>    }<br><br>    // Query mapping for fetching a specific employee by ID<br>    @QueryMapping<br>    public Optional&lt;Employee&gt; getEmployee(@Argument Long id) {<br>        return employeeService.getEmployeeById(id);<br>    }<br><br>    // Mutation mapping for creating a new employee<br>    @MutationMapping<br>    public Employee createEmployee(@Argument Employee employee) {<br>        return employeeService.createEmployee(employee);<br>    }<br><br>    // Mutation mapping for updating an existing employee<br>    @MutationMapping<br>    public Employee updateEmployee(@Argument Long id, @Argument Employee employee) {<br>        return employeeService.updateEmployee(id, employee);<br>    }<br><br>    // Mutation mapping for deleting an employee by ID<br>    @MutationMapping<br>    public boolean deleteEmployee(@Argument Long id) {<br>        return employeeService.deleteEmployee(id);<br>    }<br>}</pre><p>Next, let’s create our schema. In GraphQL, the schema defines the API’s structure, specifying data types, queries, and mutations available to clients.</p><p>Right-click on the graphql folder and create a new file named schema.graphqls. And add the following code:</p><pre>type Employee {<br>    id: ID!<br>    firstname: String!<br>    lastname: String!<br>    email: String!<br>    phoneNumber: String!<br>    salary: Float!<br>}<br><br>type Query {<br>    getAllEmployees: [Employee]<br>    getEmployee(id: ID!): Employee<br>}<br><br>type Mutation {<br>    createEmployee(employee: EmployeeInput): Employee<br>    updateEmployee(id: ID!, employee: EmployeeInput): Employee<br>    deleteEmployee(id: ID!): Boolean<br>}<br><br>input EmployeeInput {<br>    firstname: String!<br>    lastname: String!<br>    email: String!<br>    phoneNumber: String!<br>    salary: Float!<br>}</pre><h3>Test with postman</h3><ul><li><strong>Open Postman</strong> and create a new request.</li><li>Set the request type to <strong>POST</strong> and enter the endpoint URL for your GraphQL API (<a href="http://localhost:8080/graphql).">http://localhost:8080/graphql).</a></li><li>In the <strong>Body</strong> tab, select <strong>raw</strong> and set the format to <strong>JSON</strong>.</li></ul><h4>Create an employee</h4><pre>{<br>    &quot;query&quot;: &quot;mutation { createEmployee(employee: { firstname: \&quot;John\&quot;, lastname: \&quot;Doe\&quot;, email: \&quot;john.doe@example.com\&quot;, phoneNumber: \&quot;1234567890\&quot;, salary: 50000.0 }) { id firstname lastname email phoneNumber salary } }&quot;<br>}</pre><h4>Retreive all employees</h4><pre>{<br>  &quot;query&quot;: &quot;query { getAllEmployees { id firstname lastname email phoneNumber salary } }&quot;<br>}</pre><h4>Retreive an employee by id</h4><pre>{<br>  &quot;query&quot;: &quot;{ getEmployee(id: 1) { id firstname lastname email phoneNumber salary } }&quot;<br>}</pre><h4>Update an employee</h4><pre>{<br>  &quot;query&quot;: &quot;mutation { updateEmployee(id: \&quot;1\&quot;, employee: { firstname: \&quot;Jane\&quot;, lastname: \&quot;Doe\&quot;, email: \&quot;jane.doe@example.com\&quot;, phoneNumber: \&quot;0987654321\&quot;, salary: 60000.0 }) { id firstname lastname email phoneNumber salary } }&quot;<br>}</pre><h4>Delete an employee</h4><pre>{<br>  &quot;query&quot;: &quot;mutation { deleteEmployee(id: 3) }&quot;<br>}</pre><h3>Conclusion</h3><p>In this article, we introduced GraphQL and compared it with REST APIs. We explored the reasons and scenarios for choosing GraphQL over REST. Finally, we built a CRUD Spring Boot application with GraphQL to show how it works in practice.</p><p>Here’s the link to the entire project on GitHub (<a href="https://github.com/sidaouiMohamedamine/springboot-graphql-crud-project">https://github.com/sidaouiMohamedamine/springboot-graphql-crud-project</a>)</p><p>Please clone the repository, update the database configurations if necessary, and start the project to test all your APIs.</p><p>If you have any questions, feel free to contact me through my website, where you’ll find my contact details: <a href="http://www.sidaouimohamedamine.com/"><strong>http://www.sidaouimohamedamine.com/</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c00f784cff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Your First Spring Boot Application (CRUD)]]></title>
            <link>https://msidaoui.medium.com/getting-started-with-your-first-spring-boot-application-c5b3ad3156d2?source=rss-d0d27e298841------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5b3ad3156d2</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Sidaoui Mohamed Amine]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 17:13:39 GMT</pubDate>
            <atom:updated>2024-11-06T07:24:34.907Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will build our first Spring Boot application step by step. Each phase will include detailed explanations and screenshots for clarity. By the end, you’ll have a solid foundation in Spring Boot development and the confidence to create your own applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4KMZWxXuM-DHTojHwwtCtg.png" /></figure><h3><strong>Purpose of This Article</strong></h3><ul><li>Understand Spring Boot and Its Importance in Backend Application Development.</li><li>Set Up a Spring Boot Project with Necessary Dependencies.</li><li>Connect a Spring Boot Application to a PostgreSQL Database.</li><li>Create a REST API with CRUD Operations (Create, Read, Update, Delete).</li><li>Test API Endpoints Using Postman.</li></ul><h3>Technical Requirements</h3><ul><li><strong>Strong command of the Java language</strong>: Understanding of fundamental concepts, syntax, and features of the language.</li><li><strong>Knowledge of object-oriented programming (OOP) principles</strong>: Mastery of concepts such as classes, objects, inheritance, polymorphism, and encapsulation.</li><li><strong>Software design skills</strong>: Ability to apply design principles and patterns to structure and organize code effectively.</li></ul><h3><strong>Tools for This Project</strong></h3><ul><li><strong>JDK </strong>(Java Development Kit)<strong>≥17</strong></li><li><strong>An IDE (Integrated Development Environment)</strong> like <strong>IntelliJ</strong> (shareware; you can use the student pack if you are a student), <strong>STS</strong> (Spring Tool Suite), or Eclipse.</li><li><strong>PostgreSQL </strong>as the DBMS (Database Management System).</li><li><strong>Postman </strong>will be used for testing the API we will create.</li></ul><h3><strong>What Is Spring Boot?</strong></h3><p>Spring Boot is an open-source framework based on Java, designed to simplify application development by reducing the need for manual configuration. It builds on the Spring framework, providing a faster and easier way to create standalone, production-ready applications with minimal configuration. Spring Boot is particularly favored for microservices development.</p><h3><strong>Strengths of Spring Boot</strong></h3><ol><li><strong>Auto-Configuration</strong>: Spring Boot offers a default configuration that allows developers to quickly get started without having to manually configure each component.</li><li><strong>Standalone Applications</strong>: An embedded web server like Tomcat or Jetty is included in Spring Boot applications to allow them to run independently without the need for an external application server.</li><li><strong>Production-Ready</strong>: It has features that are ready for use in production, like tracking performance, managing logs, and other operational tools.</li><li><strong>Ease of Integration</strong>: Spring Boot easily integrates with other technologies and frameworks, making it simpler to develop complex solutions.</li><li><strong>Active Community</strong>: The support of a large community and comprehensive documentation makes learning and troubleshooting much easier.</li></ol><h3><strong>Initiate the Project</strong></h3><p>To start creating your Spring project, one of the methods is to visit Spring Initializr ( <a href="https://start.spring.io/">https://start.spring.io/</a> ) , where you can generate the necessary dependencies for your project. This tool allows you to customize your project settings, select the required dependencies, and download a ready-to-use project structure.</p><h4><strong>What is a dependancy</strong></h4><p>In Spring Boot, a <strong>dependency</strong> refers to an external library or module that your application needs in order to function properly. These dependencies can include various libraries for different functionalities, such as web development, data access, security, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8E4g6cDOnrjhpLTYqxnOAw.png" /></figure><p>To create a new Spring Boot project using the Spring Initializr, follow these steps for an efficient setup:</p><ol><li><strong>Select Dependency Manager</strong>: Choose <strong>Maven</strong> as the dependency management tool, as it simplifies dependency management and is widely used in enterprise applications.</li></ol><p><strong>2. Select Language and Spring Boot Version</strong>:</p><ul><li>Choose <strong>Java</strong> as the programming language.</li><li>For the Spring Boot version, select a stable release, such as <strong>3.3.5</strong>. This ensures compatibility and access to the latest Spring features.</li></ul><p><strong>3. Project Metadata</strong>:</p><ul><li><strong>Group ID</strong>: This should be a unique identifier, usually based on the domain name of your organization, reversed. For example, com.sidaoui .</li><li><strong>Artifact ID</strong>: Name your project; in this example, use employeeManagementSystem.</li><li><strong>Name</strong> and <strong>Description</strong>: The name is often the same as the artifact ID. For the description, provide a clear and concise purpose for the project.</li><li><strong>Package Name</strong>: This is often auto-filled based on your Group ID and Artifact ID but can be adjusted as needed.</li></ul><p><strong>4. Packaging and Java Version</strong>:</p><ul><li>Set <strong>Packaging</strong> to <strong>Jar</strong> (instead of War) since Jar files are more common for standalone Spring Boot applications.</li><li>Choose the Java version that matches your environment. In my case, I used Java 17.</li></ul><p><strong>5. Dependencies</strong>:</p><ul><li>Add dependencies based on your project’s requirements. For a typical web application, you might need:</li><li><strong>PostgreSQL Driver</strong>: For database connectivity if you’re using PostgreSQL.</li><li><strong>Spring Boot DevTools</strong>: Provides faster application restart and live reload, enhancing the development experience.</li><li><strong>Spring Web</strong>: Adds support for building web applications, including RESTful services.</li><li><strong>Spring Data JPA</strong>: Simplifies database interactions with Hibernate and JPA.</li><li><strong>Lombok</strong>: Reduces boilerplate code by generating getters, setters, and other methods automatically.</li><li><strong>Spring Data JDBC</strong>: Alternative for simple SQL-based persistence without full JPA complexity.</li></ul><p><strong>6. Generate the Project</strong>: After filling out all fields, click <strong>Generate</strong> to download your project as a ZIP file.</p><p>This setup ensures you have all necessary configurations to build a Spring Boot application efficiently, focusing on maintainability and modularity.</p><p>After unzipping your folder, double-click on the <strong>pom.xml</strong> file. This will open a window in your Integrated Development Environment (IDE), such as IntelliJ IDEA, STS or Eclipse. Next, right-click on the <strong>pom.xml</strong> file, select <strong>Maven</strong>, and then click on <strong>Reload Project</strong>. This action will force the IDE to reload all Maven dependencies and synchronize the project, ensuring that all libraries and configurations specified in the <strong>pom.xml</strong> are correctly applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzNM0RWG7ipqJgofsF6ESw.png" /></figure><h3>Connect the Application to PostgreSQL Database</h3><p>After creating our Spring Boot project, the first step is to configure the database in our PostgreSQL. To do this, we specify the database name along with the necessary credentials, such as the username and password.</p><p>In my case, I named the database employee, with the username as postgresql and the password as admin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EaFPlcRzC2DBwLWVu7HKA.png" /></figure><p>Now we will go to our file application.properties the configuration file in our Spring Boot project. This configuration enables the application to connect effectively to the database, making it easier to manage data operations, such as CRUD (Create, Read, Update, Delete) operations and data persistence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6Jo8g1zhaWgmvzKbona2Q.png" /></figure><p>Here’s an explanation of each line in your application.properties file for a Spring Boot application:</p><pre>spring.application.name=employeeManagementSystem</pre><ul><li><strong>spring.application.name</strong>: This sets the name of the Spring Boot application. In this case, the name is “employeeManagementSystem.”</li></ul><pre>server.port=8081</pre><ul><li><strong>server.port</strong>: This specifies the port on which the application server will listen for requests. Here, the server will be accessible on port 8081 instead of the default port 8080.</li></ul><pre>spring.datasource.url=jdbc:postgresql://localhost:5432/employee?createDatabaseIfNotExist=true</pre><ul><li><strong>spring.datasource.url</strong>: This defines the connection URL for the database. In this example, it connects to a PostgreSQL database on localhost at port 5432, with the database name employee. The option createDatabaseIfNotExist=true indicates that if the database does not exist, it will be created automatically.</li></ul><pre>spring.datasource.username=postgres</pre><ul><li><strong>spring.datasource.username</strong>: This specifies the username used to connect to the database. Here, the user is postgres, which is the default user for PostgreSQL.</li></ul><pre>spring.datasource.password=admin</pre><ul><li><strong>spring.datasource.password</strong>: This indicates the password associated with the username for connecting to the database. In this example, the password is admin.</li></ul><pre>spring.datasource.driver-class-name=org.postgresql.Driver</pre><ul><li><strong>spring.datasource.driver-class-name</strong>: This sets the name of the JDBC driver class to use for connecting to the database. In this case, org.postgresql.Driver is the driver for PostgreSQL.</li></ul><pre>spring.jpa.hibernate.ddl-auto=update</pre><ul><li><strong>spring.jpa.hibernate.ddl-auto</strong>: This configures the behavior of schema management by Hibernate. The update option means that Hibernate will automatically update the database schema to reflect changes made to the entities, without dropping existing data.</li></ul><pre>spring.jpa.show-sql=true</pre><ul><li><strong>spring.jpa.show-sql</strong>: When set to true, this option allows Hibernate to display the generated SQL queries in the console during execution. This can be useful for debugging and for seeing how database operations are performed.</li></ul><h3>Project Structure</h3><p>Before starting development, we will structure the project in a clear and organized way to facilitate code maintainability, readability, and scalability. Here is a basic structure for a Spring Boot project, with descriptions of the main folders and files.</p><p>First of all, we will create the necessary packages for the project. Right-click on the main package, select “New,” then click on “Package.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKGHDMATirFyum-WknUcpQ.png" /></figure><ul><li><strong>entity </strong>: Holds <strong>entity classes</strong> that represent data tables in the database. Each class (or model) defines the structure of data, with attributes that map to table columns.</li><li><strong>repository</strong>: Defines <strong>database access</strong> interfaces, usually extending JpaRepository. Repositories handle CRUD operations (Create, Read, Update, Delete) on data.</li><li><strong>service</strong>: Contains the <strong>business logic</strong> of the application. Services process data, working between controllers (user requests) and repositories (database operations).</li><li><strong>controller</strong>: This folder contains all REST controller classes that handle HTTP requests from clients ( GET, POST, PUT, DELETE). Each controller maps these requests to specific methods and manages the responses sent back to clients. Essentially, controllers are the entry points for the API endpoints of the application.</li></ul><h3>Presentation of our project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQ0ckcFK7fM3LBxl20krvA.png" /></figure><p>The figure above illustrates the class diagram of our system. In this article, we will focus only on the Employee class and the associated basic CRUD operations.</p><h3>Creating the Employee Entity</h3><p>In Spring Boot, an entity is a class that represents a table in a database. Each instance of this class corresponds to a row in the table. Entities are typically annotated with JPA (Java Persistence API) annotations, which allow Spring to manage data persistence.</p><p>To create our Employee class, follow these steps:</p><ol><li>Right-click on the <strong>Entity</strong> package.</li><li>Select <strong>New</strong> &gt; <strong>Class</strong>.</li><li>Name the class <strong>Employee</strong> and confirm by clicking <strong>Finish</strong>.</li></ol><p>This will create a new Employee class where we can start defining its properties and methods.</p><p>Now here is our class after creating the necessary attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAWM8_VsAczd9lDf3AeShg.png" /></figure><h4><strong>Annotations in Spring Boot</strong></h4><p>Annotations in Spring Boot play a crucial role in creating robust, maintainable, and easily configurable applications. They allow developers to focus more on business logic by significantly reducing repetitive code and configuration requirements. With these annotations, development becomes more intuitive and efficient, promoting enhanced productivity and simplified management of dependencies and component behaviors within the application.</p><p>In our Employee class, we will use several annotations specific to Spring Boot and Java Persistence API (JPA). Here is the role of each annotation in this class:</p><p><strong>@Entity</strong>:</p><p>Indicates that the Employee class is a JPA entity and will be mapped to a table in the database. This annotation is essential for Hibernate or JPA to manage this class as a persistent entity.</p><p><strong>@AllArgsConstructor</strong> (from Lombok):</p><p>Automatically generates a constructor with all the arguments for each attribute of the Employee class.</p><p><strong>@NoArgsConstructor</strong> (from Lombok):</p><p>Automatically generates a no-argument constructor for the Employee class, which is often required by JPA.</p><p><strong>@Data</strong> (from Lombok):</p><p>Automatically generates the getter, setter, toString, equals, and hashCode methods for all attributes of the Employee class.</p><p><strong>@Table(name = “employee_table”)</strong>:</p><p>Allows specifying the name of the table associated with this entity in the database. Here, it is associated with the table named employee_table.</p><p><strong>@Id</strong>:</p><p>Designates the id field as the primary key of the entity.</p><p><strong>@GeneratedValue(strategy = GenerationType.IDENTITY)</strong>:</p><p>Indicates that the value of the ID will be generated automatically by the database. The GenerationType.IDENTITY strategy means that the ID generation is managed by the database, often with an auto-incrementing field.</p><p><strong>@Column(name = “employeeFirstName”)</strong>:</p><p>Specifies the name of the column in the database table for the firstname field. Here, the column name will be employeeFirstName in the database.</p><p>If you don’t include the @Column annotation, the column name will default to the attribute&#39;s name.</p><p>Now to start the project, click the ‘RUN’ button and ensure that the database table has been created with all the necessary fields.</p><h3>Creating the Employee Repository</h3><p>In Spring Boot, a repository is a mechanism that allows interaction with the database by encapsulating read and write operations. It is part of the persistence layer and typically uses Spring Data JPA to simplify interactions with the database.</p><p><strong>Role of a Repository:</strong></p><ul><li><strong>Abstraction of Database Operations:</strong> Repositories provide an interface for performing CRUD (Create, Read, Update, Delete) operations without the need to write explicit SQL queries. This simplifies the code and makes it more readable.</li><li><strong>Entity Management:</strong> They are responsible for managing entities. For example, an EmployeeRepository would handle all operations related to the Employee entity.</li><li><strong>Custom Queries:</strong> Spring Data JPA allows defining custom search methods in repositories using naming conventions. For instance, a method named findByLastName could automatically generate a query to retrieve employees by their last name.</li><li><strong>Integration with JPA:</strong> Repositories utilize JPA to manage data persistence, which includes features such as transaction management, caching, and lazy loading.</li><li><strong>Simplicity:</strong> They enable focusing on business logic without worrying about the details of data access.</li></ul><p>Here is our repository, which inherits from JpaRepository, specifying the table name and the entity’s key type. By inheriting from JpaRepository, we take advantage of the advanced features of Spring Data JPA, such as automatic management of CRUD operations, pagination, sorting, and custom queries, which greatly simplifies our code and allows us to focus on business logic rather than the implementation details of data access.</p><p>The @Repository annotation indicates that EmployeeRepository is a component of the persistence layer and that it manages data access for the Employee entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJn3jGqQQYizgoJ4jZKJvw.png" /></figure><h3>Creating the Employee Service</h3><p>Services in Spring Boot play a crucial role in structuring and organizing applications. By centralizing business logic, they help maintain clean and modular code, this facilitating maintenance and evolution. Through their interaction with repositories, services efficiently manage data access while applying validation and processing rules. In summary, services serve as an intermediary layer that connects controllers and repositories, ensuring a clear separation of concerns and a robust architecture for the application.</p><h4>Roles of Services</h4><ul><li><strong>Business Logic</strong>: Encapsulate and manage the business logic of the application.</li><li><strong>Interaction with Repositories</strong>: Communicate with repositories to access database data.</li><li><strong>Abstraction</strong>: Provide an abstraction for the presentation layer, hiding implementation details.</li><li><strong>Data Validation</strong>: Include data validation before processing.</li><li><strong>Reusability</strong>: Promote the sharing of business logic across different controllers.</li><li><strong>External Integration</strong>: Manage integration with other systems or external services.</li></ul><p>The image below shows the employee interface when created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM5CuvDK8CiVuWwUp8W5Qg.png" /></figure><p>And here is our service class that we have implemented, along with an explanation of each part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_q4WqhUEi4euv2gBQNISag.png" /></figure><p><strong>@Service</strong></p><p>This annotation signifies that the annotated class is a service, serving as a specialization of the @Component annotation, which indicates that it is a component managed by the Spring container. It is used to mark service classes that encapsulate business logic, allowing Spring to automatically detect these classes during component scanning. This enables the framework to create instances of the service classes and manage them within the application context.</p><p><strong>implements IEmployeeService</strong></p><p>This part of the class declaration indicates that <strong>EmployeeServiceImpl </strong>commits to providing concrete implementations for all methods defined in the <strong>IEmployeeService </strong>interface. When a class implements an interface, it must provide a definition for all declared methods within that interface, ensuring that the class has a consistent and predictable structure. This allows other classes or components to work with instances of EmployeeServiceImpl without needing to worry about the details of its implementation.</p><p>Using interfaces also promotes the principle of programming to an interface, which is a key aspect of object-oriented architecture. This approach enhances abstraction and facilitates changes to implementations without affecting the code that relies on these interfaces.</p><p><strong>Dependency Injection</strong></p><p>Dependency Injection (DI) is a design principle that allows for the external provision of a class’s dependencies (the objects it requires), rather than having the class create them internally. This can typically be accomplished through constructors, methods, or properties. For instance, in a Spring application, the @Autowired annotation can be used to inject a dependency, facilitating better modularity and testability of the code.</p><p><strong>@Autowired</strong></p><p>This annotation enables Spring to automatically inject dependencies into classes. In this case, it is used to inject an instance of EmployeeRepository into EmployeeServiceImpl. With dependency injection, employeeRepository can be utilized to perform CRUD operations on Employee entities without the need to manually create an instance of EmployeeRepository.</p><p><strong>create Employee(Employee employee): </strong>Create a new employee and save it in the database.</p><p><strong>getAllEmployee():</strong> Retrieve all employees from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5wzJt4fKJtsBNs-9FhtqA.png" /></figure><p><strong>getEmployeeById(Long id):</strong> Retrieves a specific employee by id.<br><strong>updateEmployee(Long id, Employee employee):</strong> Updates the information of an existing employee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L60duvasEc1iDaT0G08vig.png" /></figure><p><strong>deleteEmployee(Long id): </strong>Deletes an employee based on their id.</p><h3>Creating the Employee Controller</h3><p>A controller in Spring Boot is a Java class that manages HTTP requests and coordinates responses sent to the client. In a Spring-based web application, controllers are responsible for receiving incoming requests (GET, POST, PUT, DELETE, etc.), processing data, calling services to apply business logic, and returning an appropriate response (usually in JSON or XML).</p><p>The capture below shows the controller for the Employee entity, which manages CRUD operations through a RESTful API. It handles HTTP requests (GET, POST, PUT, DELETE) to interact effectively with the service layer and ensures secure data management with integrated access control and error handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Okdhygkt5MkwWlX10ZrXQw.png" /></figure><p>@RestController: Indicates that the class is a REST controller, ready to handle HTTP requests and return JSON/XML responses.</p><p>@RequestMapping defines the base entry point (api/employee/), so all requests to this URL will be directed to this controller.</p><p>@Autowired: Indicates that Spring should automatically inject an instance of EmployeeServiceImpl into this controller. This facilitates dependency injection, allowing the EmployeeServiceImpl service to be used for employee management operations.</p><p><strong>@PostMapping(“createEmployee”)</strong></p><p>This annotation maps POST HTTP requests to the addEmployee method. This means that a POST request sent to api/employee/createEmployee will call this method.</p><h4>createEmployee(Employee employee)</h4><p>This method takes an Employee object as a parameter from the request body, then calls the createEmployee method from the service to add a new employee. It returns the created Employee object with its saved information.</p><h4>@GetMapping(&quot;getAllEmployee&quot;)</h4><p>This annotation maps GET HTTP requests to the getAllEmployee method. A GET request sent to api/employee/getAllEmployee will invoke this method to retrieve the list of all employees.</p><h4>getAllEmployee()</h4><p>This method calls the getAllEmployee method from the service to obtain a list of all employees. It returns the list of employees in JSON format.</p><h4>@GetMapping(&quot;getEmployeeById/{id}&quot;)</h4><p>This annotation maps GET HTTP requests to the getEmployeeById method. The {id} in the URL path represents a path parameter, and this method will be called when api/employee/getEmployeeById/{id} is invoked with a specific identifier.</p><p>@PathVariable is used in Spring to extract values from the URL and bind them to method parameters. For example, in @GetMapping(&quot;getEmployeeById/{id}&quot;), {id} is a URL variable that can be retrieved in the method using @PathVariable(&quot;id&quot;) Long id. This allows for the creation of dynamic and flexible routes to access resources.</p><h4>getEmployeeById(Long id)</h4><p>This method takes an id parameter from the URL and calls the getEmployeeById method from the service to obtain the details of a specific employee. It returns the corresponding Employee object or an error if the employee does not exist.</p><h4><strong>@PutMapping(&quot;updateEmployee/{id}&quot;)</strong></h4><p>This annotation maps PUT HTTP requests to the updateEmployee method. This method will be called when a PUT request is sent to api/employee/updateEmployee/{id}, with an identifier to update a specific employee.</p><h4><strong>updateEmployee(Long id, Employee employee)</strong></h4><p>This method takes an id and an Employee object from the request body. It calls the updateEmployee method in the service to update the information of the employee with the specified ID and returns the updated Employee object.</p><h4>@DeleteMapping(&quot;deleteEmployee/{id}&quot;)</h4><p>This annotation maps DELETE HTTP requests to the deleteEmployee method. When a DELETE request is sent to api/employee/deleteEmployee/{id}, this method deletes the corresponding employee.</p><h4><strong>deleteEmployee(Long id)</strong></h4><p>This method takes an identifier id as a URL parameter, calls the deleteEmployee method from the service to delete the corresponding employee, and returns a confirmation message indicating whether the deletion was successful.</p><h3>Test with Postman</h3><p>Now we will test the APIs with Postman.</p><h4><strong>Launch Postman on your computer.</strong></h4><h4><strong>Create a New Collection</strong></h4><p>1. <strong>Click on the “Collections” button</strong> in the left panel.</p><p><strong>2. Click on the “New Collection” button</strong> or the “+” symbol next to “Collections.”</p><p><strong>3. Give your collection a name</strong>, such as “Employee Management API.”</p><p><strong>4. Click “Create”</strong> to create the collection.</p><p><strong>Add a Request to Add an Employee (POST)</strong></p><ol><li>Select the collection you just created.</li><li>Click on the “Add Request” button.</li><li>Name the request, for example, “create Employee.”</li><li>Choose the request type (POST) from the dropdown menu.</li><li>Enter the URL: <a href="http://localhost:8081/api/employee/addEmployee.">http://localhost:8081/api/employee/createEmployee.</a></li><li>Go to the Body tab, select “raw,” and then choose “JSON.”</li><li>Add the request body in JSON format</li><li><strong>Click “Send”</strong> to send the request.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxYM5-KJyimFKkbkRRTyzw.png" /></figure><p><strong>Add a request to get all employees (GET) in Postman:</strong></p><ol><li><strong>Click on the “Add Request” button</strong> in your collection.</li><li><strong>Name the request</strong>, for example, “Get All Employees.”</li><li><strong>Select the request type</strong> (GET).</li><li><strong>Enter the URL</strong>: <a href="http://localhost:8080/api/employee/getAllEmployee.">http://localhost:8081/api/employee/getAllEmployee.</a></li><li><strong>Click “Send”</strong> to send the request.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Hrsx7wRknJGXZASbgyIyw.png" /></figure><p><strong>Add a request to get an employee by ID (GET) in Postman:</strong></p><ol><li><strong>Click on the “Add Request” button</strong> in your collection.</li><li><strong>Name the request</strong>, for example, “Get Employee By ID.”</li><li><strong>Select the request type</strong> (GET).</li><li><strong>Enter the URL</strong>: <a href="http://localhost:8080/api/employee/getEmployeeById/%7Bid%7D.">http://localhost:8081/api/employee/getEmployeeById/{id}.</a></li><li><strong>Replace </strong><strong>{id} with a real ID</strong>, for example, 1, so the URL becomes <a href="http://localhost:8080/api/employee/getEmployeeById/1.">http://localhost:8081/api/employee/getEmployeeById/1.</a></li><li><strong>Click “Send”</strong> to send the request.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPxG_4L-jr166mdEWQAACw.png" /></figure><p><strong>Add a Request to Update an Employee (PUT)</strong></p><ol><li>Click on the “Add Request” button.</li><li>Name the request, for example, “Update Employee.”</li><li>Choose the request type (PUT).</li><li>Enter the URL: <a href="http://localhost:8080/api/employee/updateEmployee/%7Bid%7D.">http://localhost:8081/api/employee/updateEmployee/{id}.</a></li><li>Replace {id} with the ID of the employee you want to update.</li><li>Add the request body in JSON format, for example:</li><li>Click on “Send.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpivxbdP2MvDaI915ccAmA.png" /></figure><p><strong>Add a Request to Delete an Employee (DELETE)</strong></p><ol><li>Click on the “Add Request” button.</li><li>Name the request, for example, “Delete Employee.”</li><li>Choose the request type (DELETE).</li><li>Enter the URL: <a href="http://localhost:8080/api/employee/deleteEmployee/%7Bid%7D.">http://localhost:8081/api/employee/deleteEmployee/{id}.</a></li><li>Replace {id} with the ID of the employee you want to delete.</li><li>Click on “Send.”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8Di_-P7qBIoQiAMqoCVrA.png" /></figure><h3>Conclusion</h3><p>Now that part of our project has been completed, we can proceed to finalize the other entities in the same manner. This will ensure consistency and efficiency in our development while making sure that each entity adheres to the standards we have established.</p><p>Here’s the link to the entire project on GitHub <a href="https://github.com/sidaouiMohamedamine/employee-management-backend"><strong>https://github.com/sidaouiMohamedamine/employee-management-backend</strong></a>.</p><p>Please clone the repository, update the database configurations if necessary, and start the project to test all your APIs.</p><p>If you have any questions, feel free to contact me through my LinkedIn profile<strong> </strong><a href="https://www.linkedin.com/in/sidaouimohamedamine/"><strong>https://www.linkedin.com/in/sidaouimohamedamine/</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b3ad3156d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>