<?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 MateoRamirezR on Medium]]></title>
        <description><![CDATA[Stories by MateoRamirezR on Medium]]></description>
        <link>https://medium.com/@matteo.dcj?source=rss-2ff61273e528------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ag2VstNtM3OujJnYphCO9Q.jpeg</url>
            <title>Stories by MateoRamirezR on Medium</title>
            <link>https://medium.com/@matteo.dcj?source=rss-2ff61273e528------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:22:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matteo.dcj/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[Configuring AWS VPC, Load Balancers, and DNS for WordPress and Moodle Integration]]></title>
            <link>https://medium.com/@matteo.dcj/configuring-aws-vpc-load-balancers-dns-ec2-wordpress-moodle-90907a460b27?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/90907a460b27</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 01:36:33 GMT</pubDate>
            <atom:updated>2024-09-07T01:40:18.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aQQYjnGE69YtGi6ekEQvA.png" /></figure><blockquote>Implementing High-Availability VPC Architectures, DNS Routing, and Load Balancing for WordPress and Moodle in AWS</blockquote><h3>Table of Contents</h3><ol><li><strong>Introduction.</strong></li><li><strong>System Architecture.</strong></li><li><strong>Implementation and Deployment.</strong></li></ol><ul><li>Configuration of the <strong>VPC</strong> and Subnets.</li><li>Configuration of the <strong>DNS Server.</strong></li><li>Configuration of the <strong>Load Balancer (HAProxy).</strong></li></ul><p><strong>4. Installation and Configuration of WordPress.</strong></p><p><strong>5. Installation and Configuration of Moodle.</strong></p><p><strong>6. Verification and Results.</strong></p><p><strong>7. Issues Encountered During Development, Troubleshooting, and/or Recommendations.</strong></p><p><strong>8. Conclusions.</strong></p><p><strong>9. References.</strong></p><h3>List of Figures</h3><ol><li><strong>AWS Resource Map.</strong></li><li><strong>Screenshot of EC2 Instances in AWS.</strong></li><li><strong>BIND Configuration File</strong> named.conf.local.</li><li><strong>BIND Configuration File</strong> db.learxyz.online.</li><li><strong>BIND Configuration File</strong> db.10.</li><li><strong>HAProxy Configuration File</strong> haproxy.cfg.</li><li><strong>HAProxy Statistics Page.</strong></li><li><strong>WordPress Main Page.</strong></li><li><strong>Moodle Learning Portal.</strong></li><li><strong>AWS Security Group Configuration.</strong></li><li><strong>Route 53 Configuration.</strong></li><li><strong>DNS Propagation Verification on WhatsMyDNS.</strong></li></ol><h3>Introduction</h3><p>The project involves the deployment of a <strong>cloud services environment</strong> for <strong>XYZ S.A. Manufacturas (Fictitious not real company)</strong>. The goal is to create a scalable and highly available infrastructure using <strong>AWS</strong>, which includes a <strong>CMS</strong> (WordPress), an <strong>LMS</strong> (Moodle), and a load balancer (<strong>HAProxy</strong>). The setup includes creating a <strong>VPC</strong> with public and private subnets, installing services on <strong>EC2 instances</strong>, and configuring a domain in <strong>Route 53</strong>.</p><h3>System Architecture</h3><h4>AWS Resource Map</h4><p><strong><em>Figure 1: AWS Resource Map</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*uWNFhFPdXIiy_-dl8_q4hg.png" /></figure><p>The resource map shows the <strong>VPC</strong> structure implemented for <strong>XYZ S.A. Manufacturas</strong>. It includes:</p><ul><li><strong>VPC (Virtual Private Cloud)</strong>: XYZSA-vpc-01, which houses all network resources.</li></ul><p><strong>Subnets</strong>:</p><ul><li>Public-subnet-XYZSA-01: Public subnet containing the public instance.</li><li>Private-subnet-XYZSA-01: Private subnet containing application and database instances.</li></ul><p><strong>Route Tables</strong>:</p><ul><li>Public-Route-Table-XYZSA-VPC: Manages traffic for the public subnet.</li><li>Private-Route-Table-XYZSA-VPC: Manages traffic for the private subnet.</li></ul><p><strong>Network Connections</strong>:</p><ul><li><strong>Internet Gateway</strong> (ig-XYZSA-vpc): Enables Internet connectivity for the <strong>VPC</strong>.</li><li><strong>NAT Gateway</strong> (Nat-gateway-XYZSA-VPC): Enables instances in the private subnet to securely access the Internet.</li></ul><h3>Implementation and Deployment</h3><h4>VPC and Subnet Configuration</h4><p><strong><em>Figure 2: Screenshot of EC2 Instances in AWS</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zqcvVeq5cVIH9ZiE.png" /></figure><p>This screenshot shows the <strong>EC2 instances</strong> deployed in AWS:</p><ul><li><strong>private-instance-CMS-01-XYZSA</strong> and <strong>private-instance-CMS-02-XYZSA</strong>: These instances host the <strong>WordPress CMS</strong>. Having two instances allows for <strong>high availability</strong> and <strong>load balancing</strong>.</li><li><strong>private-instance-DB-01-XYZSA</strong>: This instance hosts the <strong>MariaDB database</strong>, accessible only from the application instances.</li><li><strong>private-instance-LMS-01-XYZSA</strong>: This instance runs the <strong>Moodle LMS</strong>.</li><li><strong>public-instance-01-XYZSA</strong>: This public instance acts as a <strong>load balancer</strong> and <strong>DNS server</strong>, directing traffic to the appropriate instances in the private subnet.</li></ul><h4>DNS Server Configuration</h4><p><strong><em>Figure 3: BIND Configuration File</em></strong> named.conf.local</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*5lS2ut9crjfmarIb.png" /></figure><p>This file configures the <strong>BIND DNS server</strong> to resolve domain names to IP addresses:</p><ul><li><strong>zone “learxyz.online”</strong>: Defines the primary zone for the domain learxyz.online, indicating that DNS records for this domain are in db.learxyz.online.</li><li><strong>zone “1.0.10.in-addr.arpa”</strong>: Defines the zone for <strong>reverse IP resolution</strong> in the 10.0.1.0 subnet, with records in db.10.</li></ul><p><strong><em>Figure 4: BIND Configuration File</em></strong> db.learxyz.online</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*xxP4ILnDdlNzltp9.png" /></figure><p>This file contains the specific DNS records for learxyz.online:</p><ul><li><strong>SOA Record</strong>: Defines the origin server and zone update parameters.</li><li><strong>NS Records</strong>: ns1.learxyz.online and ns2.learxyz.online are the authoritative name servers.</li><li><strong>A Records</strong>: ns1 and ns2 point to 100.27.144.145 (elastic IP of the public instance). The @ (root domain) also points to 100.27.144.145.</li><li><strong>CNAME Record</strong>: www.learxyz.online is an alias pointing to @, resolving to 100.27.144.145.</li><li><strong>A Record</strong>: lms.learxyz.online points to 100.27.144.145.</li></ul><p>These records ensure that all DNS requests for <strong>learxyz.online</strong> and its subdomains are directed to the <strong>elastic IP</strong> of the public instance, where <strong>HAProxy</strong> will load balance the traffic.</p><p><strong><em>Figure 5: BIND Configuration File</em></strong> db.10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*gVyuSeJQGlnsRPZh.png" /></figure><p>This file contains the <strong>reverse resolution</strong> records:</p><ul><li><strong>PTR Records</strong>: Maps IP addresses to corresponding domain names. 10.0.1.10 resolves to www.learxyz.online and 10.0.1.12 to lms.learxyz.online.</li></ul><p>These records allow for <strong>reverse DNS resolution</strong>, useful for diagnostics and certain applications requiring domain name verification from IPs.</p><h4>Load Balancer Configuration (HAProxy)</h4><p><strong><em>Figure 6: HAProxy Configuration File</em></strong> haproxy.cfg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*brpxG4PHusMo5IQU.png" /></figure><p>This file configures <strong>HAProxy</strong>, the <strong>load balancer</strong>:</p><ul><li><strong>Listen stats</strong>: Enables the statistics interface on port 8080, accessible with basic authentication.</li><li><strong>Frontend http_front</strong>: Defines a frontend listening on port 80. Uses <strong>ACLs</strong> to redirect traffic based on the host name:</li><li>learxyz.online and www.learxyz.online are directed to the backend wordpress_servers.</li><li>lms.learxyz.online is directed to the backend moodle_servers.</li><li><strong>Backend wordpress_servers</strong>: Balances traffic between two <strong>WordPress instances</strong> (10.0.1.119 and 10.0.1.129).</li><li><strong>Backend moodle_servers</strong>: Balances traffic to the <strong>Moodle instance</strong> (10.0.1.174).</li></ul><p><strong>HAProxy</strong> distributes incoming requests to the appropriate instances, ensuring <strong>high availability</strong> and <strong>redundancy</strong>.</p><p><strong><em>Figure 7: HAProxy Statistics Page</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zy1pZRMbkbL912rttIzhOw.png" /></figure><p>This page provides real-time statistics on <strong>HAProxy’s performance</strong>:</p><ul><li><strong>Connection Status</strong>: Shows the number of active and queued connections.</li><li><strong>Processed Traffic</strong>: Incoming and outgoing bytes, denied requests, and errors.</li><li><strong>Backend Instance Status</strong>: Indicates whether instances are active and available for load balancing.</li></ul><h4>WordPress Installation and Configuration</h4><p><strong><em>Figure 8: WordPress Homepage</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/0*8F53SL6ecybAeybI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*A0M-OzlXI2CJXX48.png" /></figure><p>These images show the homepage of the <strong>WordPress site</strong> at www.learxyz.online. The page changes language when reloaded in the browser to demonstrate <strong>load balancing</strong>, distributing requests between the two <strong>WordPress instances</strong>. This ensures the site remains available even if one instance fails.</p><h4>Moodle Installation and Configuration</h4><p><strong><em>Figure 9: Moodle Learning Portal</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*pS9wNpHs5iY0-ysN.png" /></figure><p>This image shows the <strong>Moodle learning portal</strong> at lms.learxyz.online. The course &quot;Introduction to XYZ Manufacturing&quot; is available, designed to train employees on the company&#39;s manufacturing processes. <strong>Moodle</strong> is configured to provide a robust and scalable platform for <strong>online education and training</strong>.</p><h3>Verification and Results</h3><p><strong><em>Figure 10: AWS Security Group Configuration</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*EP83Rn05i5LA33VB.png" /></figure><p><strong>Security Group</strong> rules control access to <strong>EC2 instances</strong>:</p><ul><li><strong>ICMP</strong>: Allows all <strong>ICMP packets</strong> for diagnostics (ping).</li><li><strong>SSH (22)</strong>: Allows <strong>SSH access</strong> for remote administration.</li><li><strong>MySQL/Aurora (3306)</strong>: Allows <strong>MySQL traffic</strong> from any IP, enabling connection to the database.</li><li><strong>DNS (UDP 53)</strong> and <strong>DNS (TCP 53)</strong>: Allow DNS traffic.</li><li><strong>Custom TCP (8080)</strong>: Allows access to the <strong>HAProxy statistics page</strong>.</li><li><strong>HTTP (80)</strong> and <strong>HTTPS (443)</strong>: Allow HTTP and HTTPS traffic for web access.</li></ul><p>These rules ensure that instances are accessible only through the necessary ports, improving security.</p><p><strong><em>Figure 11: Route 53 Configuration</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*5DsfAYUmM40JnI-2.png" /></figure><p><strong>Route 53</strong> manages traffic routing for learxyz.online:</p><ul><li><strong>A Record</strong>: learxyz.online points to <strong>elastic IP</strong> 100.27.144.145, directing all traffic to the load balancer.</li><li><strong>NS Records</strong>: Defines the <strong>authoritative name servers</strong>.</li><li><strong>SOA Record</strong>: Contains origin server information and zone parameters.</li><li><strong>A Record</strong>: lms.learxyz.online points to 100.27.144.145.</li><li><strong>CNAME Record</strong>: www.learxyz.online is an alias pointing to learxyz.online.</li></ul><p>These records ensure that requests for learxyz.online and its subdomains are properly directed to the <strong>public instance</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*jJqX6iHDV8wrxxNE.png" /></figure><p><strong><em>Figure 12: DNS Propagation Verification in WhatsMyDNS</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*hb1X3xdq3wTgknpo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eb5WRX4at7uSqCzr.png" /></figure><p>This image shows <strong>DNS record propagation</strong> using <strong>WhatsMyDNS</strong>. Successful global propagation ensures that learxyz.online resolves correctly to 100.27.144.145 from multiple locations worldwide, guaranteeing <strong>accessibility</strong> and <strong>redundancy</strong>.</p><h3>Issues Encountered, Troubleshooting, and Recommendations</h3><p>Several issues were encountered during project development that required attention and resolution:</p><ol><li><strong>DNS Server Configuration:</strong></li></ol><ul><li><strong>Issue:</strong> DNS records did not propagate correctly initially.</li><li><strong>Solution:</strong> The BIND records were reviewed and corrected, ensuring the name servers pointed to the correct elastic IP. WhatsMyDNS was used to confirm global propagation of the records.</li></ul><p><strong>2. HAProxy Load Balancer Configuration:</strong></p><ul><li><strong>Issue:</strong> HTTP traffic was not evenly distributed between the WordPress instances.</li><li><strong>Solution:</strong> ACLs and backend settings in haproxy.cfg were adjusted to ensure all requests were properly load balanced.</li></ul><p><strong>3. WordPress and Moodle Installation:</strong></p><ul><li><strong>Issue:</strong> WordPress instances displayed the default Apache page instead of WordPress content.</li><li><strong>Solution:</strong> WordPress files were correctly moved to the web server’s root directory, and the proper permissions were set.</li></ul><p><strong>4. Security Group Configuration:</strong></p><ul><li><strong>Issue:</strong> Access to necessary service ports was restricted.</li><li><strong>Solution:</strong> Security Group rules were updated to allow traffic on specific ports (80, 443, 22, 3306, 53, 8080).</li></ul><p><strong>5. Moodle Configuration:</strong></p><ul><li><strong>Issue:</strong> Missing required PHP extensions during Moodle installation.</li><li><strong>Solution:</strong> Required PHP extensions (xml, intl, zip, etc.) were installed and enabled, and PHP configurations (max_input_vars, memory_limit) were adjusted to meet Moodle’s requirements.</li></ul><h3>Conclusions</h3><p>The project demonstrated XYZ S.A. Manufacturas’ ability to implement a scalable and highly available cloud infrastructure. AWS and HAProxy provided the necessary flexibility and redundancy to support the company’s critical applications. The following points highlight the project’s conclusions:</p><ul><li><strong>Scalability:</strong> The infrastructure can easily scale to handle increased traffic and workload.</li><li><strong>High Availability:</strong> Redundancy and load balancing ensure that services remain available even if an instance fails.</li><li><strong>Security:</strong> Proper configuration of Security Groups and access policies ensures resources are accessible only by authorized users.</li></ul><h3>Future Work</h3><p>Future recommendations for XYZ S.A. Manufacturas include:</p><ul><li><strong>Automation:</strong> Implement AWS Lambda functions to automate system monitoring and scaling.</li><li><strong>Monitoring:</strong> Use AWS CloudWatch for real-time monitoring of infrastructure performance and resource utilization.</li><li><strong>Disaster Recovery:</strong> Set up automatic backups and a disaster recovery plan to ensure business continuity in case of failures.</li></ul><h3>References</h3><ul><li>“Amazon Web Services (AWS) Documentation,” AWS, [Online]. Available: <a href="https://docs.aws.amazon.com/">https://docs.aws.amazon.com/</a>.</li><li>“HAProxy Documentation,” HAProxy Technologies, [Online]. Available: <a href="https://www.haproxy.org/">https://www.haproxy.org/</a>.</li><li>“Moodle Documentation,” Moodle, [Online]. Available: <a href="https://docs.moodle.org/">https://docs.moodle.org/</a>.</li><li>“WordPress Documentation,” WordPress, [Online]. Available: <a href="https://wordpress.org/documentation/">https://wordpress.org/documentation/</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90907a460b27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Introduction to Parallel Computing in Go: A Practical Approach with Goroutines, WaitGroups…]]></title>
            <link>https://medium.com/@matteo.dcj/introduction-to-parallelism-in-go-goroutines-mutexes-waitgroups-e8c5b3f35a1a?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c5b3f35a1a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[parallel-computing]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 01:44:00 GMT</pubDate>
            <atom:updated>2024-08-19T01:44:00.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Quick Introduction to Parallel Computing in Go: A Practical Approach with Goroutines, WaitGroups, Mutexes and Atomic Operations</h3><blockquote>Parallelism Fundamentals in Go: Learn how to Implement Goroutines and WaitGroups to Run Tasks Concurrently</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Z4cV8PirzEHJTZJrygNjg.png" /></figure><h3>Introduction</h3><p>A fundamental technique for improving performance is <strong>parallel computing</strong>, which allows multiple tasks to run simultaneously to make the best use of system resources. In this blog, we will explore how to implement parallel programming techniques in Go, using practical examples and key concepts such as <strong>goroutines, WaitGroups, Mutexes and atomic operations</strong>.</p><h3>Introduction to Parallel Computing</h3><p><strong>Parallel computing</strong> is a form of processing in which tasks are divided into sub-tasks that can be executed at the same time. This contrasts with <strong>sequential computing</strong>, where tasks are executed one after the other. The main idea is that by executing multiple operations simultaneously, the overall execution time can be reduced and the overall efficiency of the system can be improved.</p><h3>Parallelism vs. Concurrency</h3><p>It is important to differentiate between <strong>parallelism</strong> and <strong>concurrency</strong>:</p><ul><li><strong>Parallelism:</strong> This refers to the simultaneous execution of multiple tasks. In the context of computing, this generally involves the use of multiple CPU cores to execute tasks at the same time. In Go, this is achieved through the use of goroutines and the thread-based execution model.</li><li><strong>Concurrency:</strong> The ability to handle multiple tasks in such a way that they appear to be running simultaneously, even if they are not necessarily running in parallel. Concurrency can involve switching between tasks on a single CPU core. In Go, concurrency is handled by goroutines and channels, facilitating the creation of programs that can do multiple things at once.</li></ul><h3>Parallel Computing in Go</h3><p>Go, known for its simplicity and efficiency, offers powerful tools for parallel programming. Among them, goroutines are fundamental. <strong>Goroutines </strong>are functions that run concurrently with other functions. They are lightweight and managed by the Go runtime, allowing highly parallelised applications to be created without additional complications.</p><ul><li><strong>Goroutines:</strong> These are the basic unit of execution in Go. They are created using the go keyword, and the Go runtime handles the concurrent and parallel execution of these goroutines.</li><li><strong>WaitGroups:</strong> These are used to wait for a set of goroutines to finish execution. They provide a form of synchronisation between goroutines, ensuring that all parallel tasks complete before continuing.</li><li><strong>Mutexes: </strong>These are mechanisms to control concurrent access to shared resources. They prevent race condition problems, where two or more goroutines attempt to access and modify the same resource simultaneously, which can lead to unexpected results or errors.</li></ul><p>In this blog, we will use a practical example of parallel processing in Go to illustrate these concepts. Through the analysis of code that performs parallel mapping, filtering and reduction operations, we will see how to apply these concepts to improve performance and efficiency in Go applications. We will explore how goroutines and other tools provided by the language can be used to achieve faster and more efficient data processing.</p><h3>Key Components in the Code</h3><p>In this section, we will discuss in detail the essential components of our code, explaining how goroutines, sync.WaitGroup, sync.Mutex and atomic operations are used to implement parallel programming in Go.</p><p><strong>You can find the complete code here:</strong></p><p><a href="https://github.com/MateoRamirezRubio1/learning_Go_Golang/blob/main/parallelismAndConcurrency/parallel_map_filter_reduce.go">learning_Go_Golang/parallelismAndConcurrency/parallel_map_filter_reduce.go at main · MateoRamirezRubio1/learning_Go_Golang</a></p><h3>Goroutines</h3><p><strong>Goroutines </strong>are a fundamental feature of Go that allows concurrent execution of functions. They are created by using the go keyword before a function or function expression. Goroutines are lightweight and managed by the Go runtime, which means that they can be created and managed in large numbers without a high resource cost.</p><p>In the code, goroutines are used to perform parallel operations on different parts of a slice. This is done in the parallelMap, parallelFilter, and parallelReduce functions:</p><pre>// Each worker applies the mapping function to its chunk of the slice.<br>		go func(start, end int) {<br>			defer wg.Done()<br>			for j := start; j &lt; end; j++ {<br>				result[j] = mapFunc(nums[j])<br>			}<br>		}(start, end)</pre><p>Each goroutine takes a segment of the nums slice and applies the mapFunc function to each element of that segment. The use of goroutines allows multiple segments of the slice to be processed at the same time, reducing the overall execution time.</p><h3>WaitGroups</h3><p>The sync.WaitGroup is a synchronisation tool used to wait for a group of goroutines to complete their execution. It is used to coordinate the completion of multiple goroutines and ensure that all goroutines have finished before continuing the execution of the program.</p><p>In the code, sync.WaitGroup is used to ensure that the main program waits for all goroutines to finish before continuing:</p><pre>// Create a WaitGroup to synchronize the workers.<br> var wg sync.WaitGroup<br><br> // Start the workers.<br> for i := 0; i &lt; numWorkers; i++ {<br>  start := i * chunkSize<br>  end := start + chunkSize<br>  if i == numWorkers-1 {<br>   end = n<br>  }<br>  wg.Add(1)<br>  // Each worker applies the mapping function to its chunk of the slice.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   for j := start; j &lt; end; j++ {<br>    result[j] = mapFunc(nums[j])<br>   }<br>  }(start, end)<br> }<br><br> // Wait for all workers to finish.<br> wg.Wait()</pre><p>Here, wg.Add(1) increments the WaitGroup counter each time a new goroutine is started. Each goroutine calls wg.Done() when it finishes, decrementing the counter. wg.Wait() blocks the main thread until the counter reaches zero, i.e. until all goroutines have finished their work.</p><h3>Mutexes</h3><p>The sync.Mutex is a synchronisation mechanism used to prevent race conditions, which occur when multiple goroutines attempt to access and modify shared data at the same time. A mutex ensures that only one goroutine can access a critical section of code at a time.</p><p>In the code, sync.mutex is used to protect access to the result slice during filtering and reduction operations:</p><pre>// Create a Mutex to protect the result slice.<br> var mu sync.Mutex<br><br>// Each worker filters its chunk of the slice and appends the results to the local result slice.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   localResult := make([]int, 0, end-start)<br>   for j := start; j &lt; end; j++ {<br>    if filterFunc(nums[j]) {<br>     localResult = append(localResult, nums[j])<br>    }<br>   }<br>   // Lock the Mutex and append the local result slice to the global result slice.<br>   mu.Lock()<br>   result = append(result, localResult...)<br>   mu.Unlock()<br>  }(start, end)</pre><p>The mutex mu is used to ensure that only one goroutine can modify result at any given time. mu.Lock() acquires the mutex before modifying result, and mu.Unlock() releases the mutex after the modification.</p><h3>Atomic Operations</h3><p>Atomic operations allow operations on shared variables to be performed safely without the need for mutexes. The sync/atomic package provides operations such as addition, subtraction, and compare and shift, which are atomic and ensure that operations are safe in a concurrent environment.</p><p>In the code, atomic.AddInt32 is used to perform the reduction safely:</p><pre>var result int32<br><br>// Each worker reduces its chunk of the slice and atomically adds the result to the global result variable.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   localResult := nums[start]<br>   for j := start + 1; j &lt; end; j++ {<br>    localResult = reduceFunc(localResult, nums[j])<br>   }<br>   // Lock the Mutex and atomically add the local result to the global result variable.<br>   mu.Lock()<br>   atomic.AddInt32(&amp;result, int32(localResult))<br>   mu.Unlock()<br>  }(start, end)</pre><p>Here, atomic.AddInt32(&amp;result, int32(localResult)) adds the localResult value to the result variable atomically, avoiding synchronisation problems without the need to use a mutex.</p><h3>Parallel Execution in Action: Mapping, Filtering and Reduction</h3><p>Now, we will examine how mapping, filtering, and reduction operations are implemented in parallel using goroutines, sync.WaitGroup, sync.Mutex, and atomic operations. These operations are common in data processing and benefit greatly from parallel programming to improve performance.</p><h3>Parallel Mapping</h3><p><strong>Mapping</strong> is the process of applying a function to each element of a data set and transforming those elements into new values. In the code provided, parallelMap performs this operation in parallel.</p><p><strong>Implementation</strong></p><pre>// parallelMap applies a mapping function to each element of a slice in parallel.<br>func parallelMap(nums []int, mapFunc func(int) int, numWorkers int) []int {<br> n := len(nums)<br> // Create a result slice of the same length as the input slice.<br> result := make([]int, n)<br> // Calculate the chunk size for each worker.<br> chunkSize := n / numWorkers<br> // Create a WaitGroup to synchronize the workers.<br> var wg sync.WaitGroup<br><br> // Start the workers.<br> for i := 0; i &lt; numWorkers; i++ {<br>  start := i * chunkSize<br>  end := start + chunkSize<br>  if i == numWorkers-1 {<br>   end = n<br>  }<br>  wg.Add(1)<br>  // Each worker applies the mapping function to its chunk of the slice.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   for j := start; j &lt; end; j++ {<br>    result[j] = mapFunc(nums[j])<br>   }<br>  }(start, end)<br> }<br><br> // Wait for all workers to finish.<br> wg.Wait()<br> return result<br>}</pre><p><strong>Explanation</strong></p><ol><li><strong>Creating the Result Slice: </strong>A result slice is created with the same length as the nums input slice. This slice will store the mapping results.</li><li><strong>Division of Labour:</strong> The chunk size for each goroutine is calculated as n / numWorkers. Each goroutine will process a section of the nums slice, from index start to end.</li><li><strong>Launching Goroutines:</strong> A goroutine is started for each slice segment. Each goroutine applies the mapFunc function to its segment of nums and stores the result in result.</li><li><strong>Synchronisation:</strong> sync.WaitGroup is used to wait for all goroutines to finish. wg.Add(1) is called before starting each goroutine, and wg.Done() is called at the end.</li><li><strong>Wait for Completion:</strong> wg.Wait() blocks execution until all goroutines have finished their work, ensuring that result is completely filled with mapped values.</li></ol><h3>Parallel Filtering</h3><p><strong>Filtering</strong> is the process of selecting elements from a dataset that meet a specific condition. In parallelFilter, this process is done in parallel to improve performance.</p><p><strong>Implementation</strong></p><pre>// parallelFilter filters a slice in parallel using a filtering function.<br>func parallelFilter(nums []int, filterFunc func(int) bool, numWorkers int) []int {<br> n := len(nums)<br> chunkSize := n / numWorkers<br> var wg sync.WaitGroup<br> // Create a Mutex to protect the result slice.<br> var mu sync.Mutex<br> result := make([]int, 0, n)<br><br> for i := 0; i &lt; numWorkers; i++ {<br>  start := i * chunkSize<br>  end := start + chunkSize<br>  if i == numWorkers-1 {<br>   end = n<br>  }<br>  wg.Add(1)<br>  // Each worker filters its chunk of the slice and appends the results to the local result slice.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   localResult := make([]int, 0, end-start)<br>   for j := start; j &lt; end; j++ {<br>    if filterFunc(nums[j]) {<br>     localResult = append(localResult, nums[j])<br>    }<br>   }<br>   // Lock the Mutex and append the local result slice to the global result slice.<br>   mu.Lock()<br>   result = append(result, localResult...)<br>   mu.Unlock()<br>  }(start, end)<br> }<br><br> // Wait for all workers to finish.<br> wg.Wait()<br> return result<br>}</pre><p><strong>Explanation</strong></p><ol><li><strong>Creating the Result Slice:</strong> A result slice is created which is initially empty. This slice will store the elements that pass the filter.</li><li><strong>Division of Labour:</strong> Each goroutine processes a section of the nums slice, applying the filterFunc function to select the elements that meet the condition. Accumulation of</li><li><strong>Local Results:</strong> Each goroutine maintains a local slice localResult to temporarily store the elements that pass the filter. This avoids data contention between goroutines.</li><li><strong>Mutex Access Protection:</strong> After a goroutine completes its filtering, it uses mu.Lock() to ensure exclusive access to the result slice and aggregate the filtered items. mu.Unlock() releases the mutex after the operation.</li><li><strong>Synchronisation:</strong> sync.WaitGroup is used to wait for all goroutines to finish. wg.Add(1) is called before starting each goroutine, and wg.Done() is called at the end.</li><li><strong>Wait for Completion:</strong> wg.Wait() ensures that result is completely filled before returning it.</li></ol><h3>Parallel Reduction</h3><p><strong>Reduction</strong> is the process of combining all elements of a dataset into a single value using a reduce function. In parallelReduce, this process is performed in parallel.</p><p><strong>Implementation</strong></p><pre>// parallelReduce reduces a slice in parallel using a reduction function.<br>func parallelReduce(nums []int, reduceFunc func(int, int) int, numWorkers int) int {<br> n := len(nums)<br> chunkSize := n / numWorkers<br> var wg sync.WaitGroup<br> var mu sync.Mutex<br> var result int32<br><br> for i := 0; i &lt; numWorkers; i++ {<br>  start := i * chunkSize<br>  end := start + chunkSize<br>  if i == numWorkers-1 {<br>   end = n<br>  }<br>  wg.Add(1)<br>  // Each worker reduces its chunk of the slice and atomically adds the result to the global result variable.<br>  go func(start, end int) {<br>   defer wg.Done()<br>   localResult := nums[start]<br>   for j := start + 1; j &lt; end; j++ {<br>    localResult = reduceFunc(localResult, nums[j])<br>   }<br>   // Lock the Mutex and atomically add the local result to the global result variable.<br>   mu.Lock()<br>   atomic.AddInt32(&amp;result, int32(localResult))<br>   mu.Unlock()<br>  }(start, end)<br> }<br><br> // Wait for all workers to finish.<br> wg.Wait()<br> return int(result)<br>}</pre><p><strong>Explanation</strong></p><ol><li><strong>Result initialisation:</strong> result is a variable of type int32 that is used to store the final accumulated value. It is initialised with a default value.</li><li><strong>Division of Labour:</strong> Each goroutine processes a segment of the nums slice, applying the reduceFunc function to combine the values into a partial result.</li><li><strong>Local Result Calculation:</strong> Each goroutine maintains a localResult variable to accumulate the partial result of its segment. The reduceFunc function is applied iteratively to the elements of the segment.</li><li><strong>Atomic Update:</strong> After calculating the partial result, atomic.AddInt32 is used to add localResult to the result variable atomically. This ensures that the update is safe in a concurrent environment without using a mutex for synchronisation.</li><li><strong>Synchronisation:</strong> sync.WaitGroup is used to wait for all goroutines to finish. wg.Add(1) is called before starting each goroutine, and wg.Done() is called on completion.</li><li><strong>Wait for Completion:</strong> wg.Wait() blocks until all goroutines have finished, ensuring that result contains the final accumulated value.</li></ol><h3>Detailed Explanation of main</h3><p>main() is the main function in a Go program, and in this case, it coordinates the execution of parallel processing in the program. In the following, we will break down each part of main to understand how it works and what its purpose is.</p><h4><strong>Data Generation</strong></h4><pre>// Generate a random slice of 1000000 integers between 1 and 9.<br>nums := generateRandomSlice(1000000, 1, 9)<br>fmt.Println(&quot;First numbers:&quot;, nums[:10])</pre><ul><li><strong>Data Generation:</strong> The generateRandomSlice function is used to create a 1,000,000 slice of random integers in the range 1 to 9. This slice simulates a large data set to process.</li><li><strong>Print First Numbers:</strong> A portion of the slice (nums[:10]) is printed to show the first 10 numbers generated. This is useful to verify that the data generation was successful.</li></ul><h4>Measuring Execution Time</h4><pre>// Start measuring execution time.<br>start := time.Now()</pre><ul><li><strong>Measurement Start:</strong> time.Now() is used to capture the current time, marking the start of the measurement of parallel processing execution time. This will allow to calculate how long it takes to complete all parallel operations.</li></ul><h4>Configuring the Number of Workers</h4><pre>// Get the number of CPUs available.<br>numWorkers := runtime.NumCPU()</pre><ul><li><strong>Number of Workers: </strong>runtime.NumCPU() returns the number of CPU cores available on the machine. This value is used to define how many workers (goroutines) will be used in parallel processing. Using a number equal to the number of CPU cores helps to optimise performance. In the next section when we run the code we will go more into this.</li></ul><h4>Application of Parallel Functions</h4><pre>// Apply the mapping function in parallel.<br>mapped := parallelMap(nums, func(x int) int { return x * 2 }, numWorkers)</pre><ul><li><strong>Application of parallelMap: </strong>The parallelMap function is called to apply a mapping function to each element of the slice nums. In this case, the mapping function multiplies each number by 2.</li></ul><pre>// Apply the filtering function in parallel.<br>filtered := parallelFilter(mapped, func(x int) bool { return x &gt; 10 }, numWorkers)</pre><ul><li><strong>Application of parallelFilter:</strong> The parallelFilter function is called to filter the mapped slice, keeping only elements greater than 10.</li></ul><pre>// Apply the reduction function in parallel.<br>result := parallelReduce(filtered, func(acc, x int) int { return acc + x }, numWorkers)</pre><ul><li><strong>Application of parallelReduce:</strong> The parallelReduce function is called to reduce the filtered slice by summing all elements. The reduce function takes an accumulator and an element, and returns their sum.</li></ul><h4>Printout of Results</h4><pre>fmt.Println(&quot;Result:&quot;, result)</pre><ul><li><strong>Print Result: </strong>The final result of the reduction is printed. This is the aggregated value of all elements that passed the filter.</li></ul><h4>Measuring Execution Time</h4><pre>// Stop measuring execution time and print the duration.<br>duration := time.Since(start)<br>fmt.Println(&quot;Execution time:&quot;, duration)</pre><ul><li><strong>End of Measurement:</strong> time.Since(start) calculates the duration from the start of parallel processing to the current time. This duration is printed to show how long it took to perform all parallel operations.</li></ul><h3>Examples of results and numWorkers</h3><pre>numWorkers := runtime.NumCPU()</pre><p>The line numWorkers := runtime.NumCPU() is a key part of the code that allocates the number of workers to be used to process tasks in parallel. This line uses the runtime.NumCPU() function, which returns the number of CPU cores available on the system where the program is running. This number is then assigned to numWorkers, which determines how many goroutines will be created to split the work.</p><h3>Use Cases and Considerations</h3><ol><li><strong>Parallelism Optimisation:</strong></li></ol><ul><li><strong>CPU Leverage:</strong> By using runtime.NumCPU(), the code attempts to take full advantage of the available hardware by allocating one goroutine per CPU core. This can improve performance by distributing the workload across all cores, allowing multiple tasks to run in parallel without saturating a single core.</li></ul><p><strong>2. Avoid Goroutine Overload:</strong></p><ul><li><strong>Worker/Task Balance: </strong>If numWorkers is equal to or close to runtime.NumCPU(), the program is likely to maintain an appropriate balance between the number of workers and system capabilities. However, if this number is significantly exceeded, performance may suffer due to system overhead from creating and managing too many goroutines, which can lead to unnecessary competition for system resources.</li></ul><p><strong>3. Problems with Small Data Sizes:</strong></p><ul><li><strong>More Workers than Tasks:</strong> If the number of workers (numWorkers) is greater than the number of elements in the array, a problem can occur. For example, if you have an array with 4 elements and numWorkers is 8 (assuming the CPU has 8 cores), some goroutines will not have enough elements to process. This can cause incorrect or inefficient behaviour, such as:</li><li><strong>Resource Waste: </strong>Some goroutines may end up not doing any useful work, which wastes system resources.</li><li><strong>Incorrect results:</strong> Depending on how the code is structured, if the work is divided into more goroutines than elements in the array, some goroutines might not process any data, which could lead to incorrect results.</li></ul><p><strong>4. Manual Tuning of numWorkers:</strong></p><ul><li><strong>Optimisation for Specific Data:</strong> In some cases, it may be beneficial to manually set numWorkers instead of using runtime.NumCPU(). For example, if you know the array size is small, you can set numWorkers to a lower number to avoid over-allocating goroutines. This can result in more efficient code that is easier to debug.</li></ul><p><strong>5. Behaviour with Very Large Arrays:</strong></p><ul><li><strong>Equal Division of Labor:</strong> When working with very large arrays, runtime.NumCPU() can help ensure that each CPU core gets a reasonable share of the work. This is especially useful in intensive operations where parallelism can significantly reduce execution time.</li></ul><h3>Practical Example</h3><p>Suppose you are running code on a system with 8 CPU cores (runtime.NumCPU() returns 8). If you have an array with 100 elements, and you use numWorkers := 8, each goroutine will process 12 or 13 elements (100/8 = 12.5). This is usually efficient.</p><p>However, if the array has only 4 elements and numWorkers is still 8, then each goroutine will handle half an element, which is impractical and may cause some goroutines to do nothing, or even throw errors if the code does not handle this scenario correctly.</p><h3>Execution and result verification</h3><p>To:</p><pre>nums := generateRandomSlice(10, 1, 9)<br>fmt.Println(&quot;First numbers:&quot;, nums[:10])<br><br>// Start measuring execution time.<br>start := time.Now()<br>// Get the number of CPUs available.<br>numWorkers := 3</pre><p>When running the code with the command go run parallel_map_filter_reduce.go, with the above parameters set in the main(), we get in console:</p><pre>First numbers: [3 6 1 2 8 1 7 2 8 6]<br>Result: 70<br>Execution time: 514.3µs</pre><h3>Execution Explanation</h3><ol><li><strong>Random Slice Generation:</strong></li></ol><ul><li>generateRandomSlice(10, 1, 9) generates a slice of 10 random integers, each within the range of 1 to 9.</li><li>In this particular run, the numbers generated were: [3, 6, 1, 2, 2, 8, 1, 7, 2, 8, 6].</li><li>This line also prints the numbers generated: First numbers: [3 6 1 2 8 1 7 2 8 6].</li></ul><p><strong>2. Number of Workers:</strong></p><ul><li>We define numWorkers := 3, indicating that 3 goroutines (workers) will be used to process the slice in parallel.</li></ul><p><strong>3. Execution Result:</strong></p><ul><li>The code processed the generated slice using the parallel mapping, filtering and reduction functions.</li><li>The final result was 70.</li></ul><h3>Checking the Result</h3><p>Let’s check the result step by step:</p><ol><li><strong>Mapping (Multiplication by 2):</strong></li></ol><ul><li>The numbers [3, 6, 1, 2, 2, 8, 1, 7, 2, 8, 6] are mapped to [6, 12, 2, 4, 16, 2, 14, 4, 16, 12].</li></ul><p><strong>2. Filtering (Greater than 10):</strong></p><ul><li>Numbers greater than 10 are filtered out, leaving [12, 16, 14, 16, 16, 12].</li></ul><p><strong>3. Reduction (Sum):</strong></p><ul><li>The sum of the filtered numbers is 12 + 16 + 14 + 16 + 16 + 12 = 70.</li></ul><p>The result obtained (70) is correct, as it corresponds to the sum of the values that passed the filter after being mapped.</p><h3>Warning about numWorkers</h3><p>When using numWorkers, it is important to choose an appropriate value for the number of workers in relation to the size of the slice. Here are some warnings:</p><ul><li><strong>Too many Workers:</strong> if numWorkers is greater than the number of elements in the slice, some workers will have no work, which could cause parallelism to be inefficient. This can also lead to problems if the code does not handle these cases correctly, as happened in the example above with an incorrect result.</li><li><strong>Too Few Workers: </strong>If the number of workers is too low, parallelism will not be properly exploited, which could cause the program to run slower than if more workers were used.</li></ul><p>In this case, with numWorkers := 3 for a 10-element slice, each worker processes approximately 3-4 elements, which is reasonable and results in correct processing.</p><h3>Conclusion</h3><p>We have explored the fascinating world of parallel computing in Go, focusing on how to take advantage of the language’s features to improve the efficiency and performance of our applications. Through a practical example that performs parallel mapping, filtering and reduction operations, we have seen how goroutines, WaitGroups and Mutexes can be used to handle concurrent tasks and synchronise access to shared resources.</p><h4>How would you improve this code to make it even more efficient or robust?</h4><p>Your perspective can help to further optimise the code and adapt it to new situations.</p><p>I look forward to hearing from you in the comments.</p><p><strong>You may be interested:</strong></p><p><a href="https://medium.com/@matteo.dcj/django-rest-framework-testing-pytest-mocks-coverage-8af023e72ad5">Mastering Testing in Django REST Framework: From Pytest and Fixtures to Mocks and Coverage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c5b3f35a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Testing in Django REST Framework: From Pytest and Fixtures to Mocks and Coverage]]></title>
            <link>https://medium.com/@matteo.dcj/django-rest-framework-testing-pytest-mocks-coverage-8af023e72ad5?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af023e72ad5</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 06:20:10 GMT</pubDate>
            <atom:updated>2024-08-14T06:20:10.291Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Exploring Techniques, Best Practices and Essential Tools for Effective Testing and Quality Assurance of your Django REST Applications</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64f_aQ6RtQV193y9qz0POA.png" /></figure><h3>Introduction</h3><p>In this blog we’ll see a basic guide on how to test a Django project using the Django REST Framework! Here, we’ll learn the basics of testing with pytest, including essential concepts such as fixtures and mocks, to test execution and test coverage with coverage.</p><p>This is the second part of a project we have already done in the blog, in this blog we will do the testing of this project.</p><p><strong>You can see how the code base of the Django project was developed step by step with the Django REST framework here:</strong></p><p><a href="https://medium.com/@matteo.dcj/complete-guide-to-the-django-services-and-repositories-design-pattern-with-the-django-rest-a1ef1ab7d9e7">Complete Guide to the Django Services and Repositories Design Pattern with the Django REST…</a></p><h3>Contents</h3><p>In this guide we will cover:</p><ul><li><strong>Initial Setup:</strong> How to install and configure pytest and other packages needed to test your Django project.</li><li><strong>Fixtures:</strong> How to use fixtures to set up test data and prepare the test environment efficiently.</li><li><strong>Mocks:</strong> How to use pytest-mock to simulate behaviours and conditions in your tests, ensuring that you can test different scenarios without relying on real implementations.</li><li><strong>Model Testing:</strong> We will verify the creation of model instances and their string representations to ensure they work as expected.</li><li><strong>Repository Testing:</strong> We will test the operation of repository methods, including database manipulation and error handling.</li><li><strong>API View Testing:</strong> We will validate that API views respond correctly to HTTP requests and handle data properly.</li><li><strong>Web View Testing:</strong> We will ensure that web views load correctly and display the expected content.</li><li><strong>Code Coverage:</strong> We will run tests and generate coverage reports to identify areas of the code that need further testing.</li><li><strong>Recommendations, Test Types and Best Practices.</strong></li></ul><p>We will look at practical examples of configuring files such as pytest.ini and demonstrate how to run the commands to get detailed coverage reports with coverage.</p><h3>Introduction to Testing with Pytest</h3><p>Testing is a crucial part of software development that ensures the quality, functionality and reliability of code. In the Python ecosystem, pytest is one of the most popular and powerful tools for testing.</p><h4>What is Pytest?</h4><p>pytest is a Python testing framework that makes it easy to write simple, scalable tests. It is known for its simplicity and its ability to adapt to projects of any size. With pytest, you can write unit tests, integration tests, and more, using a clear and concise syntax.</p><h4>Advantages of Using Pytest:</h4><ol><li><strong>Simplicity and Flexibility:</strong>pytest allows you to write tests using simple functions. You don&#39;t need to learn a complex syntax or follow a rigid structure.</li><li><strong>Powerful Fixtures:</strong>pytest provides a fixture system that allows you to configure the state before and after testing, making it easy to create repeatable and isolated test environments (more on fixtures later in the blog).</li><li><strong>Extensible Plugins:</strong>pytest has a lot of plugins that extend its functionality, such as pytest-django for Django projects, pytest-mock for mocks and many more.</li><li><strong>Clear Error Reporting:</strong> Error messages in pytest are detailed and easy to understand, which helps to identify and fix problems quickly.</li><li><strong>Automatic Test Detection:</strong>pytest automatically detects tests in your project without the need to explicitly record them, which simplifies test organisation.</li></ol><h4>Integration with Django</h4><p>pytest integrates easily with Django through the pytest-django plugin. This allows you to efficiently test views, models and other components of a Django project. With pytest-django, you can use Django-specific fixtures, such as the test database, users and more.</p><h3>Initial setup for Testing with Pytest in a Django project with Django REST Framework</h3><p>Before starting to write and run tests with pytest in a Django project, it is essential to properly configure the test environment.</p><h4>Installing the requirements</h4><p>To install the pytest, pytest-django, beautifulsoup4, coverage and pytest-mock dependencies, follow these steps:</p><ul><li><strong>Create a virtual environment (optional but recommended):</strong></li></ul><pre>python -m venv env<br>source env/bin/activate</pre><ul><li><strong>Install the dependencies using pip:</strong></li></ul><pre>pip install pytest pytest-django beautifulsoup4 coverage pytest-mock</pre><p><strong>Little explanation:</strong></p><ul><li><strong>pytest:</strong> The core testing framework.</li><li><strong>pytest-django:</strong> Plugin that makes it easy to integrate pytest with Django.</li><li><strong>beautifulsoup4:</strong> Used to parse and check HTML in view tests.</li><li><strong>coverage:</strong> Tool to measure test coverage, ensuring that all parts of the code are tested.</li><li><strong>pytest-mock:</strong> Plugin to facilitate the creation and use of mocks in tests.</li></ul><h4>Pytest configuration</h4><p>To configure pytest in a Django project, we need to create a pytest.ini file in the root directory of the project. This file will define the specific pytest settings.</p><p>Create a file called pytest.ini in the root directory of your Django project and add the following configuration:</p><pre>[pytest]<br>DJANGO_SETTINGS_MODULE = my_project_blog.settings<br>python_files = tests.py test_*.py *_tests.py</pre><ul><li><strong>DJANGO_SETTINGS_MODULE:</strong> Specifies the Django configuration module that pytest should use.</li><li><strong>python_files:</strong> Defines the filename patterns that pytest will recognise as test files. In this case, pytest will look for files named tests.py, files starting with test_, and files ending in _tests.py.</li></ul><h3>Structure</h3><p>For this project, all the tests of the project will be located in the tests directory which is located in the apps directory. We will follow the following file structure of the tests for better separation of functions and readability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*FATDOk0z2zu9E_Jy.png" /></figure><p>In this blog, we will cover some of the main tests (<em>Note:</em> We will only look at the main tests as the others have a similar structure), but you can find the full test code here:</p><p><a href="https://github.com/MateoRamirezRubio1/mini-blog-rest-api/tree/main/apps/tests">mini-blog-rest-api/apps/tests at main · MateoRamirezRubio1/mini-blog-rest-api</a></p><h3>Definitions before starting (Fixtures)</h3><p>In order to get started with the testing, we will create some Fixtures which we will use in several of the tests later on. To give you some context, let’s quickly look at what a Fixture is in Pytest.</p><h4>What is a Fixture?</h4><p>In the context of testing, a Fixture is a set of data, objects, or configurations that are prepared before running a test.</p><p>Fixtures commonly define the steps and data that constitute the Arrange phase of a test (see the <a href="https://docs.pytest.org/en/stable/explanation/anatomy.html#test-anatomy">anatomy of a test</a>), as well as the Cleanup phase using Python’s yield statement (<a href="https://docs.pytest.org/en/stable/how-to/fixtures.html#yield-fixtures-recommended">see more on this</a>).</p><p>Basically, test functions request the fixtures they need by declaring them as arguments to the test function where they want to use them. So, when pytest is going to run a test, the first thing it does is look at the parameters that this test function has, and then it looks for fixtures that have the same names as those parameters. Once pytest finds them, it executes them, captures what they return (if anything), and passes those objects to the test function as arguments.</p><p>In order for Pytest to know that a function is a Fixture, we must decorate it with @pytest.fixture.</p><h4>What are fixtures used for?</h4><p>Fixtures are widely used for different functions, some of these are:</p><ul><li><strong>Prepare the Test Environment:</strong> Configure the necessary state for testing to be performed under specific conditions. For example, creating objects in the database or initialising configurations.</li><li><strong>Code Reuse:</strong> Allows the same set of data or configurations to be used in multiple tests, avoiding code duplication.</li><li><strong>Test Isolation:</strong> Ensures that each test runs in a clean and consistent environment, avoiding side effects between tests.</li><li><strong>Configuration Automation:</strong> Simplifies the automatic configuration of the test environment, ensuring that tests are set up correctly before execution.</li></ul><h3>Coding Fixtures</h3><p>Already having some knowledge about what fixtures are, for this case, we will create 4 fixtures which we will set in the conftest.py file:</p><ol><li><strong>Fixture post:</strong></li></ol><ul><li><strong>Purpose:</strong> To create an instance of Post that can be used for testing.</li><li><strong>Reason:</strong> To test any functionality that involves the Post model, you need an existing Post object in the database. By using a fixture to create this object, you can ensure that each test has a consistent, well-defined Post to work with.</li><li><strong>Benefit:</strong> Using fixtures avoids duplication of code in every test that needs a Post, ensuring that all tests that depend on a Post use the same data set.</li></ul><pre>@pytest.fixture<br>def post(db):<br>    &quot;&quot;&quot;<br>    Create a Post instance with title and content for testing.<br><br>    Args:<br>        db: The pytest fixture that sets up a test database.<br><br>    Returns:<br>        Post: A Post object with predefined title and content.<br>    &quot;&quot;&quot;<br>    return Post.objects.create(title=&quot;Test Post&quot;, content=&quot;This is a test post&quot;)</pre><p><strong>2. Fixture comment:</strong></p><ul><li><strong>Purpose:</strong> Create an instance of Comment that is associated to a previously created Post.</li><li><strong>Rationale:</strong> Similar to the Post case, if your tests involve the Comment model, you need a Comment object in the database. By associating the Comment with a Post, you can test the comment-related functionality of a specific post.</li><li><strong>Benefit:</strong> By using this fixture, you can test how comments interact with posts without having to manually create a Post in each test. It also ensures that the Comment is correctly linked to a Post.</li></ul><pre>@pytest.fixture<br>def comment(db, post):<br>    &quot;&quot;&quot;<br>    Create a Comment instance associated with the provided Post.<br><br>    Args:<br>        db: The pytest fixture that sets up a test database.<br>        post: The Post fixture providing a Post object.<br><br>    Returns:<br>        Comment: A Comment object linked to the provided Post.<br>    &quot;&quot;&quot;<br>    return Comment.objects.create(content=&quot;This is a test comment&quot;, post=post)</pre><p><strong>3. api_client fixture:</strong></p><ul><li><strong>Purpose:</strong> Provide an instance of APIClient to make HTTP requests to API Endpoints.</li><li><strong>Rationale:</strong> When testing API views and Endpoints, you need a tool to simulate HTTP requests and receive responses. APIClient is ideal for this because it is designed to interact with API Endpoints and verify responses.</li><li><strong>Benefit:</strong> Allows you to test API logic, validations, and responses in a controlled test environment. Ensures that the test client is configured consistently for all API testing.</li></ul><pre>@pytest.fixture<br>def api_client():<br>    &quot;&quot;&quot;<br>    Provide an instance of APIClient for making API requests.<br><br>    Returns:<br>        APIClient: An instance of the APIClient class.<br>    &quot;&quot;&quot;<br>    return APIClient()</pre><p><strong>4. Fixture client:</strong></p><ul><li><strong>Purpose:</strong> Provide an instance of the standard Django test client for making HTTP requests.</li><li><strong>Rationale:</strong> In addition to testing the API, you may need to test HTML-based views. Client allows you to perform these tests by simulating HTTP requests and verifying the responses of template-based views.</li><li><strong>Benefit:</strong> Allows you to test user interaction with the web application, such as page display and form handling, ensuring that the UI part of the application works correctly.</li></ul><pre>@pytest.fixture<br>def client():<br>    &quot;&quot;&quot;<br>    Provide a Django test client instance for making HTTP requests.<br><br>    Returns:<br>        Client: An instance of Django&#39;s test Client class.<br>    &quot;&quot;&quot;<br>    return Client()</pre><h3>Coding the tests</h3><p>Now that we have everything configured, we’ll start testing.</p><p>We’ll do it in blocks, first we’ll test the Django models, then the repositories, the services, the API REST views and finally the web views.</p><h4>Testing the models</h4><p><strong>File:</strong>test_models.py</p><p>The testing of the models will verify the correct creation and representation of the Post and Comment models, ensuring that the data is handled and presented correctly in different situations.</p><ol><li><strong>test_post_creation(post):</strong></li></ol><ul><li><strong>Purpose:</strong> Verifies that a Post object is created correctly with the expected title and content.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses the post fixture, which creates an instance of Post with predefined data.</li><li><strong>Verification:</strong> Ensures that the title and content attributes of the Post object match the expected values (‘Test Post’ and ‘This is a test post’, respectively).</li><li><strong>Why:</strong> Ensures that the creation of Post objects works as expected by ensuring that the attributes are set correctly at creation time.</li></ul><pre>def test_post_creation(post):<br>    &quot;&quot;&quot;<br>    Verify that a Post object is created with the correct title and content.<br><br>    Args:<br>        post: The Post fixture providing a Post object.<br>    &quot;&quot;&quot;<br>    assert post.title == &quot;Test Post&quot;<br>    assert post.content == &quot;This is a test post&quot;</pre><p><strong>2. </strong><strong>test_comment_creation(comment):</strong></p><ul><li><strong>Purpose:</strong> Verifies that a Comment object is correctly created with the expected content and that it is associated with the correct Post.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses the comment fixture, which creates an instance of Comment linked to a specific Post.</li><li><strong>Verification:</strong> Ensures that the content attribute of the Comment object is ‘This is a test comment’ and that the associated Post has the expected title ‘Test Post’.</li><li><strong>Why:</strong> Confirms that the comment is correctly associated with the Post and that the data is stored as expected.</li></ul><pre>def test_comment_creation(comment):<br>    &quot;&quot;&quot;<br>    Verify that a Comment object is created with the correct content and associated Post title.<br><br>    Args:<br>        comment: The Comment fixture providing a Comment object.<br>    &quot;&quot;&quot;<br>    assert comment.content == &quot;This is a test comment&quot;<br>    assert comment.post.title == &quot;Test Post&quot;</pre><p><strong>3. </strong><strong>test_comment_string_representation(comment):</strong></p><ul><li><strong>Purpose:</strong> Verifies that the string representation of a Comment object is correctly truncated to 20 characters.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses the comment fixture, which provides a Comment with specific content.</li><li><strong>Verification:</strong> Checks that the output of str(comment) matches the first 20 characters of the comment content (‘This is a test comment’).</li><li><strong>Why:</strong> Ensures that the ___str___ method of the Comment model behaves correctly, truncating the content to 20 characters as expected, which is useful for displaying a preview of the comment in user interfaces.</li></ul><pre>def test_comment_string_representation(comment):<br>    &quot;&quot;&quot;<br>    Verify that the string representation of a Comment is correctly truncated to 20 characters.<br><br>    Args:<br>        comment: The Comment fixture providing a Comment object.<br>    &quot;&quot;&quot;<br>    strComment = &quot;This is a test comment&quot;<br>    assert str(comment) == strComment[:20]</pre><h4>Testing repositories</h4><p><strong>Files:</strong>test_repositories_comment.py, test_repositories_post.py</p><p>These tests will be in charge of ensuring that the repository methods work correctly both in normal conditions (when data exists) and in error situations (when data does not exist or there are database errors), thus ensuring the reliability of the repository code.</p><ol><li><strong>test_repository_get_comment_by_id_exists(comment):</strong></li></ol><ul><li><strong>Purpose:</strong> Verify that a Comment object can be retrieved by its ID when it exists in the database.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses the comment fixture to provide an existing Comment object.</li><li><strong>Verification:</strong> Uses the get_comment_by_post_and_id method of the CommentRepository to retrieve the comment by post ID and comment ID.</li><li><strong>Asserts:</strong> Checks that the retrieved comment is equal to the Comment object provided by the fixture.</li><li><strong>Why:</strong> Ensures that the repository method works correctly to retrieve existing comments, thus validating the basic functionality of the repository.</li></ul><pre>def test_repository_get_comment_by_id_exists(comment):<br>    &quot;&quot;&quot;<br>    Verify that a Comment can be retrieved by its ID when it exists in the database.<br><br>    Args:<br>        comment: The Comment fixture providing a Comment object.<br><br>    Asserts:<br>        The result should be equal to the provided Comment object.<br>    &quot;&quot;&quot;<br>    result = CommentRepository.get_comment_by_post_and_id(comment.post.id, comment.id)<br>    assert result == comment</pre><p><strong>2. </strong><strong>test_repository_get_comment_by_id_is_does_not_exist():</strong></p><ul><li><strong>Purpose:</strong> Verify that trying to retrieve a Comment by its ID when it does not exist returns None.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Provides a post ID and comment ID that do not exist in the database.</li><li><strong>Verification:</strong> Uses the get_comment_by_post_and_id method of the CommentRepository to try to retrieve the non-existent comment.</li><li><strong>Asserts:</strong> Checks that the result is None.</li><li><strong>Why:</strong> Ensures that the repository method correctly handles cases where the comment does not exist, returning None as expected.</li></ul><pre>@pytest.mark.django_db<br>def test_repository_get_comment_by_id_is_does_not_exist():<br>    &quot;&quot;&quot;<br>    Verify that attempting to retrieve a Comment by ID when it does not exist returns None.<br><br>    Asserts:<br>        The result should be None.<br>    &quot;&quot;&quot;<br>    result = CommentRepository.get_comment_by_post_and_id(232, 9999)  # Non-existent ID<br>    assert result is None</pre><p>(</p><p>Little interlude so we know a bit more about what @pytest.mark.django_db is and why we use it:</p><h4>@pytest.mark.django_db</h4><ul><li><strong>Purpose:</strong> The @pytest.mark.django_db decorator is used to indicate that the test interacts with the Django database.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Some tests need to access or modify the database to verify correct code behaviour.</li><li><strong>Verification:</strong> Without this decorator, tests that attempt to interact with the database would throw an error, as pytest isolates tests from accessing the database by default to improve performance.</li><li><strong>Why:</strong> This decorator is crucial for tests that verify the creation, update, delete or query of objects in the database, ensuring that database operations are performed in a controlled and isolated test environment.</li></ul><p>)</p><p><strong>3. </strong><strong>test_database_error_repository_create_comment(mocker):</strong></p><ul><li><strong>Purpose:</strong> To test whether the create_comment repository method handles database errors (DatabaseError) correctly.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses mocker to patch the Comment.objects.create method and simulate a DatabaseError.</li><li><strong>Verification:</strong> Attempts to create a comment using the create_comment method of the CommentRepository.</li><li><strong>Asserts:</strong> Checks that a DatabaseError is thrown as a result of the simulation.</li><li><strong>Why:</strong> Ensures that the repository handles database errors correctly during comment creation, thus validating the robustness and error handling capability of the repository.</li></ul><pre>def test_database_error_repository_create_comment(mocker):<br>    &quot;&quot;&quot;<br>    Test if the repository method create_comment handles DatabaseError properly.<br><br>    Args:<br>        mocker: The pytest-mock fixture used to patch objects.<br>    <br>    Asserts:<br>        The method should raise a DatabaseError when a DatabaseError is simulated.<br>    &quot;&quot;&quot;<br>    mocker.patch(&#39;apps.comments.repositories.comment_repository.Comment.objects.create&#39;, side_effect=DatabaseError)<br><br>    with pytest.raises(DatabaseError):<br>        CommentRepository.create_comment({}, 1)</pre><p>(</p><p>Little interlude for us to learn a bit about what mocker is and how to use it:</p><h4>Using mocker</h4><ul><li><strong>Purpose:</strong>mocker is a tool provided by pytest-mock that is used to patch methods or functions during testing. This allows to simulate different behaviours and situations of the components under test.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> In tests that verify database error handling, the Comment.objects.create method is patched to simulate a DatabaseError.</li><li><strong>Verification:</strong> By patching this method, the desired behaviour (in this case, throwing a DatabaseError) is forced without the need for the database to actually fail.</li><li><strong>Asserts:</strong> Verifies that the code handles the simulated errors correctly.</li><li><strong>Why:</strong> The use of mocker allows testing how the code handles exceptions and other specific cases without relying on unpredictable external conditions. It is a fundamental technique in unit testing to ensure that the code responds appropriately to different scenarios, including errors.</li></ul><p>)</p><h4>Testing REST API views</h4><p><strong>Files:</strong>test_api_comment.py, test_api_post.py</p><p>These tests will ensure that the REST API views correctly handle the creation and updating of comments and posts, including input validation and error handling.</p><p>This approach will help ensure that the REST API views are robust and handle different usage scenarios correctly, improving the quality and reliability of the code.</p><ol><li><strong>test_create_comment(api_client, post):</strong></li></ol><ul><li><strong>Purpose:</strong> Verify that a new Comment can be created for a Post via the API.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Uses the api_client fixture to make API requests and the post fixture to provide a Post object.</li><li><strong>Action:</strong> Makes a POST request to the post-comment-create URL with the data needed to create a new comment.</li><li><strong>Asserts:</strong></li><li>Verifies that the response status is HTTP 201 Created.</li><li>Verifies that the response data includes the content of the new comment.</li><li><strong>Why:</strong> Ensures that the API handles the creation of new comments correctly by validating the resource creation functionality.</li></ul><pre>def test_create_comment(api_client, post):<br>    &quot;&quot;&quot;<br>    Verify that a new Comment can be created for a Post via the API.<br><br>    Args:<br>        api_client: The APIClient fixture for making API requests.<br>        post: The Post fixture providing a Post object.<br><br>    Asserts:<br>        The response status should be HTTP 201 Created.<br>        The response data should include the content of the new Comment.<br>    &quot;&quot;&quot;<br>    response = api_client.post(<br>        reverse(&quot;post-comment-create&quot;, args=[post.id]),<br>        {&quot;post&quot;: post.id, &quot;content&quot;: &quot;New comment&quot;},<br>        format=&quot;json&quot;,<br>    )<br><br>    assert response.status_code == status.HTTP_201_CREATED<br>    assert response.data[&quot;content&quot;] == &quot;New comment&quot;</pre><p><strong>2. </strong><strong>test_perform_update_raises_kwargs_does_not_exists():</strong></p><ul><li><strong>Purpose:</strong> Verify that perform_update throws an APIException if comment_pk is not present in kwargs.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Creates an instance of CommentRetrieveUpdateDestroyAPIView and sets kwargs to an empty dictionary.</li><li><strong>Action:</strong> Attempts to execute perform_update without providing comment_pk.</li><li><strong>Asserts:</strong></li><li>Verifies that an APIException is thrown.</li><li>Verifies that the exception message is ‘Comment ID is required to update the comment.’</li><li><strong>Why:</strong> Ensures that the view correctly handles cases where the required arguments are not present, providing proper validation and error handling.</li></ul><pre>def test_perform_update_raises_kwargs_does_not_exists():<br>    &quot;&quot;&quot;<br>    Verify that perform_update raises an APIException if &#39;comment_pk&#39; is not provided in kwargs.<br>    <br>    Asserts:<br>        The exception message should be &quot;Comment ID is required to update the comment.&quot;<br>    &quot;&quot;&quot;<br>    view = CommentRetrieveUpdateDestroyAPIView()<br>    view.kwargs = {}<br><br>    try:<br>        view.perform_update({})<br>    except APIException as exc:<br>        assert str(exc) == &quot;Comment ID is required to update the comment.&quot;</pre><p><strong>3. </strong><strong>test_perform_update_invalid_comment_id():</strong></p><ul><li><strong>Purpose:</strong> Verify that perform_update throws an APIException if comment_pk has an invalid format.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong> Creates an instance of CommentRetrieveUpdateDestroyAPIView and sets kwargs with comment_pk as an invalid value.</li><li><strong>Action:</strong> Uses a MockSerializer to simulate a validated serializer and then attempts to execute perform_update.</li><li><strong>Asserts:</strong></li><li>Verifies that an APIException is thrown.</li><li>Verifies that the exception message is ‘Invalid Comment ID format.’</li><li><strong>Why:</strong> Ensures that the view correctly handles cases where arguments have an invalid format, thus validating the robustness of error handling and data validation.</li></ul><pre>class MockSerializer(Serializer):<br>    &quot;&quot;&quot;<br>    Mock serializer class to simulate serializer behavior in tests.<br>    &quot;&quot;&quot;<br>    validated_data = {&quot;content&quot;: &quot;Test comment&quot;}<br><br>def test_perform_update_invalid_comment_id():<br>    &quot;&quot;&quot;<br>    Verify that perform_update raises an APIException if &#39;comment_pk&#39; has an invalid format.<br>    <br>    Asserts:<br>        The exception message should be &quot;Invalid Comment ID format.&quot;<br>    &quot;&quot;&quot;<br>    view = CommentRetrieveUpdateDestroyAPIView()<br>    view.kwargs = {&quot;comment_pk&quot;: &quot;invalid&quot;}<br><br>    serializer = MockSerializer(data={&quot;content&quot;: &quot;Test comment&quot;})<br>    serializer.is_valid()  # Simulate successful serializer validation<br><br>    with pytest.raises(APIException) as excinfo:<br>        view.perform_update(serializer)<br>    assert str(excinfo.value) == &quot;Invalid Comment ID format.&quot;</pre><h4>Testing web views</h4><p><strong>Files:</strong>test_web_views_comment.py, test_web_views_post.py</p><p>These tests will verify that the ‘Post’ and ‘Comment’ web views are working correctly. Helping to ensure that users can see the details and lists of ‘Posts’ and ‘Comments’ as expected in the web interface, improving the quality and reliability of the application.</p><ol><li><strong>test_post_detail_view(client, post):</strong></li></ol><ul><li><strong>Purpose:</strong> Verify that the detail view of a Post returns a successful response and that it includes the title of the specific Post.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong></li><li>client<strong>:</strong> Uses Django’s client fixture to make HTTP requests.</li><li>post<strong>:</strong> Use the post fixture to provide a Post object.</li><li><strong>Action:</strong> Make a GET request to the Post’s detail URL using reverse to resolve to the correct URL and pass the Post ID.</li><li><strong>Asserts:</strong></li><li>Verifies that the status of the response is HTTP 200 OK.</li><li>Verifies that the content of the response includes the Post title in binary format (b ‘Test Post’).</li><li><strong>Why:</strong> This test ensures that the Post detail view works correctly and that the Post title is displayed as expected, validating both functionality and data representation.</li></ul><pre>def test_post_detail_view(client, post):<br>    &quot;&quot;&quot;<br>    Verify that the Post detail view returns a successful response and includes the title of the specific Post.<br><br>    Args:<br>        client: The Django test client fixture for making HTTP requests.<br>        post: The Post fixture providing a Post object.<br><br>    Asserts:<br>        The response status should be HTTP 200 OK.<br>        The response content should include the title of the Post.<br>    &quot;&quot;&quot;<br>    response = client.get(reverse(&quot;post-detail&quot;, args=[post.id]))<br>    assert response.status_code == 200<br>    assert b&quot;Test Post&quot; in response.content</pre><p><strong>2. </strong><strong>test_comment_detail_view(client, comment):</strong></p><ul><li><strong>Purpose:</strong> Verify that the detail view of a Comment returns a successful response and that it includes the content of the specific Comment.</li></ul><p><strong>Rationale:</strong></p><ul><li><strong>Input:</strong></li><li>client<strong>:</strong> Uses Django&#39;s client fixture to make HTTP requests.</li><li>comment<strong>:</strong> Uses the comment fixture to provide a Comment object.</li><li><strong>Action:</strong> Make a GET request to the Comment’s detail URL using reverse to resolve to the correct URL and pass the Post and Comment IDs.</li><li><strong>Asserts:</strong></li><li>Verify that the status of the response is HTTP 200 OK.</li><li>Uses BeautifulSoup to parse the HTML content of the response and extract all elements.</li><li>Verifies that the content of the elements includes the text of the specific comment.</li><li><strong>Why:</strong> This test ensures that the Comment detail view works correctly and that the Comment content is displayed as expected, validating both functionality and data representation.</li></ul><pre>def test_comment_detail_view(client, comment):<br>    &quot;&quot;&quot;<br>    Verify that the Comment detail view returns a successful response and includes the content of a specific Comment.<br><br>    Args:<br>        client: The Django test client fixture for making HTTP requests.<br>        comment: The Comment fixture providing a Comment object.<br><br>    Asserts:<br>        The response status should be HTTP 200 OK.<br>        The response content should include the text of the Comment.<br>    &quot;&quot;&quot;<br>    response = client.get(<br>        reverse(&quot;post-comment-detail&quot;, args=[comment.post.id, comment.id])<br>    )<br>    assert response.status_code == 200<br><br>    soup = BeautifulSoup(response.content, &quot;html.parser&quot;)<br>    comments = soup.find_all(&quot;p&quot;)<br>    comment_texts = [comment.get_text() for comment in comments]<br>    assert &quot;This is a test comment&quot; in comment_texts</pre><h3>Using Coverage with Pytest in our Django project</h3><p>Coverage is an essential tool for measuring test coverage in a project. It allows us to see which parts of the code are being tested and which are not, helping to identify areas that need more testing. In this section, we will look at two key commands for using coverage in conjunction with pytest.</p><h4>Command 1: python -m coverage run -m pytest:</h4><pre>python -m coverage run -m pytest</pre><ul><li><strong>python -m coverage:</strong> This command runs the coverage module as a script. Using -m instead of just coverage ensures that the version of coverage installed in the current virtual environment is used.</li><li><strong>run:</strong> This subcommand of coverage indicates that we want to run a script (in this case, pytest) and measure the coverage while it is running.</li><li><strong>-m pytest:</strong> This part of the command tells Python to execute the pytest module. This way, coverage will run pytest and record code coverage during test execution.</li></ul><p>This command runs all tests using pytest and, at the same time, records the code coverage, generating a .coverage file in the root directory of the project containing the coverage data.</p><h4>Command 2: python -m coverage report --include=‘apps/’ --show-missing:</h4><pre>python -m coverage report --include=&quot;apps/*&quot; --show-missing</pre><ul><li><strong>python -m coverage:</strong> As in the previous command, executes the module coverage.</li><li><strong>report:</strong> This coverage subcommand generates a coverage report on the terminal.</li><li><strong>— include=‘apps/*’:</strong> This argument indicates that we only want to include files in the apps folder in the coverage report. You can adjust this path according to the structure of your projects and the scope you want to give to your test coverage. This is useful to exclude files you are not interested in, such as configuration files or third-party libraries.</li><li><strong>— show-missing:</strong> This argument adds a column to the report that shows which lines of each file were not covered by the tests. This makes it easier to identify specific areas of code that need further testing.</li></ul><h3>Running the tests with Coverage and Pytest</h3><h4>First command:</h4><p>The command python -m coverage run -m pytest runs the tests using pytest and also measures the coverage of the code.</p><p>If you run the command, you should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MH_xEiYoBz8dYumX.png" /></figure><p><strong>Collection analysis and execution of tests:</strong></p><ul><li><strong>Total tests collected:</strong> 44.</li><li><strong>Results:</strong></li><li>All tests (44) passed successfully.</li><li>The total execution time was 0.83s.</li></ul><p><strong>Explanation:</strong></p><p>This result shows that all the tests that we defined so far in the project were executed correctly and passed. There were no failures, bugs or skipped tests, which indicates that the code under test behaves as expected in all cases covered by the tests.</p><h4>Second command:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3LCphJVylv516v46.png" /></figure><p><strong>Code Coverage Report Explanation:</strong></p><p>After running the command to generate the code coverage report, we will get a detailed breakdown of how the tests cover the source code as we can see in the image above.</p><p>Let’s take a closer look at what all this data means:</p><p><strong>Sections of the Report</strong></p><ol><li><strong>Name:</strong></li></ol><ul><li>This column shows the path to each file in the project that contains executable code.</li><li><strong>For example</strong>, apps\comments\models.py refers to the models.py file in the comments app.</li></ul><p><strong>2. Stmts:</strong></p><ul><li>This column indicates the total number of statements (lines of executable code) in each file.</li><li><strong>For example</strong>, apps\comments\models.py has 9 statements.</li></ul><p><strong>3. Miss:</strong></p><ul><li>This column shows how many statements in the file were not executed during testing.</li><li><strong>For example</strong>, if apps\posts\views\web_views.py has 4 lines not covered, it means that 4 lines of code in that file were not executed by the tests.</li></ul><p><strong>4. Cover:</strong></p><ul><li>This column shows the percentage of coverage for each file. It represents the percentage of lines of code executed during testing.</li><li><strong>For example</strong>, apps\posts\views\api_views.py has a coverage of 71%, which means that 71% of its lines of code were executed during the tests.</li></ul><p><strong>5. Missing:</strong></p><ul><li>This column lists the specific lines that were not covered by the tests.</li><li><strong>For example</strong>, apps\comments\views\web_views.py shows 21, 24-25, 54, 58, 60-63, indicating that these lines were not executed.</li></ul><p><strong>Meaning and Measurements</strong></p><ol><li><strong>Lines Not Covered (Miss):</strong></li></ol><ul><li><strong>Meaning:</strong> The lines of code listed in this column were not executed during testing. This could be because certain paths in the code are not being tested.</li><li><strong>Action:</strong> Add tests to cover these paths. For example, if there is error handling on these lines, make sure your tests include cases that trigger those errors.</li></ul><p><strong>2. Low Cover (Cover):</strong></p><ul><li><strong>Meaning:</strong> A low percentage indicates that a large part of the code in that file is not being tested.</li><li><strong>Action:</strong> Review files with low coverage and add tests to cover more use cases. This may include additional unit tests or functional tests that exercise more code paths.</li></ul><p><strong>3. Full Coverage (100% Cover):</strong></p><ul><li><strong>Meaning:</strong> All statements in these files were executed during testing.</li><li><strong>Measurement:</strong> Although the coverage is 100%, make sure that the tests also correctly verify the logic of the code, not just that it executes.</li></ul><h3>Recommendations and Best Practices</h3><p>Finally, we will look at some recommendations, types of tests and best practices for effective application testing, especially in the context of applications such as this one.</p><ol><li><strong>Types of Tests</strong></li></ol><p>To achieve complete and effective coverage, consider implementing the following types of tests:</p><ul><li><strong>Unit Tests:</strong> Verify the operation of individual pieces of code, such as functions, methods or classes. Make sure that each unit of code does what is expected without relying on other parts of the system.</li><li><strong>Integration Tests:</strong> Validate how different components of the system interact. In the Django REST Framework, this may include testing that API endpoints work correctly and that data is handled properly between views and models.</li><li><strong>Functionality Testing:</strong> This focuses on the full functionality of the system from the user’s point of view. For example, make sure that users can create, read, update and delete resources correctly through the API.</li><li><strong>Regression Testing:</strong> Ensures that code changes do not break existing functionality. They should be run regularly to detect problems introduced by new features or bug fixes.</li><li><strong>Performance Testing:</strong> Verify the behaviour of the application under load and stress conditions. It is useful to identify bottlenecks and ensure that the application can handle the expected traffic.</li></ul><p><strong>2. Best Practices</strong></p><p>To ensure that your testing is effective and reliable, consider the following practices:</p><ul><li><strong>Code Coverage:</strong> Although not a guarantee of quality, high code coverage (ideally over 80%) helps identify untested areas. Use tools such as coverage.py to measure and improve coverage.</li><li><strong>Test Independence:</strong> Each test should be independent and run in any order. Use fixtures to set the initial state and clean up after each test if necessary.</li><li><strong>Use of Mocks and Stubs:</strong> For unit tests, use mocks to simulate external behaviours and dependencies. This ensures that tests are fast and do not depend on external services or shared state.</li><li><strong>Error and Exception Testing:</strong> Be sure to test cases where the application must handle errors and exceptions. Verify that errors are handled properly and that useful messages are returned to the user.</li><li><strong>Security Testing:</strong> Include tests that verify the security of your application, such as permission validation and protection against common vulnerabilities (e.g., SQL injection, Cross-Site Scripting).</li><li><strong>Testing in Real Environments:</strong> Run your tests in environments that mimic the production environment as closely as possible to detect problems that only occur in specific configurations.</li></ul><p><strong>3. Additional Recommendations</strong></p><ul><li><strong>Keep Tests Readable and Maintainable:</strong> Write tests that are clear and easy to understand. Use descriptive test names and keep test code clean and well organised.</li><li><strong>Automate Test Execution:</strong> Integrate your tests into the continuous integration (CI) process so that they run automatically on every code change. This helps identify problems quickly and ensures that new code does not break existing functionality.</li><li><strong>Review and Refactor:</strong> Regularly review and refactor your tests to improve their coverage and efficiency. Test code can also become obsolete over time, so keep it up to date.</li></ul><p>And that’s it for our basic guide to testing in a Django REST Framework project!</p><p>Remember that testing is a crucial part of software development, and maintaining good coverage and well-defined tests will help you prevent bugs and improve the quality of your code over time.</p><p>If you have additional questions, feel free to leave them in the comments.</p><p>Thanks for reading and happy code testing!</p><p><strong>Other topics you may be interested in:</strong></p><ul><li><a href="https://medium.com/@matteo.dcj/how-to-name-endpoints-urls-in-a-rest-api-complete-guide-with-best-practices-and-practical-example-7e2dbab5f1cd">How to Name Endpoints/URLs in a REST API: Complete Guide with Best Practices and Practical Example</a></li><li><a href="https://medium.com/@matteo.dcj/using-environment-variables-with-flutter-dotenv-and-dotenv-in-flutter-step-by-step-guide-709ac93e8ec2">Using Environment Variables with flutter_dotenv and DotEnv in Flutter: Step by Step Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af023e72ad5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Environment Variables with flutter_dotenv and DotEnv in Flutter: Step by Step Guide]]></title>
            <link>https://medium.com/@matteo.dcj/using-environment-variables-with-flutter-dotenv-and-dotenv-in-flutter-step-by-step-guide-709ac93e8ec2?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/709ac93e8ec2</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dotenv]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 05:02:09 GMT</pubDate>
            <atom:updated>2024-08-06T05:02:09.035Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Load and access your environment variables securely and efficiently in your Flutter applications.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D808%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Ddependencies%25253A%25250A%252520%252520flutter_dotenv%25253A%252520%25255E5.1.0%25250A%25250Aflutter%25253A%25250A%252520%252520assets%25253A%25250A%252520%252520%252520%252520-%252520.env&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dyaml%26width%3D808%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D4x%26wm%3Dfalse%26code%3Ddependencies%2525253A%2525250A%25252520%25252520flutter_dotenv%2525253A%25252520%2525255E5.1.0%2525250A%2525250Aflutter%2525253A%2525250A%25252520%25252520assets%2525253A%2525250A%25252520%25252520%25252520%25252520-%25252520.env&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9496e00b5bf36f1c2d8ca37629222b5/href">https://medium.com/media/e9496e00b5bf36f1c2d8ca37629222b5/href</a></iframe><h3>Introduction</h3><p>When building Flutter applications, it’s essential to manage sensitive data like API keys, database credentials, or environment-specific configurations. Hardcoding these values directly in your code is a security risk and can lead to issues when deploying your app to different environments.</p><p>That’s where .env variables come in – a simple and effective way to store and manage environment-specific configurations. In this blog, we’ll explore how to use .env files to manage environment variables in your Flutter app, with a step-by-step guide and a practical example.</p><h3>Some concepts</h3><h4>What Are .env Files?</h4><p>.env files are simple text files used to store environment-specific variables. They typically contain key-value pairs, like API keys or base URLs, which can be accessed throughout your application.</p><h4>Why Use .env Files?</h4><ul><li><strong>Separation of Concerns:</strong> Keep configuration settings separate from your code.</li><li><strong>Security:</strong> Store sensitive information like API keys securely.</li><li><strong>Flexibility:</strong> Easily switch between different environments (development, staging, production).</li></ul><h3>Step-by-Step Guide</h3><h4>Prerequisites</h4><p>Before we begin, ensure you have the following:</p><ul><li>A Flutter project set up.</li></ul><h4>Step 1: Add the dotenv package</h4><p>First, add the dotenv package to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter_dotenv: ^5.1.0</pre><h4>Step 2: Create a .env File</h4><p>Create a .env file in the root directory of your Flutter project. This file will store your environment variables.</p><pre>API_KEY=your_api_key_here<br>BASE_URL=https://example.com</pre><h4>Step 3: Update pubspec.yaml</h4><p>Ensure that the .env file is included as an asset in your project. Modify your pubspec.yaml file to include the .env file:</p><pre>flutter:<br>  assets:<br>    - .env</pre><p><strong>Important:</strong> Run flutter pub get to apply the changes.</p><h4>Step 4: Load the .env File</h4><p>In your main.dart file, import flutter_dotenv and load the .env file before running the app:</p><pre>import &#39;package:flutter_dotenv/flutter_dotenv.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized(); // Ensure Flutter is initialized<br>  try {<br>    await dotenv.load(fileName: &quot;.env&quot;); // Load environment variables<br>  } catch (e) {<br>    throw Exception(&#39;Error loading .env file: $e&#39;); // Print error if any<br>  }<br>  runApp(const MainApp()); // Runs the app<br>}</pre><ol><li><strong>Ensure Flutter is initialized:</strong> WidgetsFlutterBinding.ensureInitialized() ensures that Flutter&#39;s framework is initialized before loading the .env file. This is important because dotenv.load() relies on Flutter&#39;s file system to read the .env file.</li><li><strong>Load environment variables:</strong> await dotenv.load(fileName: &quot;.env&quot;) loads the environment variables from the .env file. The await keyword ensures that the loading process is completed before proceeding.</li><li><strong>Error handling:</strong> The try-catch block catches any errors that might occur while loading the .env file. If an error occurs, it throws an exception with a meaningful error message.</li><li><strong>Run the app:</strong> Finally, runApp(const MainApp()) runs the app.</li></ol><h4>Step 5: Access Environment Variables</h4><p>You can access the environment variables using dotenv.env:</p><pre>import &#39;package:flutter_dotenv/flutter_dotenv.dart&#39;;<br><br>class ApiService {<br>  final String baseUrl = dotenv.env[&#39;BASE_URL&#39;] ?? &#39;default_url&#39;;<br>  final String apiKey = dotenv.env[&#39;API_KEY&#39;] ?? &#39;default_key&#39;;<br><br>  // Use baseUrl and apiKey in your API calls<br>}</pre><h3>Troubleshooting</h3><h4>Common Issues:</h4><ol><li><strong>File Not Found:</strong> Ensure the .env file is in the root directory and correctly specified in pubspec.yaml.</li><li><strong>File Not Loading:</strong> Confirm that await dotenv.load() is called before running the app.</li></ol><p><strong><em>Note:</em></strong> Remember to add your .env file to your .gitignore file to avoid committing sensitive data to your version control system.</p><p>By following these steps and using flutter_dotenv in your Flutter app, you&#39;ll be able to manage your environment-specific configurations securely and efficiently.</p><p>I hope this helps! Let me know if you have any questions.</p><p><strong>Aditional Resources:</strong></p><ul><li><a href="https://pub.dev/packages/flutter_dotenv">Flutter Dotenv documentation.</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*2tYKLNOwlehtSObE3FnDFw.png" /></figure><p><strong>Topics you may be interested in:</strong></p><ul><li><a href="https://medium.com/@matteo.dcj/complete-guide-to-the-django-services-and-repositories-design-pattern-with-the-django-rest-a1ef1ab7d9e7">Complete Guide to the Django Services and Repositories Design Pattern with the Django REST…</a></li><li><a href="https://medium.com/@matteo.dcj/how-to-name-endpoints-urls-in-a-rest-api-complete-guide-with-best-practices-and-practical-example-7e2dbab5f1cd">How to Name Endpoints/URLs in a REST API: Complete Guide with Best Practices and Practical Example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709ac93e8ec2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to the Django Services and Repositories Design Pattern with the Django REST…]]></title>
            <link>https://medium.com/@matteo.dcj/complete-guide-to-the-django-services-and-repositories-design-pattern-with-the-django-rest-a1ef1ab7d9e7?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1ef1ab7d9e7</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 00:27:57 GMT</pubDate>
            <atom:updated>2024-08-06T00:27:57.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Guide to the Django Services and Repositories Design Pattern with the Django REST Framework</h3><blockquote>How to Structure and Maintain Your Web Application Efficiently and Scalably using RESTful APIs and Best Practices</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*y3Op_lgozLbtwJ5iqL0tew.png" /></figure><h3>Table of contents</h3><ul><li><strong>Introduction to the Django Services and Repositories Design Pattern with Django REST Framework</strong></li></ul><ol><li><strong>Creation and design of the project</strong></li></ol><ul><li><strong>Start and creation of the Django project</strong></li><li><strong>Creation of Django applications</strong></li><li><strong>File settings</strong></li><li><strong>Project structure</strong></li><li><strong>System design</strong></li><li><strong>Design of REST APIs</strong></li></ul><p><strong>2. Coding and deepening</strong></p><ul><li><strong>Model</strong></li><li><strong>Views</strong></li><li><strong>Repositories</strong></li><li><strong>Services</strong></li><li><strong>Serializers</strong></li><li><strong>Configuration of URLs</strong></li></ul><p><strong>3. Web application and API testing</strong></p><ul><li><strong>Execute the project</strong></li><li><strong>Add comments to posts</strong></li><li><strong>Verify the creation of posts and comments</strong></li></ul><p><strong>4. Conclusions</strong></p><ul><li><strong>Benefits of the Services and Repositories Pattern</strong></li></ul><h3>Introduction to the Django Services and Repositories Design Pattern with Django REST Framework</h3><p>In the world of software development, code organisation and maintainability are crucial to the long-term success of any project. In particular, when working with frameworks like Django and the Django REST Framework to build robust web applications and APIs, it’s essential to follow design patterns that help us keep our code clean, modular and easy to scale.</p><p>In this blog, we will explore one of these widely used design patterns: Services and Repositories. This pattern allows us to separate the concerns of data access and business logic, improving the structure and clarity of our code. Through this approach, we not only make our applications easier to maintain and test, but also more flexible and future-proof.</p><p>Join us as we break down this pattern step-by-step, from initial project setup to service and repository deployment, and discover how it can transform the way you develop your Django apps.</p><p>The realisation of the project is divided into three main sections: the structuring and design of the project; the coding of the structured project; testing.</p><p><strong>You can find the complete code and structure of the project in the following GitHub link:</strong></p><p><a href="https://github.com/MateoRamirezRubio1/mini-blog-rest-api">GitHub - MateoRamirezRubio1/mini-blog-rest-api: A mini blog Django project demonstrating the implementation of the Services and Repositories design pattern for a blog application.</a></p><h3>Creation and design of the project</h3><p>In this first section, we will see how to create a new Django project with DRF (Django REST Framework) and we will analyse how the main parts of the project and REST APIs will be structured.</p><h4>1. Start and creation of the Django project</h4><p>Before starting the project, you must install Django and Django REST Framework if you don’t already have it:</p><pre> pip install django djangorestframework</pre><p>Now that we’ve installed the main tools we’re going to use for the project, we’ll create a new Django project using the django-admin startproject command:</p><pre> django-admin startproject my_project_blog</pre><p>This command generates the basic structure of a Django project, including configuration files and a project directory.</p><h4>2. Creation of Django applications</h4><p>For this small blog project, we will have two main functionalities which we will divide into two Django apps: Posts and Comments.</p><p>For this, in the terminal, inside the main project directory (my_project_blog), create two applications: Posts and Comments using the python command manage.py startapp:</p><pre> python manage.py startapp posts<br> python manage.py startapp comments</pre><p>Apps are modular Django components that group related functionalities. In this case, Posts will handle blog posts and Comments will handle comments.</p><h4><strong>3. File settings</strong></h4><p>Add the created apps and the DRF to the INSTALLED_APPS section in the project settings file: /my_project_blog/my_project_blog/settings.py :</p><pre>INSTALLED_APPS = [<br>    &quot;rest_framework&quot;,<br>    &quot;apps.posts&quot;,<br>    &quot;apps.comments&quot;,<br>...</pre><h4>4. Project structure</h4><p>Next I will show you how the project will be structured, you can create all the directories/folders and files (ignore README.md, .env, .gitignore), and then we will fill them with code as we learn.</p><ul><li><strong>Main structure:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*-Ml5fy_6ykeepkaB" /></figure><ul><li><strong>Structure of the Comments app:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*ZERQl4_Cqqkqoxsx" /></figure><ul><li><strong>Structure of the Posts app:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/0*dC1uVTdFZVQT2TJA" /></figure><h4>5. System design</h4><p>For the realisation of the project we opted for an architecture based on layers and classic design patterns such as Repository and Services.</p><p>The Services and Repositories pattern divides business logic (services) and data access logic (repositories) into separate layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*tR5qvruRJ-j6N9CLN7TW4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/0*scgjZGZROh4S5ap2" /></figure><p>We will delve a little deeper into each layer later as we code.</p><h4>6. Design of REST APIs</h4><p>REST APIs allow communication between the frontend and the backend. We use the Django REST Framework to create RESTful APIs. This is the structure we have for their respective naming and functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*CiwDWP9vWXGdXYdB5K9fFg.png" /></figure><p><strong>You can learn more about naming your REST Endpoints here:</strong></p><p><a href="https://medium.com/@matteo.dcj/how-to-name-endpoints-urls-in-a-rest-api-complete-guide-with-best-practices-and-practical-example-7e2dbab5f1cd">How to Name Endpoints/URLs in a REST API: Complete Guide with Best Practices and Practical Example</a></p><h3>Coding and deepening</h3><p>Now that we are clear about the layout of the project, for the second section, we will code our blogging project by delving into several of the layers we talked about earlier.</p><h4>1. Model</h4><p>The Model represents the data. It defines the database tables. In Django, models are classes that inherit from models.Model.</p><p>For this project we will create two models, one for each Django app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*v1WsDwO53u1dfHlGRC1sJg.png" /></figure><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/models.py :</li></ul><pre>class Post(models.Model):<br>    title = models.CharField(max_length=200)<br>    content = models.TextField()<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.title</pre><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/models.py :</li></ul><pre>from apps.posts.models import Post<br><br><br>class Comment(models.Model):<br>    post = models.ForeignKey(Post, related_name=&quot;comments&quot;, on_delete=models.CASCADE)<br>    content = models.TextField()<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.content[:20]</pre><h4>2. Views</h4><p>The View handles user requests and returns responses. Django offers both class-based views (CBV) and function-based views (FBV).</p><p>CommentListView and CommentDetailView are examples of Class-Based Views (CBV).</p><p>Separation of concerns is a design principle that promotes the separation of a program into distinct sections, with each section addressing a separate concern.</p><p>As we saw earlier for this project, we separated the views into two:</p><ul><li><strong>API REST Views:</strong> Handle API-specific logic, such as serialisation, validation and returning JSON responses.</li><li><strong>Traditional Django Views (Web Views):</strong> They handle rendering templates, session management and other web-specific logic.</li></ul><p><strong>For the Posts app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/views/api_views.py :</li></ul><pre>from rest_framework import generics<br>from ..serializers import PostSerializer<br>from ..services.post_service import PostService<br>from rest_framework.exceptions import NotFound, ValidationError<br>from django.core.exceptions import ObjectDoesNotExist<br><br><br>class PostListCreateAPIView(generics.ListCreateAPIView):<br>    &quot;&quot;&quot;<br>    API view for listing all posts and creating a new post.<br>    Utilizes Django REST Framework&#39;s ListCreateAPIView for listing and creating resources.<br>    &quot;&quot;&quot;<br>    serializer_class = PostSerializer  # Defines the serializer class used for converting model instances to JSON and vice versa.<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Fetch all posts from the database.<br>        `get_queryset` method specifies the queryset for listing posts.<br><br>        :return: QuerySet of all Post objects.<br>        &quot;&quot;&quot;<br>        return PostService.get_all_posts()  # Delegates the database query to the PostService layer.<br><br>    def perform_create(self, serializer):<br>        &quot;&quot;&quot;<br>        Handle the creation of a new post.<br>        `perform_create` is called after validation of the serializer.<br><br>        :param serializer: Validated serializer containing data for creating a new post.<br>        :raises ValidationError: If the creation of the post fails.<br>        &quot;&quot;&quot;<br>        try:<br>            PostService.create_post(serializer.validated_data)  # Use PostService to handle creation logic.<br>        except ValidationError as e:<br>            raise ValidationError({&quot;detail&quot;: str(e)})<br><br><br>class PostRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):<br>    &quot;&quot;&quot;<br>    API view for retrieving, updating, and deleting a specific post.<br>    Extends RetrieveUpdateDestroyAPIView for detailed operations on a single resource.<br>    &quot;&quot;&quot;<br>    serializer_class = PostSerializer  # Specifies the serializer class for retrieving, updating, and deleting resources.<br><br>    def get_object(self):<br>        &quot;&quot;&quot;<br>        Retrieve a post object based on the provided post_id.<br>        `get_object` method returns the post instance for the specified post_id.<br><br>        :return: Post object if found.<br>        :raises NotFound: If the post does not exist.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)  # Extract post_id from the URL kwargs.<br>        try:<br>            post = PostService.get_post_by_id(post_id)  # Fetch the post using PostService.<br>            return post<br>        except ObjectDoesNotExist:<br>            raise NotFound(&quot;Post not found&quot;)  # Raise a 404 error if the post does not exist.<br>        except ValidationError as e:<br>            raise NotFound({&quot;detail&quot;: str(e)})<br><br>    def perform_update(self, serializer):<br>        &quot;&quot;&quot;<br>        Update an existing post instance.<br>        `perform_update` is called after the serializer&#39;s data is validated.<br><br>        :param serializer: Validated serializer containing data for updating the post.<br>        :raises ValidationError: If the update fails.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs[&quot;post_id&quot;]  # Extract post_id from the URL kwargs.<br>        try:<br>            PostService.update_post(serializer.validated_data, post_id)  # Delegate the update logic to PostService.<br>        except ObjectDoesNotExist:<br>            raise NotFound(&quot;Post not found&quot;)<br>        except ValidationError as e:<br>            raise ValidationError({&quot;detail&quot;: str(e)})<br><br>    def perform_destroy(self, instance):<br>        &quot;&quot;&quot;<br>        Delete a post instance.<br>        `perform_destroy` is called to delete the specified post.<br><br>        :param instance: The post instance to delete.<br>        :raises NotFound: If the post does not exist.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs[&quot;post_id&quot;]  # Extract post_id from the URL kwargs.<br>        try:<br>            PostService.delete_post(post_id)  # Delegate the deletion logic to PostService.<br>        except ObjectDoesNotExist:<br>            raise NotFound(&quot;Post not found&quot;)<br>        except ValidationError as e:<br>            raise ValidationError({&quot;detail&quot;: str(e)})</pre><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/views/web_views.py :</li></ul><pre>from django.views.generic import ListView, DetailView<br>from django.http import Http404<br>from ..models import Post<br>from ..services.post_service import PostService<br>from django.core.exceptions import ValidationError<br><br>class PostListView(ListView):<br>    &quot;&quot;&quot;<br>    Class-based view for listing all posts in the web interface.<br>    Utilizes Django&#39;s ListView to handle displaying a list of posts.<br>    &quot;&quot;&quot;<br>    model = Post  # Specifies the model to be used in the view.<br>    template_name = &quot;posts/post_list.html&quot;  # Path to the template for rendering the list of posts.<br>    context_object_name = &quot;posts&quot;  # Context variable name to be used in the template.<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Overrides the default get_queryset method to fetch all posts from the service layer.<br><br>        :return: QuerySet of all Post objects.<br>        &quot;&quot;&quot;<br>        return PostService.get_all_posts()  # Delegates the database query to the PostService.<br><br><br>class PostDetailView(DetailView):<br>    &quot;&quot;&quot;<br>    Class-based view for displaying the details of a single post.<br>    Utilizes Django&#39;s DetailView to handle displaying detailed information of a single post.<br>    &quot;&quot;&quot;<br>    model = Post<br>    template_name = &quot;posts/post_detail.html&quot;  # Path to the template for rendering post details.<br>    context_object_name = &quot;post&quot;  # Context variable name to be used in the template.<br><br>    def get_object(self, queryset=None):<br>        &quot;&quot;&quot;<br>        Overrides the default get_object method to fetch a specific post based on post_id.<br><br>        :param queryset: Optional queryset to filter the object (default is None).<br>        :return: Post object if found.<br>        :raises Http404: If the post does not exist.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)  # Extract post_id from the URL kwargs.<br>        if not post_id:<br>            raise Http404(&quot;Post ID not provided.&quot;)<br><br>        try:<br>            post = PostService.get_post_by_id(post_id)  # Fetches the post using the PostService.<br>            if post is None:<br>                raise Http404(&quot;Post not found.&quot;)<br>            return post<br>        except ValidationError as e:<br>            raise Http404(f&quot;Invalid request: {str(e)}&quot;)</pre><p><strong>For the Comments app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/views/api_views.py :</li></ul><pre>from rest_framework import generics<br>from rest_framework.exceptions import NotFound, ValidationError, APIException<br>from ..serializers import CommentSerializer<br>from ..services.comment_service import CommentService<br><br>class CommentListCreateAPIView(generics.ListCreateAPIView):<br>    serializer_class = CommentSerializer<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Retrieve the &#39;post_id&#39; from the URL kwargs and fetch comments related to the given post ID using the CommentService.<br><br>        :return: QuerySet of Comment objects.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        &quot;&quot;&quot; <br>        post_id = self.kwargs.get(&quot;post_id&quot;)<br>        if not post_id:<br>            raise APIException(&quot;Post ID is required to fetch comments.&quot;)<br>        try:<br>            return CommentService.get_comments_by_post_id(post_id)<br>        except ValueError:<br>            raise APIException(&quot;Invalid Post ID format.&quot;)<br><br>    def perform_create(self, serializer):<br>        &quot;&quot;&quot;<br>        Create a new comment for the specified post using the CommentService.<br><br>        :param serializer: Serializer instance with validated data.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)<br>        if not post_id:<br>            raise APIException(&quot;Post ID is required to create a comment.&quot;)<br>        try:<br>            CommentService.create_comment(serializer.validated_data, post_id)<br>        except ValueError:<br>            raise APIException(&quot;Invalid Post ID format.&quot;)<br><br>class CommentRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):<br>    serializer_class = CommentSerializer<br><br>    def get_object(self):<br>        &quot;&quot;&quot;<br>        Retrieve the specific comment for the given post ID and comment ID using the CommentService.<br><br>        :return: Comment object.<br>        :raises: NotFound if the comment does not exist.<br>        :raises: ValidationError if &#39;post_id&#39; or &#39;comment_pk&#39; is not provided.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)<br>        comment_id = self.kwargs.get(&quot;comment_pk&quot;)<br>        if not post_id or not comment_id:<br>            raise APIException(&quot;Post ID and Comment ID are required to fetch the comment.&quot;)<br>        try:<br>            comment = CommentService.get_comment_by_post_and_id(post_id, comment_id)<br>            if comment is None:<br>                raise NotFound(&quot;Comment not found&quot;)<br>            return comment<br>        except ValueError:<br>            raise APIException(&quot;Invalid Post or Comment ID format.&quot;)<br><br>    def perform_update(self, serializer):<br>        &quot;&quot;&quot;<br>        Update the specified comment using the CommentService.<br><br>        :param serializer: Serializer instance with validated data.<br>        :raises: ValidationError if &#39;comment_pk&#39; is not provided.<br>        &quot;&quot;&quot;<br>        comment_id = self.kwargs.get(&quot;comment_pk&quot;)<br>        if not comment_id:<br>            raise APIException(&quot;Comment ID is required to update the comment.&quot;)<br>        try:<br>            CommentService.update_comment(serializer.validated_data, comment_id)<br>        except ValueError:<br>            raise APIException(&quot;Invalid Comment ID format.&quot;)<br><br>    def perform_destroy(self, instance):<br>        &quot;&quot;&quot;<br>        Delete the specified comment using the CommentService.<br><br>        :param instance: Comment instance to be deleted.<br>        :raises: ValidationError if &#39;comment_pk&#39; is not provided.<br>        &quot;&quot;&quot;<br>        comment_id = self.kwargs.get(&quot;comment_pk&quot;)<br>        if not comment_id:<br>            raise APIException(&quot;Comment ID is required to delete the comment.&quot;)<br>        try:<br>            CommentService.delete_comment(comment_id)<br>        except ValueError:<br>            raise APIException(&quot;Invalid Comment ID format.&quot;)</pre><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/views/web_views.py :</li></ul><pre>from django.views.generic import ListView, DetailView<br>from django.core.exceptions import ObjectDoesNotExist<br>from rest_framework.exceptions import ValidationError<br>from ..models import Comment<br>from ..services.comment_service import CommentService<br><br>class CommentListView(ListView):<br>    model = Comment<br>    template_name = &quot;comments/comment_list.html&quot;<br>    context_object_name = &quot;comments&quot;<br><br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Extract &#39;post_id&#39; from URL parameters to fetch comments associated with a specific post.<br><br>        :return: QuerySet of Comment objects.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to fetch comments.&quot;)<br>        try:<br>            return CommentService.get_comments_by_post_id(post_id)<br>        except Exception as e:<br>            raise e<br><br>    def get_context_data(self, **kwargs):<br>        &quot;&quot;&quot;<br>        Get the default context from the parent class and add additional context for &#39;post_id&#39;.<br><br>        :param kwargs: Additional context parameters.<br>        :return: Context dictionary.<br>        &quot;&quot;&quot;<br>        context = super().get_context_data(**kwargs)<br>        context[&quot;post_id&quot;] = self.kwargs.get(&quot;post_id&quot;)<br>        return context<br><br>class CommentDetailView(DetailView):<br>    model = Comment<br>    template_name = &quot;comments/comment_detail.html&quot;<br>    context_object_name = &quot;comment&quot;<br><br>    def get_object(self, queryset=None):<br>        &quot;&quot;&quot;<br>        Extract &#39;post_id&#39; and &#39;comment_id&#39; from URL parameters to retrieve a specific comment for a post.<br><br>        :return: Comment object.<br>        :raises: ValidationError if &#39;post_id&#39; or &#39;comment_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the comment does not exist.<br>        &quot;&quot;&quot;<br>        post_id = self.kwargs.get(&quot;post_id&quot;)<br>        comment_id = self.kwargs.get(&quot;comment_id&quot;)<br>        if not post_id or not comment_id:<br>            raise ValidationError(&quot;Post ID and Comment ID are required to fetch the comment.&quot;)<br>        try:<br>            comment = CommentService.get_comment_by_post_and_id(post_id, comment_id)<br>            if comment is None:<br>                raise ObjectDoesNotExist(f&quot;Comment with post_id {post_id} and comment_id {comment_id} not found.&quot;)<br>            return comment<br>        except ObjectDoesNotExist as e:<br>            raise e<br>        except Exception as e:<br>            raise e</pre><h4>3. Repositories</h4><p>Repositories handle data persistence and encapsulate data access logic. They are defined in separate files (repositories.py) within each application.</p><p><strong>For the Post app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/repositories/post_repository.py :</li></ul><pre>from ..models import Post<br>from django.core.exceptions import ObjectDoesNotExist, ValidationError<br><br><br>class PostRepository:<br>    &quot;&quot;&quot;<br>    Repository class for handling data operations related to the Post model.<br>    &quot;&quot;&quot;<br><br>    @staticmethod<br>    def get_all_posts():<br>        &quot;&quot;&quot;<br>        Fetch all posts from the database.<br><br>        :return: QuerySet of all Post objects.<br>        &quot;&quot;&quot;<br>        return Post.objects.all()<br><br>    @staticmethod<br>    def get_post_by_id(post_id):<br>        &quot;&quot;&quot;<br>        Fetch a specific post by its primary key (ID).<br><br>        :param post_id: Primary key of the post to fetch.<br>        :return: Post object if found, None otherwise.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to fetch the post.&quot;)<br>        try:<br>            return Post.objects.get(pk=post_id)<br>        except Post.DoesNotExist:<br>            return None<br><br>    @staticmethod<br>    def create_post(data):<br>        &quot;&quot;&quot;<br>        Create a new post with the provided data.<br><br>        :param data: Dictionary of data to create the post.<br>        :return: Newly created Post object.<br>        &quot;&quot;&quot;<br>        return Post.objects.create(**data)<br><br>    @staticmethod<br>    def update_post(data, post_id):<br>        &quot;&quot;&quot;<br>        Update an existing post with the provided data.<br><br>        :param data: Dictionary of data to update the post.<br>        :param post_id: Primary key of the post to update.<br>        :return: Updated Post object.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the post is not found.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to update the post.&quot;)<br>        try:<br>            post = Post.objects.get(pk=post_id)<br>            for attr, value in data.items():<br>                setattr(post, attr, value)  # Dynamically update each attribute<br>            post.save()<br>            return post<br>        except Post.DoesNotExist:<br>            raise ObjectDoesNotExist(f&quot;Post with ID {post_id} does not exist.&quot;)<br><br>    @staticmethod<br>    def delete_post(post_id):<br>        &quot;&quot;&quot;<br>        Delete a post by its primary key (ID).<br><br>        :param post_id: Primary key of the post to delete.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the post is not found.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to delete the post.&quot;)<br>        try:<br>            post = Post.objects.get(pk=post_id)<br>            post.delete()<br>        except Post.DoesNotExist:<br>            raise ObjectDoesNotExist(f&quot;Post with ID {post_id} does not exist.&quot;)</pre><p><strong>For the Comments app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/repositories/comment_repository.py :</li></ul><pre>from ..models import Comment<br>from django.core.exceptions import ObjectDoesNotExist<br>from django.db.utils import DatabaseError<br><br>class CommentRepository:<br>    @staticmethod<br>    def get_comments_by_post_id(post_id):<br>        &quot;&quot;&quot;<br>        Retrieve all comments associated with a specific post_id.<br><br>        :param post_id: The ID of the post to retrieve comments for.<br>        :return: QuerySet of Comment objects.<br>        &quot;&quot;&quot;<br>        try:<br>            return Comment.objects.filter(post_id=post_id)<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when retrieving comments for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def get_comment_by_post_and_id(post_id, comment_id):<br>        &quot;&quot;&quot;<br>        Retrieve a specific comment by post_id and comment_id.<br><br>        :param post_id: The ID of the post the comment is associated with.<br>        :param comment_id: The ID of the comment to retrieve.<br>        :return: Comment object if found, None otherwise.<br>        &quot;&quot;&quot;<br>        try:<br>            return Comment.objects.get(post_id=post_id, id=comment_id)<br>        except Comment.DoesNotExist:<br>            return None<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when retrieving comment {comment_id} for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def create_comment(data, post_id):<br>        &quot;&quot;&quot;<br>        Create a new comment associated with a specific post_id.<br><br>        :param data: Dictionary containing the data for the new comment.<br>        :param post_id: The ID of the post the comment is associated with.<br>        :return: The newly created Comment object.<br>        &quot;&quot;&quot;<br>        try:<br>            return Comment.objects.create(post_id=post_id, **data)<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when creating comment for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def update_comment(data, comment_id):<br>        &quot;&quot;&quot;<br>        Update an existing comment identified by comment_id.<br><br>        :param data: Dictionary containing the data to update the comment with.<br>        :param comment_id: The ID of the comment to update.<br>        :return: The updated Comment object.<br>        &quot;&quot;&quot;<br>        try:<br>            comment = Comment.objects.get(pk=comment_id)<br>            for attr, value in data.items():<br>                setattr(comment, attr, value)<br>            comment.save()<br>            return comment<br>        except Comment.DoesNotExist:<br>            return None<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when updating comment {comment_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def delete_comment(comment_id):<br>        &quot;&quot;&quot;<br>        Delete an existing comment identified by comment_id.<br><br>        :param comment_id: The ID of the comment to delete.<br>        :return: True if the comment was successfully deleted, False otherwise.<br>        &quot;&quot;&quot;<br>        try:<br>            comment = Comment.objects.get(pk=comment_id)<br>            comment.delete()<br>            return True<br>        except Comment.DoesNotExist:<br>            return False<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when deleting comment {comment_id}: {e}&quot;)<br>            raise e</pre><h4>4. Services</h4><p>Services contain the business logic and act as intermediaries between views and repositories. They are defined in separate files (services.py) within each application.</p><p><strong>For the Post app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/services/post_service.py :</li></ul><pre>from ..repositories.post_repository import PostRepository<br>from django.core.exceptions import ValidationError, ObjectDoesNotExist<br><br>class PostService:<br>    &quot;&quot;&quot;<br>    Service class for handling business logic related to the Post model.<br>    &quot;&quot;&quot;<br><br>    @staticmethod<br>    def get_all_posts():<br>        &quot;&quot;&quot;<br>        Retrieve all posts from the repository.<br><br>        :return: QuerySet of all Post objects.<br>        &quot;&quot;&quot;<br>        return PostRepository.get_all_posts()<br><br>    @staticmethod<br>    def get_post_by_id(post_id):<br>        &quot;&quot;&quot;<br>        Retrieve a post by its ID from the repository.<br><br>        :param post_id: Primary key of the post to fetch.<br>        :return: Post object if found, None otherwise.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the post does not exist.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to fetch the post.&quot;)<br>        post = PostRepository.get_post_by_id(post_id)<br>        if post is None:<br>            raise ObjectDoesNotExist(f&quot;Post with ID {post_id} does not exist.&quot;)<br>        return post<br><br>    @staticmethod<br>    def create_post(data):<br>        &quot;&quot;&quot;<br>        Create a new post with the given data.<br><br>        :param data: Dictionary of data to create the post.<br>        :return: Newly created Post object.<br>        :raises: ValidationError if required data fields are missing.<br>        &quot;&quot;&quot;<br>        # Example validation: Ensure title and content are provided<br>        if not data.get(&quot;title&quot;) or not data.get(&quot;content&quot;):<br>            raise ValidationError(&quot;Title and content are required to create a post.&quot;)<br>        return PostRepository.create_post(data)<br><br>    @staticmethod<br>    def update_post(data, post_id):<br>        &quot;&quot;&quot;<br>        Update an existing post with the given data.<br><br>        :param data: Dictionary of data to update the post.<br>        :param post_id: Primary key of the post to update.<br>        :return: Updated Post object.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the post does not exist.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to update the post.&quot;)<br>        if not data:<br>            raise ValidationError(&quot;Data is required to update the post.&quot;)<br>        return PostRepository.update_post(data, post_id)<br><br>    @staticmethod<br>    def delete_post(post_id):<br>        &quot;&quot;&quot;<br>        Delete a post by its ID from the repository.<br><br>        :param post_id: Primary key of the post to delete.<br>        :raises: ValidationError if &#39;post_id&#39; is not provided.<br>        :raises: ObjectDoesNotExist if the post does not exist.<br>        &quot;&quot;&quot;<br>        if not post_id:<br>            raise ValidationError(&quot;Post ID is required to delete the post.&quot;)<br>        return PostRepository.delete_post(post_id)</pre><p><strong>For the Comments app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/services/comment_service.py :</li></ul><pre>from ..repositories.comment_repository import CommentRepository<br>from django.core.exceptions import ObjectDoesNotExist<br>from django.db.utils import DatabaseError<br><br>class CommentService:<br>    @staticmethod<br>    def get_comments_by_post_id(post_id):<br>        &quot;&quot;&quot;<br>        Retrieve all comments associated with a specific post_id.<br><br>        :param post_id: The ID of the post to retrieve comments for.<br>        :return: QuerySet of Comment objects.<br>        :raises: DatabaseError if there is an error accessing the database.<br>        &quot;&quot;&quot;<br>        try:<br>            return CommentRepository.get_comments_by_post_id(post_id)<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when retrieving comments for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def get_comment_by_post_and_id(post_id, comment_id):<br>        &quot;&quot;&quot;<br>        Retrieve a specific comment by post_id and comment_id.<br><br>        :param post_id: The ID of the post the comment is associated with.<br>        :param comment_id: The ID of the comment to retrieve.<br>        :return: Comment object if found, None otherwise.<br>        :raises: DatabaseError if there is an error accessing the database.<br>        &quot;&quot;&quot;<br>        try:<br>            return CommentRepository.get_comment_by_post_and_id(post_id, comment_id)<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when retrieving comment {comment_id} for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def create_comment(data, post_id):<br>        &quot;&quot;&quot;<br>        Create a new comment associated with a specific post_id.<br><br>        :param data: Dictionary containing the data for the new comment.<br>        :param post_id: The ID of the post the comment is associated with.<br>        :return: The newly created Comment object.<br>        :raises: DatabaseError if there is an error accessing the database.<br>        &quot;&quot;&quot;<br>        try:<br>            return CommentRepository.create_comment(data, post_id)<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when creating comment for post_id {post_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def update_comment(data, comment_id):<br>        &quot;&quot;&quot;<br>        Update an existing comment identified by comment_id.<br><br>        :param data: Dictionary containing the data to update the comment with.<br>        :param comment_id: The ID of the comment to update.<br>        :return: The updated Comment object.<br>        :raises: ObjectDoesNotExist if the comment does not exist.<br>        :raises: DatabaseError if there is an error accessing the database.<br>        &quot;&quot;&quot;<br>        try:<br>            comment = CommentRepository.update_comment(data, comment_id)<br>            if comment is None:<br>                raise ObjectDoesNotExist(f&quot;Comment with id {comment_id} does not exist.&quot;)<br>            return comment<br>        except ObjectDoesNotExist as e:<br>            # Log the exception (if logging is configured)<br>            # logger.warning(f&quot;Attempted to update non-existent comment {comment_id}: {e}&quot;)<br>            raise e<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when updating comment {comment_id}: {e}&quot;)<br>            raise e<br><br>    @staticmethod<br>    def delete_comment(comment_id):<br>        &quot;&quot;&quot;<br>        Delete an existing comment identified by comment_id.<br><br>        :param comment_id: The ID of the comment to delete.<br>        :return: True if the comment was successfully deleted, False otherwise.<br>        :raises: DatabaseError if there is an error accessing the database.<br>        &quot;&quot;&quot;<br>        try:<br>            success = CommentRepository.delete_comment(comment_id)<br>            if not success:<br>                raise ObjectDoesNotExist(f&quot;Comment with id {comment_id} does not exist.&quot;)<br>            return success<br>        except ObjectDoesNotExist as e:<br>            # Log the exception (if logging is configured)<br>            # logger.warning(f&quot;Attempted to delete non-existent comment {comment_id}: {e}&quot;)<br>            raise e<br>        except DatabaseError as e:<br>            # Log the exception (if logging is configured)<br>            # logger.error(f&quot;Database error when deleting comment {comment_id}: {e}&quot;)<br>            raise e</pre><h4>5. Serializers</h4><p>Serializers convert complex data into native data formats (JSON) and vice versa. Serialisers are an important part of creating REST APIs with DRF which are not usually used in a normal Django project.</p><p><strong>For the Post app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/serializers.py</li></ul><pre>from rest_framework import serializers<br>from .models import Post<br><br># Serializer for the Post model<br># This class is responsible for converting Post instances into JSON data and validating incoming data for creating or updating posts.<br>class PostSerializer(serializers.ModelSerializer):<br><br>    # Meta class specifies the model and fields to be used by the serializer.<br>    class Meta:<br>        model = Post  # The model associated with this serializer. It tells DRF which model the serializer will be handling.<br>        fields = &quot;__all__&quot;  # Specifies that all fields from the model should be included in the serialization and deserialization process.</pre><p><strong>For the Comments app:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/comments/serializers.py :</li></ul><pre>from rest_framework import serializers<br>from .models import Comment<br><br># CommentSerializer is a ModelSerializer that automatically creates fields and methods for the Comment model.<br>class CommentSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Comment  # The model that this serializer will be based on.<br>        fields = &quot;__all__&quot;  # Automatically include all fields from the Comment model.</pre><h4>6. Configuration of URLs</h4><p>URLs are organised into two separate files for the API and web views, allowing a clear separation between accessing data via the API and presenting data via web views. This organisation facilitates code management and maintenance by distinguishing between paths that serve JSON data and paths that present HTML views.</p><p>API routes are defined only in the Posts application to centralise the management of resources related to posts and their comments. By not having its own urls.py file in the Comments application, redundancy is reduced and the project structure is simplified by grouping all related API paths in one place. This makes it easier to understand the data flow and the interrelationship between posts and comments, promoting a more coherent and maintainable architecture, and the correct use of REST best practices.</p><p><strong>URLs API REST:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/urls/api_urls.py :</li></ul><pre>from django.urls import path<br>from ..views.api_views import PostListCreateAPIView, PostRetrieveUpdateDestroyAPIView<br>from ...comments.views.api_views import (<br>    CommentListCreateAPIView,<br>    CommentRetrieveUpdateDestroyAPIView,<br>)<br><br>urlpatterns = [<br>    # Route for listing all posts or creating a new post<br>    path(&quot;&quot;, PostListCreateAPIView.as_view(), name=&quot;post-list-create&quot;),<br>    # Route for retrieving, updating, or deleting a specific post by post_id<br>    path(<br>        &quot;&lt;int:post_id&gt;/&quot;,<br>        PostRetrieveUpdateDestroyAPIView.as_view(),<br>        name=&quot;post-retrieve-update-destroy&quot;,<br>    ),<br>    # Route for listing all comments for a specific post or creating a new comment for that post<br>    path(<br>        &quot;&lt;int:post_id&gt;/comments/&quot;,<br>        CommentListCreateAPIView.as_view(),<br>        name=&quot;post-comment-create&quot;,<br>    ),<br>    # Route for retrieving, updating, or deleting a specific comment by comment_pk for a specific post<br>    path(<br>        &quot;&lt;int:post_id&gt;/comments/&lt;int:comment_pk&gt;/&quot;,<br>        CommentRetrieveUpdateDestroyAPIView.as_view(),<br>        name=&quot;post-comment-retrieve-update-destroy&quot;,<br>    ),<br>]</pre><p><strong>URLs web:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/apps/posts/urls/web_urls.py :</li></ul><pre>from django.urls import path<br>from ..views.web_views import PostListView, PostDetailView<br>from ...comments.views.web_views import CommentListView, CommentDetailView<br><br>urlpatterns = [<br>    # Route for listing all posts.<br>    # The URL is &quot;web/posts/&quot;, and it maps to PostListView to display a list of all posts.<br>    path(&quot;&quot;, PostListView.as_view(), name=&quot;post-list&quot;),<br>    # Route for displaying details of a specific post identified by post_id.<br>    # The URL is &quot;web/posts/&lt;post_id&gt;/&quot;, and it maps to PostDetailView to display details of a single post.<br>    path(&quot;&lt;int:post_id&gt;/&quot;, PostDetailView.as_view(), name=&quot;post-detail&quot;),<br>    # Route for listing all comments for a specific post identified by post_id.<br>    # The URL is &quot;web/posts/&lt;post_id&gt;/comments&quot;, and it maps to CommentListView to display a list of comments for the given post.<br>    path(<br>        &quot;&lt;int:post_id&gt;/comments&quot;,<br>        CommentListView.as_view(),<br>        name=&quot;post-comments&quot;,<br>    ),<br>    # Route for displaying details of a specific comment identified by comment_id for a specific post.<br>    # The URL is &quot;web/posts/&lt;post_id&gt;/comments/&lt;comment_id&gt;/&quot;, and it maps to CommentDetailView to display details of a single comment.<br>    path(<br>        &quot;&lt;int:post_id&gt;/comments/&lt;int:comment_id&gt;/&quot;,<br>        CommentDetailView.as_view(),<br>        name=&quot;post-comment-detail&quot;,<br>    ),<br>]</pre><p><strong>General project URLs:</strong></p><ul><li><strong>In the archive:</strong>/my_project_blog/my_project_blog/urls.py :</li></ul><pre>from django.contrib import admin<br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&quot;admin/&quot;, admin.site.urls),<br>    path(&quot;posts/&quot;, include(&quot;apps.posts.urls.web_urls&quot;)),<br>    path(&quot;api/posts/&quot;, include(&quot;apps.posts.urls.api_urls&quot;)),<br>]</pre><h3>Web application and API testing</h3><p>Now, in the third section of this blog, we will create some posts and add several comments to each of the posts to verify the correct functioning of the web application and the API and web URLs.</p><h4>1. Execute the project</h4><ul><li><strong>Creates Migrations:</strong></li></ul><pre> python manage.py makemigrations</pre><ul><li><strong>Apply migrations:</strong></li></ul><pre> python manage.py migrate</pre><ul><li><strong>Run the Django development server:</strong></li></ul><pre> python manage.py runserver</pre><p><strong><em>Note:</em></strong> Open your browser and navigate to http://127.0.0.1:8000/, from now on the urls that I will give you will be after the domain (in this case our localhost:8000 or 127.0.0.1:8000), example: If I give you the url /api/posts/, in the browser you will have to put http://127.0.0.1:8000/api/posts/ or http://localhost:8000/api/posts/.</p><h4>2. Creation of posts</h4><p><strong>2.1 Access the Django REST API interface:</strong></p><ul><li><strong>URL:</strong>/api/posts/</li><li><strong>Action:</strong> Fill in the form with the details of the post to be created and click on the “POST” button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bQWjvIfmP0TmO1eA" /></figure><h4>3. <strong>Add comments to posts:</strong></h4><p><strong>3.1 Access the Django REST API interface:</strong></p><ul><li><strong>URL:</strong>/api/posts/{post_id}/comments/</li><li><strong>Action:</strong> Fill in the form with the details of the comment to be created for a specific post and click on the &quot;POST&quot; button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7d3NTW_muQT4Tg5" /></figure><p>You can repeat these steps to create as many posts and comments as you want.</p><p>Also, in this same Django REST API interface you can edit posts or comments or delete them.</p><h4>4. Verify the creation of posts and comments:</h4><p>Having already created several posts and comments for some of these via the REST API, we can see these in the web URLs that interact with the HTML templates.</p><p>So that when you enter the given URLs you can see the same design, you can see the HTML code of each template in the HTML files of the project.</p><p><strong>Full project code on GitHub:</strong></p><p><a href="https://github.com/MateoRamirezRubio1/mini-blog-rest-api">GitHub - MateoRamirezRubio1/mini-blog-rest-api: A mini blog Django project demonstrating the implementation of the Services and Repositories design pattern for a blog application.</a></p><ol><li><strong>See the list of posts:</strong></li></ol><ul><li><strong>URL:</strong>/posts/</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*zxyQ4QYOUlU4kyL_" /></figure><p><strong>2. See the details of a specific post:</strong></p><ul><li><strong>URL:</strong>/posts/{post_id}/</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*Oi61HE9k5HzHs0hR" /></figure><p><strong>3. See comments on a specific post:</strong></p><ul><li><strong>URL:</strong>/posts/{post_id}/comments/</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*RkO8OKU2fE_TMSyx" /></figure><p><strong>4. View the details of a comment on a specific post:</strong></p><ul><li><strong>URL:</strong>/posts/{post_id}/comments/{comment_id}/</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*-n0yJqUq4Zu_zrc0" /></figure><h3>Conclusions</h3><h4>Benefits of the Services and Repositories Pattern</h4><ol><li><strong>Separation of Responsibilities:</strong></li></ol><p>Separation of responsibilities is one of the fundamental principles in software design. In the Services and Repositories pattern, we clearly separate data access concerns (repositories) from business logic (services).</p><p><strong>Benefits:</strong></p><ul><li><strong>Clarity and Organisation:</strong> The code is organised so that each class and function has a single, clearly defined responsibility. This makes the code easier to understand and maintain.</li><li><strong>Maintainability:</strong> When the business logic changes, only the services need to be modified, while the repositories remain unchanged. This reduces the number of changes and the risk of introducing errors.</li><li><strong>Team Collaboration: </strong>In a development team, different members can work at different layers (e.g. one on services and one on repositories) without interfering with each other, facilitating collaboration and integration.</li></ul><p><strong>2. Re-use of the Code:</strong></p><p>The pattern encourages code reuse by centralising business logic and data access in specific classes. This avoids code duplication and facilitates code reuse in different parts of the application.</p><p><strong>Benefits:</strong></p><ul><li><strong>Duplication Reduction:</strong> By having business logic in services and data access in repositories, we avoid repeating code in multiple places, making the code more DRY (Don’t Repeat Yourself).</li><li><strong>Consistency:</strong> Reusing the same code in different parts of the application ensures that the same logic and rules are followed everywhere, which increases consistency and reduces errors.</li><li><strong>Ease of Update:</strong> If you need to change the way data is accessed or business logic is implemented, you only need to update the corresponding repository or service. The other parts of the application that depend on them will automatically benefit from the changes.</li></ul><p><strong>3. Ease of Testing:</strong></p><p>The separation of business logic and data access logic facilitates the creation of unit and integration tests. Services and repositories can be tested in isolation, which simplifies the testing process.</p><p><strong>Benefits:</strong></p><ul><li><strong>Unit testing:</strong> By having business logic in services and data access in repositories, it is easier to create unit tests for each component independently. This makes it possible to quickly detect errors and ensure that each part works correctly.</li><li><strong>Mocks and Stubs:</strong> During testing, it is easy to use mocks and stubs to simulate the behaviour of repositories or services. This allows testing business logic without relying on the database or other external services.</li><li><strong>Reduced Testing Complexity:</strong> By having clear and well-defined responsibilities, testing becomes less complex and more specific. This improves test coverage and software reliability.</li></ul><p><strong>4. Maintainability and Extensibility:</strong></p><p>The Services and Repositories pattern makes code more maintainable and extensible. This is especially important in long-term projects, where requirements may change over time.</p><p><strong>Benefits:</strong></p><ul><li><strong>Code Evolution:</strong> When you need to add new functionality, it is easy to extend existing services and repositories without affecting the rest of the application. This allows the code to evolve in a controlled and safe way.</li><li><strong>Easy Refactoring:</strong> If you identify an improvement in the code structure or business logic implementation, it is easy to refactor services and repositories without great risk. The separation of responsibilities makes it easy to identify which parts of the code need to be changed.</li><li><strong>Adaptability to New Technologies: </strong>If at some point you decide to change the persistence technology (for example, from a SQL database to a NoSQL one), you only need to modify the repositories without affecting the business logic implemented in the services.</li></ul><p>Finally, in closing, I thank you for your time and attention in following this guide to the Services and Repositories design pattern in a Django project with the Django REST Framework. I hope this detailed explanation has given you a solid understanding of how to structure your applications in an efficient and maintainable way.</p><p>Implementing this pattern will not only improve the organization of your code, but also facilitate its evolution and scalability as your project grows. If you have any additional questions or opinions on the topic, feel free to post in the comments, they are left open for discussion.</p><p>Good luck with your development and best of luck with your future projects!</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1ef1ab7d9e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Name Endpoints/URLs in a REST API: Complete Guide with Best Practices and Practical Example]]></title>
            <link>https://medium.com/@matteo.dcj/how-to-name-endpoints-urls-in-a-rest-api-complete-guide-with-best-practices-and-practical-example-7e2dbab5f1cd?source=rss-2ff61273e528------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2dbab5f1cd</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[MateoRamirezR]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 05:27:25 GMT</pubDate>
            <atom:updated>2024-08-03T05:32:21.271Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Learn how to design clear and effective endpoints for your REST API, improving user experience and system maintainability, with an exercise at the end.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2N6REL3XnKcp4Onci351w.png" /></figure><h3>Introduction:</h3><p>Naming the endpoints of a REST API may seem like a simple task, but in reality, it is one of the keys to ensuring that your API is intuitive, easy to use and maintain. Imagine trying to navigate a system where the paths don’t make sense or don’t follow a logical pattern. It would be like trying to find your way in a city with no road signs. In this blog, we’ll look at some best practices for naming your endpoints effectively, ensuring that your users and developers can interact with your API clearly and efficiently. At the end, you’ll see a complete example that you can use as a practical exercise to apply what you’ve learned — read on to master the art of naming endpoints in REST APIs!</p><h3>Contents:</h3><ol><li><strong>Introduction.</strong></li><li><strong>Recommendations for naming your endpoints.</strong></li></ol><ul><li><strong>Represent resources and not actions.</strong></li><li><strong>Nested hierarchical structure.</strong></li><li><strong>Use of clear and descriptive names.</strong></li><li><strong>Consistency in the use of upper and lower case letters.</strong></li><li><strong>Avoid file extensions.</strong></li><li><strong>Endpoint naming formula.</strong></li><li><strong>Complete REST API endpoint naming design example.</strong></li></ul><p><strong>3. Acknowledgments.</strong></p><h3><strong>Recommendations for naming your endpoints</strong></h3><p>When we design a REST API, we want it to be easy to understand and use. To achieve this we must follow some rules to name our URLs in a consistent way.</p><h4>1. Represent resources and not actions (<em>resources should be named in plural</em>):</h4><p>You can fall into the trap of using actions or verbs when naming your endpoints such as:</p><ul><li><strong><em>How not to do it:</em></strong></li></ul><p>GET /deleteBook/321</p><p>GET /deleteBook?id=321</p><p>POST /books/321/delete</p><p>Following the REST parameters, this is not well done, the correct way to do it for this example is that there is a resource called Books and through the HTTP methods we say the action we want to do as for example delete it (DELETE) like this:</p><ul><li><strong><em>How to do it right:</em></strong></li></ul><p>DELETE /books/321</p><p>‎</p><h4>2. Nested hierarchical structure:</h4><p>To maintain good consistency and coherence in our URLs, we must use a hierarchical structure that shows relationships between resources. Example:</p><ul><li><strong><em>How not to do it:</em></strong></li></ul><p>/books?libraryId=123</p><p>/comments?bookId=456</p><p>‎</p><ul><li><strong><em>How to do it right:</em></strong></li></ul><p>/libraries/123/books</p><p>/books/456/comments</p><p>‎</p><h4>3. Use of clear and descriptive names:</h4><p>Continuing with consistency in the naming of endpoints and knowing that verbs should not be used to name resources, remember to use names that clearly describe the resources.‎</p><ul><li><strong><em>How not to do it:</em></strong></li></ul><p>/data</p><p>/info</p><p>‎</p><ul><li><strong><em>How to do it right:</em></strong></li></ul><p>/users</p><p>/products</p><p>‎</p><h4>4. Consistency in the use of upper and lower case letters:</h4><ul><li><strong><em>How not to do it:</em> </strong>Mixing upper and lower case inconsistently:</li></ul><p>/UserProfiles</p><p>/Order_Details</p><p>‎</p><ul><li><strong><em>How to do it right: </em></strong>Use lowercase letters and hyphens consistently:</li></ul><p>/user-profiles</p><p>/order-details</p><p>‎</p><h4>5. Avoid file extensions:</h4><p>It may seem very obvious, but let’s not overlook the fact that we should not use file extensions in the resource name in our URL, we should let the content type be determined by the HTTP headers.‎</p><ul><li><strong><em>How not to do it:</em></strong></li></ul><p>/users.json</p><p>/orders.xml</p><p>‎</p><ul><li><strong><em>How to do it right:</em></strong></li></ul><p>/users</p><p>/orders</p><p>As a more visual aid, following the conventions, we can use the following formula for naming our URLs:</p><h4><em>/{collection} /{store} /{document}/{controller}</em></h4><p>‎</p><ol><li><strong>Collection (plural): </strong>A set of resources:</li></ol><ul><li>/books</li></ul><p><strong>2. Store (plural):</strong> Contains resources managed by the client (stores are not used as much):</p><ul><li>/users/12/favorites</li></ul><p><strong>3. Document (singular):</strong> An instance in a collection:</p><ul><li>/books/2</li><li>/books/maths</li></ul><p><strong>4. Controller (verb): </strong>Executable functions (usually when we use controllers the HTTP method we use is POST):</p><ul><li>/users/12/reset-password</li></ul><h3><strong>Complete example of how to name our endpoints</strong></h3><p>In this section we will see a complete example of an api design, first we will see how a bad REST API design would look like and then its correction.</p><p><strong>Note:</strong> Before seeing how a well designed REST API would look like, correct yourself the errors of the badly designed API and compare at the end. This way you will learn more!</p><h4><strong><em>Poorly Designed API:</em></strong></h4><p>‎</p><ol><li><strong>Collection of books:</strong></li></ol><ul><li><strong>Obtain all books:</strong></li><li>GET /getAllBooks</li></ul><p>‎</p><ul><li><strong>Create a new book:</strong></li><li>POST /createBook</li></ul><p>‎</p><p><strong>2. A user’s favorite books:</strong></p><ul><li><strong>Get a specific user’s favorite books:</strong></li><li>GET /getUserFavorites?userId=12</li></ul><p>‎</p><ul><li><strong>Add a book to the favorites of a specific user:</strong></li><li>POST /addFavorite?userId=12&amp;bookId=123</li></ul><p>‎</p><p><strong>3. Specific Book</strong></p><ul><li><strong>Obtain a specific book:</strong></li><li>GET /getBookById?bookId=123</li></ul><p>‎</p><ul><li><strong>Update a specific book:</strong></li><li>POST /updateBook?bookId=123</li></ul><p>‎</p><ul><li><strong>Delete a specific book:</strong></li><li>POST /deleteBook?bookId=123</li></ul><p>‎</p><p><strong>4. Action/Controller in Specific Book</strong></p><ul><li><strong>Mark a book as read:</strong></li><li>POST /markBookAsRead?bookId=123</li></ul><p>‎</p><ul><li><strong>Request a loan extension:</strong></li><li>POST /requestExtension?bookId=123</li></ul><p>‎</p><h4><strong>Problems with Bad Design:</strong></h4><ul><li><strong>Verbs in URLs: </strong>URLs should represent resources, not actions.</li><li><strong>Inappropriate use of HTTP methods:</strong> POST is used for update and delete, instead of PUT and DELETE.</li><li><strong>Use of query parameters:</strong> Query parameters (?bookId=123) are being used instead of resource identifiers in the path.</li></ul><p>‎</p><p>Now we will see the API as it would be well designed.</p><p>‎</p><h4>API REST well designed:</h4><ol><li><strong>Book Collection:</strong></li></ol><ul><li><strong>Obtain all books:</strong></li><li>GET /books</li></ul><p>‎</p><ul><li><strong>Create a new book:</strong></li><li>POST /books</li></ul><p>‎</p><p><strong>2. User Favorite Books</strong></p><ul><li><strong>Get a specific user’s favorite books:</strong></li><li>GET /users/12/favorites</li></ul><p>‎</p><ul><li><strong>Add a book to the favorites of a specific user:</strong></li><li>POST /users/12/favorites</li></ul><p>‎</p><p><strong>3. Specific Book</strong></p><ul><li><strong>Obtain a specific book:</strong></li><li>GET /books/123</li></ul><p>‎</p><ul><li><strong>Update a specific book:</strong></li><li>PUT /books/123</li></ul><p>‎</p><ul><li><strong>Delete a specific book:</strong></li><li>DELETE /books/123</li></ul><p>‎</p><p><strong>4. Action/Controller in Specific Book</strong></p><ul><li><strong>Mark a book as read:</strong></li><li>POST /books/123/mark-as-read</li></ul><p>‎</p><ul><li><strong>Request a loan extension:</strong></li><li>POST /books/123/request-extension</li></ul><p>‎</p><h4>Benefits of Good Design:</h4><ul><li><strong>Clarity: </strong>URLs are clear and represent resources.</li><li><strong>Correct use of HTTP methods: </strong>GET, POST, PUT, and DELETE are used properly.</li><li><strong>Identifiers in the path: </strong>Resource identifiers are included in the path, not as query parameters.</li><li><strong>Logical structure: </strong>The hierarchical and logical structure facilitates the understanding and use of the API.</li></ul><p>‎</p><p>Thus, by following the right structure and proper use of HTTP methods, the well-designed API is more intuitive, scalable and easy to maintain.</p><p>I hope this guide has provided you with the tools you need to design clear and consistent endpoints for your REST API. Good endpoint naming not only improves the user experience, but also facilitates the maintenance and scalability of your system. Remember that consistency and clarity are essential in API development. Don’t forget to practice with the full example. Until next time, and <strong>happy coding</strong>!</p><p>‎</p><p><strong>You can also find this content in Spanish here:</strong></p><p><a href="https://www.linkedin.com/pulse/aprende-dise%25C3%25B1ar-endpoints-claros-y-eficaces-para-su-la-ramirez-rubio-nmv7e/?trackingId=svVFJ9MRRHyFsBAGkGsxYw%3D%3D">Aprende a diseñar Endpoints claros y eficaces para su API REST, mejorando la experiencia del usuario y la mantenibilidad del sistema</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2dbab5f1cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>