<?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 Ukeme  Wilson on Medium]]></title>
        <description><![CDATA[Stories by Ukeme  Wilson on Medium]]></description>
        <link>https://medium.com/@ukemeboswilson?source=rss-efa157ed281d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XUv6uwZjXs4CJ1XzYiCX3A.png</url>
            <title>Stories by Ukeme  Wilson on Medium</title>
            <link>https://medium.com/@ukemeboswilson?source=rss-efa157ed281d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:41:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ukemeboswilson/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[Exploring Django Queries: Techniques for Efficient Querying]]></title>
            <link>https://medium.com/@ukemeboswilson/exploring-django-queries-techniques-for-efficient-querying-7a330e5d54b9?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a330e5d54b9</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[orm]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 17:49:21 GMT</pubDate>
            <atom:updated>2024-09-20T17:49:21.668Z</atom:updated>
            <content:encoded><![CDATA[<p>Django’s Object-Relational Mapping (ORM) allows you to interact with databases using Python code without needing to write raw SQL queries. It acts as a bridge between Django models, which represent database tables, and the underlying database itself. Each Django model is a Python class that corresponds to a database table, where each class attribute maps to a column in that table.</p><p>Check here to learn more about <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">Django Model</a>.</p><p>The ORM translates Python code into SQL queries by mapping Python objects (models) and their operations (such as querying, inserting, and updating) into SQL statements that interact with the database. This abstraction simplifies working with databases, allowing developers to focus on business logic rather than low-level SQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLwZyQI1sAZCwKLDoy_XjQ.png" /></figure><h4>Django’s .objects Manager</h4><p>In Django, .objects is a default model manager that provides the primary interface for querying the database. When you define a model, Django automatically adds the objects manager to it, which gives you access to methods for interacting with the database. Through this manager, you can query, filter, create, update, or delete records.</p><h4>Database-Agnostic ORM</h4><p>One of the strengths of Django’s ORM is that it is database-agnostic. This means it works seamlessly with various databases — such as PostgreSQL, MySQL, and SQLite — without requiring you to change your code. The same code can be used to interact with different databases, ensuring flexibility and ease of integration across environments.</p><h4>Simplified Querying with Django ORM</h4><p>Django ORM reduces the complexity of working with databases. Complex queries and operations can be handled through simple method calls and attributes. This approach is not only easier to read and maintain than raw SQL, but it also ensures that your database queries are more secure and optimized.</p><h4>QuerySets: The Core of Django ORM</h4><p>A QuerySet is central to Django&#39;s ORM. It represents a collection of database queries and their results, allowing developers to retrieve, filter, and manipulate data in a high-level, Pythonic way. QuerySets are lazy, meaning the actual database query is executed only when the data is needed, optimizing performance and minimizing unnecessary database hits.</p><p><strong>Lets consider this analogy</strong></p><p>Imagine a library full of books, where each <strong>shelf</strong> represents a <strong>table</strong> and each <strong>book</strong> represents a <strong>record</strong>. Now, instead of searching through the library manually, you have a <strong>librarian</strong> (Django’s ORM) who can find exactly what you need based on your request.</p><p>When you use a <strong>Django query</strong>, it’s like giving the librarian specific instructions:</p><ul><li><strong>.all()</strong>: &quot;Show me all the books on the shelf.&quot;</li><li><strong>.filter()</strong>: &quot;Show me only the books published in 2023.&quot;</li><li><strong>.exclude()</strong>: &quot;Show me all the books, except the ones published by author X.&quot;</li><li><strong>.get()</strong>: &quot;Find me the one and only book with this unique ID.&quot;</li></ul><p>The librarian (Django ORM) knows exactly how to look through the library (database) and get the information you want quickly and efficiently, without you needing to know the complex inner workings of the library system (SQL).</p><p>Lets see some examples using the models below.</p><p>(Create a Django project and a Django app. Check <a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">here</a> on how to)</p><pre>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br>    email = models.EmailField(unique=True)<br>    age = models.PositiveSmallIntegerField()<br>    <br>    def __str__(self) -&gt; str:<br>        return self.name<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    best_seller = models.BooleanField(default=False)<br>    num_pages = models.PositiveSmallIntegerField()<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name=&quot;books&quot;)<br>    <br>    def __str__(self) -&gt; str:<br>        return self.title</pre><p>Lets create some dummy data</p><pre>def create_author(name, age, email):<br>    author = Author(name=name, age=age, email=email)<br>    author.save()<br>    <br>    return author<br><br>def create_book(title, best_seller, num_pages, author):<br>    book = Book(<br>        title=title,<br>        best_seller=best_seller,<br>        num_pages=num_pages,<br>        author=author<br>        )<br>    <br>    book.save()<br><br><br>def create_records_in_table():<br>    john = create_author(&#39;John J.&#39;, 44, &quot;john@j.com&quot;)<br>    peter = create_author(&#39;Peter P.&#39;, 31, &quot;peter@p.com&quot;)<br>    andrew = create_author(&#39;Andrew A.&#39;, 44, &quot;andrew@a.com&quot;)<br><br>    create_book(&quot;Secrets Unknown&quot;, True, 400, john)<br>    create_book(&quot;Becoming John&quot;, False, 250, john)<br>    create_book(&quot;A Tale of Tales&quot;, True, 390, peter)<br>    create_book(&quot;Living the Life&quot;, True, 210, peter)<br>    create_book(&quot;New Beginnings&quot;, False, 412, andrew)<br>    <br>    print(&quot;records created&quot;)</pre><p>Run migrations</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>We will be using the Django shell to try out the queries</p><pre>python manage.py shell</pre><p>Next we create the dummy data</p><pre>&gt;&gt;&gt; from appQueries.create_records import create_records_in_table<br>&gt;&gt;&gt; create_records_in_table()<br># records created</pre><p><strong>QuerySet Examples:</strong></p><ol><li>.all(). This returns all records in the QuerySet</li></ol><pre>from appQueries.models import Book, Author<br>Book.objects.all()<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: Becoming John&gt;, &lt;Book: A Tale of Tales&gt;, &lt;Book: Living the Life&gt;, &lt;Book: New Beginnings&gt;]&gt;</pre><p>2. .filter(**kwargs): This returns records matching the given filter conditions</p><pre>Book.objects.filter(title=&quot;Living the Life&quot;)<br># &lt;QuerySet [&lt;Book: Living the Life&gt;]&gt;</pre><p>3. .exclude(**kwargs): This returns records that do not match the given conditions.</p><pre>Book.objects.exclude(title=&quot;Living the Life&quot;)<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: Becoming John&gt;, &lt;Book: A Tale of Tales&gt;, &lt;Book: New Beginnings&gt;]&gt;</pre><p>4. .get(**kwargs): Retrieves a single record matching the conditions (raises DoesNotExist if no record is found, or MultipleObjectsReturned if more than one is found).</p><pre>try:<br>   book = Book.objects.get(title=&quot;Living the Life&quot;)<br>   print(book)<br>except Book.DoesNotExist:<br>   print(&quot;Book does not exist&quot;)<br><br># &lt;Book: Living the Life&gt;</pre><p><strong>Field Lookup:</strong></p><p>We can attach certain attributes to field names to perform more specific filtering.</p><ul><li>__startswith: starting letters of the search keyword</li></ul><pre> Book.objects.filter(title__startswith=&quot;Becoming&quot;)<br># &lt;QuerySet [&lt;Book: Becoming John&gt;]&gt;</pre><ul><li>__endswith: ending letters of the search keyword</li></ul><pre>Book.objects.filter(title__endswith=&quot;n&quot;)<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: Becoming John&gt;]&gt;</pre><ul><li>__contains: partials letters of the search keyword</li></ul><pre>Book.objects.filter(title__contains=&quot;un&quot;)<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;]&gt;</pre><ul><li>__exact: exact letters of the search keyword</li></ul><pre>Book.objects.filter(title__exact=&quot;Becoming John&quot;)<br># &lt;QuerySet [&lt;Book: Becoming John&gt;]&gt;</pre><ul><li>__in: In a given list</li></ul><pre>ages = [20, 25, 30, 25, 44]<br>Author.objects.filter(age__in=ages)<br># &lt;QuerySet [&lt;Author: John J.&gt;, &lt;Author: Andrew A.&gt;]&gt;<br></pre><ul><li>__isnull: Checks if the field is NULL</li></ul><pre> Author.objects.filter(name__isnull=True)<br># &lt;QuerySet []&gt;</pre><ul><li>__regex: filter objects based on a regular expression match.</li></ul><pre> Author.objects.filter(name__regex=r&quot;^\w{4}\s\w.$&quot;)<br># &lt;QuerySet [&lt;Author: John J.&gt;]&gt;</pre><p><strong>Case insensitive:</strong></p><p>We can get case insensitive results by using ‘i’ together with the field look ups.</p><p>__istartswith</p><p>__iendswith</p><p>__icontains</p><p>__iexact</p><p><strong>Comparison lookups:</strong></p><p>__gt: Greater than</p><p>__gte: Greater than or equals</p><p>__lt: less than</p><p>__lte: less than equals</p><pre>Book.objects.filter(num_pages__gt=300)<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: A Tale of Tales&gt;, &lt;Book: New Beginnings&gt;]&gt;</pre><p><strong>Aggregation:</strong></p><p>In Django, the Sum, Avg, Max, Min, and Count functions are commonly used for <strong>aggregation</strong> on QuerySets. You can use these to perform operations like summing values, calculating averages, and finding maximum or minimum values directly on your database records.</p><pre>&gt;&gt;&gt; from django.db.models import Sum, Avg, Max, Min, Count<br>&gt;&gt;&gt;<br>&gt;&gt;&gt; Book.objects.aggregate(<br>... total_pages=Sum(&#39;num_pages&#39;),<br>... avg_pages=Avg(&#39;num_pages&#39;),<br>... max_pages=Max(&#39;num_pages&#39;),<br>... min_pages=Min(&#39;num_pages&#39;)<br>... )<br># {&#39;total_pages&#39;: 1662, &#39;avg_pages&#39;: 332.4, &#39;max_pages&#39;: 412, &#39;min_pages&#39;: 210}</pre><pre>author = Author.objects.get(name__istartswith=&quot;jo&quot;)<br># &lt;Author: John J.&gt;<br>Book.objects.filter(author=author).aggregate(num_books=Count(&#39;id&#39;))<br># {&#39;num_books&#39;: 2}</pre><p><strong>Ordering:</strong></p><pre># Ascending order<br>Book.objects.order_by(&#39;title&#39;)<br># &lt;QuerySet [&lt;Book: A Tale of Tales&gt;, &lt;Book: Becoming John&gt;, &lt;Book: Living the Life&gt;, &lt;Book: New Beginnings&gt;, &lt;Book: Secrets Unknown&gt;]&gt;</pre><pre># Descending order<br>Book.objects.order_by(&#39;-title&#39;)<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: New Beginnings&gt;, &lt;Book: Living the Life&gt;, &lt;Book: Becoming John&gt;, &lt;Book: A Tale of Tales&gt;]&gt;</pre><p><strong>Limiting:</strong></p><p>We can use .distinct() to remove duplicate records</p><pre>Author.objects.distinct()<br># &lt;QuerySet [&lt;Author: John J.&gt;, &lt;Author: Peter P.&gt;, &lt;Author: Andrew A.&gt;]&gt;<br><br>Author.objects.values(&#39;age&#39;).distinct()<br># &lt;QuerySet [{&#39;age&#39;: 44}, {&#39;age&#39;: 31}]&gt;</pre><p><strong>Values:</strong></p><ul><li>.values(*fields): returns a dictionary with specified fields</li></ul><h4><strong>Complex Queries:</strong></h4><p><strong>Q Objects:</strong></p><p>Q objects are used to build more complex queries with <strong>AND (&amp;)</strong>, <strong>OR (|)</strong>, and <strong>NOT (~) </strong>logic. They allow you to create filters that combine multiple conditions in a flexible way, which can&#39;t be easily done with normal query filters.</p><pre>from django.db.models import Q<br><br># filter books that starts with &quot;un&quot; OR books that are best sellers <br>Book.objects.filter(Q(title__istartswith=&#39;un&#39;) | Q(best_seller=True))<br># &lt;QuerySet [&lt;Book: Secrets Unknown&gt;, &lt;Book: A Tale of Tales&gt;, &lt;Book: Living the Life&gt;]&gt;</pre><p><strong>F Objects:</strong></p><p>F objects are used to reference fields in database queries without pulling their values into Python memory. This allows you to compare, update, or manipulate field values directly in the database. They are especially useful when you want to perform database-level operations between fields or update fields relative to their current values.</p><pre># add 30 to all the num_pages field <br>Book.objects.update(num_pages=F(&#39;num_pages&#39;) + 30)<br>5<br>&gt;&gt;&gt;book = Book.objects.all()<br>&gt;&gt;&gt; book[0]<br>&lt;Book: Secrets Unknown&gt;<br>&gt;&gt;&gt; book[0].num_pages<br>430</pre><h4><strong>Annotations:</strong></h4><p>Annotations<strong> </strong>allow you to add calculated fields to your querysets. This is useful when you need to perform operations on model fields (such as counting, summing, or performing calculations) and attach the result to each object in the queryset.</p><p>Annotations are typically used with <strong>aggregate functions</strong> (e.g., Count, Sum, Avg, Max, Min) and <strong>F objects</strong> for more complex calculation</p><pre>authors = Author.objects.annotate(total_pages=Sum(&#39;books__num_pages&#39;))<br># &lt;QuerySet [&lt;Author: John J.&gt;, &lt;Author: Peter P.&gt;, &lt;Author: Andrew A.&gt;]&gt;<br>&gt;&gt;&gt; authors[0]<br>&lt;Author: John J.&gt;<br>&gt;&gt;&gt; authors[0].name<br>&#39;John J.&#39;<br>&gt;&gt;&gt; authors[0].total_pages<br>650</pre><h4><strong>Caching:</strong></h4><ul><li><strong>QuerySet Caching</strong>: Once a QuerySet is evaluated, the results are cached. Subsequent accesses to the QuerySet do not hit the database again unless explicitly refreshed or modified.</li></ul><h3><strong>Conclusion</strong></h3><p>Django’s Object-Relational Mapping (ORM) is a powerful tool that abstracts away the complexities of interacting with databases, allowing developers to write Python code instead of raw SQL queries. By leveraging models, QuerySets, and managers like .objects, Django&#39;s ORM provides a high-level interface for querying and manipulating data. With support for a wide range of databases and features like filtering, aggregation, field lookups, and complex queries using Q and F objects, the ORM simplifies database operations, making development faster, more secure, and easier to maintain.</p><p>Whether you are performing simple queries or handling complex database logic, Django ORM offers a robust and intuitive way to manage your data. As you continue building with Django, mastering its ORM will enhance the efficiency and scalability of your applications.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a330e5d54b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Swagger Documentation in Django Rest Framework: A Guide to drf-yasg and drf-spectacular]]></title>
            <link>https://medium.com/@ukemeboswilson/creating-swagger-documentation-in-django-rest-framework-a-guide-to-drf-yasg-and-drf-spectacular-216fc41d47de?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/216fc41d47de</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 23:10:06 GMT</pubDate>
            <atom:updated>2024-09-01T23:10:06.805Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swagger</strong> is a widely used tool for designing, building, and documenting RESTful APIs. It provides a comprehensive suite of features that streamline the API development process. One of its standout capabilities is the automatic generation of interactive API documentation. This documentation is highly valuable as it allows developers to not only visualize but also interact with the API endpoints directly through a web browser.</p><p>API documentation is crucial for teams working on different parts of the application, especially when APIs are consumed by other developers.</p><p>By using Swagger, the documentation is always up-to-date with the code, reducing the chances of discrepancies between the API implementation and its documentation.</p><p>Lets consider this analogy</p><p>Imagine you have a new state of the art microwave. To understand how to use it, you would consult the user manual, which explains each feature, provides step-by-step instructions, and even allows you to see the microwave in action through diagrams and illustrations. The manual helps you understand how to operate it, what buttons to press, and how to troubleshoot common issues.</p><p>Similarly, DRF Swagger documentation acts as a comprehensive guide for your API. It provides a clear and interactive overview of your API’s endpoints, detailing what each one does, what inputs are required, and what responses you can expect. Just like the user manual for your microwave, the Swagger documentation makes it easier for developers to understand how to use your API, interact with its features, and test different functionalities.</p><p>In DRF, you can create swagger documentation using several swagger generators such as drf-yasg, drf-spectacular, Django REST Swagger, CoreAPI/AutoSchema, drf-openapi etc.</p><p>drf-yasg and drf-spectacular are the most popular and modern choices for Swagger/OpenAPI documentation in DRF projects</p><p>To demonstrate the swagger documentation in DRF, lets quickly set up a Django project and a Django app called docProject and docApp respectively. (if you need more insight into Django projects and Django Apps, check <a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">here</a>)</p><pre>$ pip install django<br>$ pip install djangorestframework</pre><pre>$ django-admin startproject docProject .<br>$ python manage.py startapp docApp</pre><p>Add the docApp to the list of installed apps in settings.py file of the docProject directory</p><pre># settings.py<br><br>INSTALLED_APPS = [<br>    &quot;django.contrib.admin&quot;,<br>    &quot;django.contrib.auth&quot;,<br>    &quot;django.contrib.contenttypes&quot;,<br>    &quot;django.contrib.sessions&quot;,<br>    &quot;django.contrib.messages&quot;,<br>    &quot;django.contrib.staticfiles&quot;,<br>    &#39;rest_framework&#39;, # new<br>    &#39;docApp&#39;  # new<br>]</pre><p>Set up a model. (check <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">here</a> for more details about models)</p><pre># docApp/models.py<br><br>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br>    <br>    def __str__(self):<br>        return self.name<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    author = models.ForeignKey(Author, related_name=&#39;books&#39;, on_delete=models.CASCADE)<br>    num_pages = models.IntegerField()<br>    published = models.BooleanField(default=False) <br><br>    def __str__(self):<br>        return self.title</pre><p>Set up serializers. (check <a href="https://medium.com/@ukemeboswilson/mastering-django-rest-framework-an-in-depth-guide-to-serializers-5e6b94530c7a">here</a> for more details about serializers)</p><pre># docApp/serializers.py<br><br>from rest_framework import serializers<br>from .models import Book, Author<br><br>class AuthorSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Author<br>        fields = [&#39;id&#39;, &#39;name&#39;]<br><br>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;author&#39;, &#39;num_pages&#39;, &#39;published&#39;]</pre><p>Set up views: (check <a href="https://medium.com/@ukemeboswilson/understanding-and-implementing-views-in-django-rest-framework-2184eceb7336">here</a> for more details about views)</p><pre># docApp/views.py<br><br>from rest_framework import viewsets<br><br>from .models import Book, Author<br>from .serializers import BookSerializer, AuthorSerializer<br><br>class BookModelViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br>    <br>    <br>class AuthorModelViewSet(viewsets.ModelViewSet):<br>    queryset = Author.objects.all()<br>    serializer_class = AuthorSerializer</pre><p>Set up urls: (check <a href="https://medium.com/@ukemeboswilson/mastering-url-routing-in-django-rest-framework-a-comprehensive-guide-4c7bc85d516d">here</a> for more details about views)</p><pre># docApp/urls.py<br><br>from django.urls import path, include<br>from .views import BookModelViewSet, AuthorModelViewSet<br><br>from rest_framework.routers import DefaultRouter<br><br>router = DefaultRouter()<br><br>router.register(r&quot;books&quot;, BookModelViewSet, basename=&quot;book&quot;)<br>router.register(r&quot;authors&quot;, AuthorModelViewSet, basename=&quot;author&quot;)<br><br>urlpatterns = [<br>    path(&quot;&quot;, include(router.urls)),<br>]</pre><p>Add the app to the project urls.py</p><pre># docProject/urls.py<br><br>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;&quot;, include(&quot;docApp.urls&quot;)),<br>    <br>]</pre><p>Run migrations</p><pre>$ python manage.py makemigrations  <br>$ python manage.py migrate</pre><p>Run server</p><pre>$ python manage.py runserver</pre><h3><strong>drf-yasg (Django REST Framework — Yet Another Swagger Generator)</strong></h3><p>This a popular tool used to generate real-time, interactive API documentation for Django REST Framework (DRF) projects. It focuses on making it easy to generate OpenAPI 2.0 (formerly known as Swagger) documentation for DRF projects. It offers a straightforward setup and is designed to be user-friendly with minimal configuration.</p><p>It is easy to set up and use, making it a good choice for smaller projects or those looking for quick Swagger integration.</p><pre>$ pip install drf-yasg</pre><p>Update the installed apps list</p><pre># docProject/settings.py<br><br>INSTALLED_APPS = [<br>    ...<br>    &#39;drf_yasg&#39;, # new<br>]</pre><p>Update the docProject/urls.py file</p><pre>from django.contrib import admin<br>from django.urls import path, include<br><br>from rest_framework import permissions<br>from drf_yasg.views import get_schema_view<br>from drf_yasg import openapi<br><br>schema_view = get_schema_view(<br>   openapi.Info(<br>      title=&quot;Your API Title&quot;,<br>      default_version=&#39;v1&#39;,<br>      description=&quot;Test description&quot;,<br>      terms_of_service=&quot;https://www.google.com/policies/terms/&quot;,<br>      contact=openapi.Contact(email=&quot;contact@yourapi.local&quot;),<br>      license=openapi.License(name=&quot;BSD License&quot;),<br>   ),<br>   public=True,<br>   permission_classes=(permissions.AllowAny,),<br>)<br><br>urlpatterns = [<br>    path(&quot;admin/&quot;, admin.site.urls),<br>    path(&quot;&quot;, include(&quot;docApp.urls&quot;)),<br>    path(&#39;swagger/&#39;, schema_view.with_ui(&#39;swagger&#39;, cache_timeout=0), name=&#39;schema-swagger-ui&#39;),<br>    path(&#39;redoc/&#39;, schema_view.with_ui(&#39;redoc&#39;, cache_timeout=0), name=&#39;schema-redoc&#39;),<br>    path(&#39;swagger.json&#39;, schema_view.without_ui(cache_timeout=0), name=&#39;schema-json&#39;),<br>    <br>]</pre><p><strong>title</strong>: Specifies the title of your API documentation.</p><p><strong>default_version</strong>: Defines the version of your API. This is useful if you have multiple versions of your API, allowing you to differentiate between them.</p><p><strong>description</strong>: Provides a brief description of your API. This can be an overview of what the API does, its key features, or any other relevant information.</p><p><strong>terms_of_service</strong>: A URL pointing to the terms of service for your API. This is optional but can be included if you want to provide legal terms for using the API.</p><p><strong>contact</strong>: Provides contact information for the API maintainers. This is typically used to provide an email address where users can send feedback or report issues.</p><p><strong>license</strong>: Specifies the license under which the API is distributed. This can be important for users to understand the legal permissions they have when using the API.</p><p>Visiting <a href="http://127.0.0.1:8000/swagger/">http://127.0.0.1:8000/swagger/</a> will display all the endpoints defined in the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLmHb1PTQGcqg9eEHAPGJg.png" /></figure><h3><strong>DRF Spectacular</strong></h3><p>This an extension for Django Rest Framework (DRF) that helps generate OpenAPI 3.0 documentation. It provides a streamlined and customizable way to automatically document your API endpoints.</p><p>It has a strong focus on accuracy, flexibility, and extensibility and aims to provide a more complete and reliable solution for documenting complex APIs (like nested serializers, custom fields, etc.).</p><pre>$ pip install drf-spectacular</pre><p>Update the settings.py file</p><pre># docProject/settings.py<br><br>INSTALLED_APPS = [<br>    ...<br>    &#39;drf_spectacular&#39;,<br>]<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_SCHEMA_CLASS&#39;: &#39;drf_spectacular.openapi.AutoSchema&#39;,<br>}<br><br>SPECTACULAR_SETTINGS = {<br>    &#39;TITLE&#39;: &#39;My API&#39;,<br>    &#39;DESCRIPTION&#39;: &#39;API documentation&#39;,<br>    &#39;VERSION&#39;: &#39;1.0.0&#39;,<br>}</pre><p>Update the docproject/urls.py file</p><pre>from django.contrib import admin<br>from django.urls import path, include<br>from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView<br><br>urlpatterns = [<br>    path(&quot;admin/&quot;, admin.site.urls),<br>    path(&quot;&quot;, include(&quot;docApp.urls&quot;)),<br>    path(&#39;api/schema/&#39;, SpectacularAPIView.as_view(), name=&#39;schema&#39;),<br>    path(&#39;api/docs/&#39;, SpectacularSwaggerView.as_view(url_name=&#39;schema&#39;), name=&#39;swagger-ui&#39;),<br>    <br>]</pre><p>Visiting <a href="http://127.0.0.1:8000/api/docs/">http://127.0.0.1:8000/api/docs/</a> will display all the endpoints defined in the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*VuN1VvzNXvzy_n1ZPE9j6g.png" /></figure><h4><strong>Description in views.</strong></h4><p>For either methods, you can add some descriptions for the endpoints to further explain what the endpoint is doing. This is done by passing a string to the view class.</p><pre># docApp/views.py<br><br>class BookModelViewSet(viewsets.ModelViewSet):<br>    &quot;This is a text description that help to explain this view&quot;<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*K0WAZ_KPCxhLzowXbU2JJw.png" /></figure><h3><strong>Conclusion</strong></h3><p>In this guide, we explored how to integrate Swagger documentation into a Django Rest Framework (DRF) project using two popular tools: drf-yasg and drf-spectacular. Both tools offer robust solutions for generating interactive and user-friendly API documentation, enhancing the development experience and making it easier for users to understand and interact with your API.</p><p>By following the steps outlined, you have set up a Django project with dynamic API documentation that can greatly improve collaboration and development efficiency. Whether you choose drf-yasg for its simplicity or drf-spectacular for its advanced capabilities, integrating Swagger documentation will provide a valuable resource for both developers and users of your API.</p><p>Implementing these tools ensures your API documentation is always up-to-date and reflects the current state of your code, minimizing discrepancies and enhancing overall API usability.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=216fc41d47de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Your APIs: Authentication and Authorization in Django Rest Framework]]></title>
            <link>https://medium.com/@ukemeboswilson/securing-your-apis-authentication-and-authorization-in-django-rest-framework-138293e74b75?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/138293e74b75</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 22:25:46 GMT</pubDate>
            <atom:updated>2024-10-13T10:43:01.729Z</atom:updated>
            <content:encoded><![CDATA[<p>Authentication and Authorization in Django Rest Framework (DRF) is a crucial aspect of securing your API.</p><p>Authentication involves verifying the identity of a user or client making a request to an API. It involves associating an incoming request with a set of identifying credentials, such as a user or a token.</p><p>Authorization in Django Rest Framework (DRF) refers to the process of determining whether an authenticated user has permission to perform a specific action on a resource.</p><p>DRF provides several ways to handle authorization, primarily through permissions. DRF provides a set of built-in permission classes that you can use or customize according to your needs.</p><p>Permissions and authentications are typically set at the view level and can be applied globally in the settings or on a per-view basis.</p><p><strong>Lets consider an analogy</strong>.</p><p>You’re organizing a part and you have a guest list, a bouncer at the door, and different areas within the house that are accessible to different guests based on their relationship with you.</p><ul><li><strong>Authentication</strong> is like the bouncer at the door. When a person arrives, the bouncer checks their ID (identity) to verify that they are on the guest list. If they are, they’re allowed into the party; if not, they’re turned away. In DRF, authentication is the process of verifying who the user or client is before granting access to the API.</li><li><strong>Permissions</strong> are like the rules you set for different areas in the house. Some guests can access the VIP lounge, others can only stay in the main party area, and a few close friends might have access to your private study. In DRF, permissions determine what authenticated users are allowed to do. For example, some users might only be allowed to view the content (read-only), while others might have permission to make changes (write access).</li></ul><h3><strong>Types of Authentication in DRF.</strong></h3><ul><li>Basic Authentication</li><li>Token Authentication</li><li>Session Authentication</li><li>JSON Web Token (JWT) Authentication</li><li>Oauth2.0 Authentication</li><li>Custom Authentication</li></ul><h3><strong>Types of Permissions.</strong></h3><ul><li>AllowAny</li><li>IsAuthenticated</li><li>IsAdminUser</li><li>IsAuthenticatedOrReadOnly</li></ul><h3><strong>Demo SetUp</strong></h3><p>To demonstrate these authentications and permissions, let’s quickly set up a demo project.</p><pre>$ pip install Django<br>$ pip install djangorestframework</pre><p>Create a Django project and a Django app called authProject and authApp respectively. (if you need more insight into Django projects and Django Apps, check <a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">here</a>)</p><pre>$ django-admin startproject authProject .<br>$ python manage.py startapp authApp</pre><p>set up model: (check <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">here</a> for more details about models)</p><pre># authApp/models.py<br><br>from django.db import models<br>from django.contrib.auth.models import User<br><br>    <br>class Blog(models.Model):<br>    title = models.CharField(max_length=250, null=False)<br>    author = models.ForeignKey(User,on_delete=models.CASCADE)<br>    content = models.TextField()<br>    <br>    def __str__(self):<br>        return self.title</pre><p>set up serializers: (check <a href="https://medium.com/@ukemeboswilson/mastering-django-rest-framework-an-in-depth-guide-to-serializers-5e6b94530c7a">here</a> for more details about serializers)</p><pre># authApp/serializers.py<br><br>from rest_framework import serializers<br>from django.contrib.auth.models import User<br><br>from .models import Blog<br><br>class UserRegistrationSerializer(serializers.ModelSerializer):<br>    password = serializers.CharField(write_only=True)<br>    <br>    class Meta:<br>        model = User<br>        fields = [&quot;username&quot;, &quot;email&quot;, &quot;password&quot;]<br>        <br>    def create(self, validated_data):<br>        user = User.objects.create_user(<br>            username=validated_data[&#39;username&#39;],<br>            email=validated_data[&#39;email&#39;], <br>            password=validated_data[&#39;password&#39;] <br>        )<br>        <br>        return user<br><br>class UserLoginSerializer(serializers.Serializer):<br>    username = serializers.CharField()<br>    password = serializers.CharField(write_only=True)<br><br>        <br><br>class BlogSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Blog<br>        fields = [&quot;id&quot;, &quot;title&quot;, &quot;author&quot;, &quot;content&quot;]</pre><p>set up views: (check <a href="https://medium.com/@ukemeboswilson/understanding-and-implementing-views-in-django-rest-framework-2184eceb7336">here</a> for more details about views)</p><pre># authApp/views.py<br><br>from rest_framework import viewsets, status<br>from rest_framework.response import Response<br>from django.contrib.auth import authenticate, login<br>from .serializers import UserRegistrationSerializer, UserLoginSerializer, BlogSerializer<br>from .models import Blog<br><br>class UserViewSet(viewsets.ViewSet):<br>    <br>    def register(self, request):<br>        serializer = UserRegistrationSerializer(data=request.data)<br>        if serializer.is_valid():<br>            user = serializer.save()<br>            return Response({&quot;message&quot;: f&#39;User {user.username} created successfully.&#39;}, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>        <br>    def login(self, request):<br>        serializer = UserLoginSerializer(data=request.data)<br>        if serializer.is_valid():<br>            username = serializer.validated_data[&#39;username&#39;]<br>            password = serializer.validated_data[&#39;password&#39;]<br>            <br>            user = authenticate(request, username=username, password=password)<br>            <br>            if user:<br>                login(request, user)<br>                return Response({&#39;message&#39;: f&#39;Welcome, {user.username}!&#39;}, status=status.HTTP_200_OK)<br>            else:<br>                return Response({&#39;error&#39;: &#39;Invalid login credentials.&#39;}, status=status.HTTP_401_UNAUTHORIZED)<br>        <br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br>class BlogViewSet(viewsets.ModelViewSet):<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><p>set up urls: (check <a href="https://medium.com/@ukemeboswilson/mastering-url-routing-in-django-rest-framework-a-comprehensive-guide-4c7bc85d516d">here</a> for more details about views)</p><pre># authApp/urls.py<br><br>from django.urls import path, include<br>from rest_framework import routers<br>from .views import UserViewSet, BlogViewSet<br><br>router = routers.DefaultRouter()<br><br>router.register(r&#39;blog&#39;, BlogViewSet)<br><br>user_register_viewset = UserViewSet.as_view({<br>    &#39;post&#39;: &#39;register&#39;<br>})<br><br>user_login_viewset = UserViewSet.as_view({<br>    &#39;post&#39;: &#39;login&#39;<br>})<br><br>urlpatterns = [<br>    path(&#39;api/register/&#39;, user_register_viewset, name=&quot;register&quot;),<br>    path(&#39;api/login/&#39;, user_login_viewset, name=&quot;login&quot;),<br>    path(&quot;&quot;, include(router.urls))<br>]</pre><p>set up Admin:</p><pre># authApp/admin.py<br><br>from django.contrib import admin<br><br>from .models import Blog<br><br>@admin.register(Blog)<br>class BlogAdmin(admin.ModelAdmin):<br>    list_display = [&quot;title&quot;, &quot;author&quot;, &quot;content&quot;]<br>    search_fields = [&quot;title&quot;, &quot;author&quot;]</pre><p>set up project urls:</p><pre># authProject/urls.py<br><br>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;&quot;, include(&#39;authApp.urls&#39;))<br>]<br><br></pre><p>set up settings:</p><pre># authProject/settings.py<br><br>INSTALLED_APPS = [<br>    &quot;django.contrib.admin&quot;,<br>    &quot;django.contrib.auth&quot;,<br>    &quot;django.contrib.contenttypes&quot;,<br>    &quot;django.contrib.sessions&quot;,<br>    &quot;django.contrib.messages&quot;,<br>    &quot;django.contrib.staticfiles&quot;,<br>    &#39;rest_framework&#39;, # new<br>    &#39;authApp&#39;, # new<br>]</pre><p>run migrations</p><pre>$ python manage.py makemigrations  <br>$ python manage.py migrate</pre><p>Next, we create two users. One admin user and one normal user.</p><p>Admin user:</p><pre>$ python manage.py createsuperuser</pre><p>Normal user:</p><pre>$ python manage.py runserver</pre><p>Visit “<a href="http://127.0.0.1:8000/api/register/">http://127.0.0.1:8000/api/register/</a>”. In the content tab, fill in the data below and click POST</p><pre>{<br>    &quot;username&quot;: &quot;ukeme&quot;,<br>    &quot;email&quot;: &quot;ukeme@ukeme.com&quot;,<br>    &quot;password&quot;: &quot;qwerty01&quot;<br>}</pre><p>Let’s start demonstrating the permissions</p><h3><strong>Permissions:</strong></h3><h4>Allow Any:</h4><p>This allows unrestricted access to any view or endpoint. No Authentication or Authorization checks are performed. This is the default if no other permission class is set.</p><p>Project level permission:</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.AllowAny&#39;,<br>    ],<br>}</pre><p>View level permission:</p><pre># authApp/views.py<br><br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.AllowAny]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><h4>IsAuthenticated:</h4><p>This is used to restrict access to views or viewsets to authenticated users only. If the user is not authenticated, the permission class denies access.</p><p>Project level permission:</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticated&#39;,<br>    ],<br>}</pre><p>View level permission:</p><pre># authApp/views.py<br><br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.IsAuthenticated]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><h4>IsAdminUser:</h4><p>This allows access only to users with admin status. It restricts access to API views or viewsets to users who have admin status.</p><p>It checks if the user has admin status by evaluating the “is_staff” attribute of the User model</p><p>Project level permission:</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAdminUser&#39;,<br>    ],<br>}</pre><p>View level permission:</p><pre># authApp/views.py<br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.IsAdminUser]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><h4>IsAuthenticatedOrReadOnly:</h4><p>This provides a mixed level of access control. It allows unauthenticated users to read (GET, HEAD, OPTIONS) data but requires authentication for any write operations (POST, PUT, PATCH, DELETE). This is useful for APIs where you want to allow public access to view data but restrict modification of that data to authenticated users only.</p><p>Project level permission:</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;: [<br>        &#39;rest_framework.permissions.IsAuthenticatedOrReadOnly&#39;,<br>    ],<br>}</pre><p>View level permission:</p><pre># authApp/views.py<br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.IsAuthenticatedOrReadOnly]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><h3>Authentications</h3><h4>1. Basic Authentication:</h4><p>Basic Authentication allows users to authenticate by sending their credentials (username and password) in the HTTP headers. This is generally considered less secure and is generally only appropriate for testing.</p><p>If you must use BasicAuthentication in production, this should be done over https and not http.</p><p>The client encodes the username and password into a base64 string and sends it in the Authorization header of the HTTP request. The server decodes the base64 string to retrieve the username and password. It then verifies these credentials against the database. If the credentials are valid, the request is authenticated; otherwise, it is denied.</p><p>Project level authentication</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.BasicAuthentication&#39;,<br>    ],<br>}</pre><p>view level authentication</p><pre># views.py<br><br>from rest_framework.authentication import BasicAuthentication<br><br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.IsAuthenticated]<br>    authentication_classes = [BasicAuthentication]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer</pre><p>visit: <a href="http://localhost:8000/blog/">http://localhost:8000/blog/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*MVUocWgMXvTDcUgbDTS9Hw.png" /><figcaption>basic authentication</figcaption></figure><p>You can login with either the normal user or the admin user we created earlier.</p><h4>2. Token Authentication:</h4><p>This uses tokens to manage user sessions and access control. Instead of sending username and password credentials with each request, clients receive a token after authentication, which is then used to access protected resources.</p><p>When a user successfully logs in, they receive an authentication token. This token is a string that represents the user’s credentials. It is generated by the server and sent back to the client.</p><p>The client includes this token in the Authorization header of subsequent HTTP requests. The token is usually sent using the format: Authorization: <strong>Token &lt;your-token-here&gt;</strong></p><pre>$ pip install djangorestframework authtoken</pre><pre># settings.py<br><br>INSTALLED_APPS = [<br>    # Other installed apps<br>    &#39;rest_framework&#39;,<br>    &#39;rest_framework.authtoken&#39;,<br>]<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.TokenAuthentication&#39;,<br>    ],<br>}</pre><pre># authApp/urls.py<br><br>from rest_framework.authtoken.views import obtain_auth_token<br><br>urlpatterns = [<br>    path(&#39;api-token-auth/&#39;, obtain_auth_token, name=&#39;api_token_auth&#39;),<br>    # Other URL patterns<br>]</pre><pre>$ python manage.py migrate</pre><pre># authApp/views.py<br><br>from rest_framework.authtoken.models import Token<br><br><br>class UserViewSet(viewsets.ViewSet):<br>    def login(self, request):<br>        serializer = UserLoginSerializer(data=request.data)<br>        if serializer.is_valid():<br>            username = serializer.validated_data[&#39;username&#39;]<br>            password = serializer.validated_data[&#39;password&#39;]<br>            <br>            user = authenticate(request, username=username, password=password)<br>            <br>            if user:<br>                login(request, user)<br>                token, created = Token.objects.get_or_create(user=user)<br>                return Response({&#39;token&#39;: token.key, &#39;message&#39;: f&#39;Welcome, {user.username}!&#39;}, status=status.HTTP_200_OK)<br>                <br>            else:<br>                return Response({&#39;error&#39;: &#39;Invalid login credentials.&#39;}, status=status.HTTP_401_UNAUTHORIZED)<br>        <br>    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br><br><br>class BlogViewSet(viewsets.ModelViewSet):<br>    permission_classes = [permissions.IsAuthenticated]<br>    queryset = Blog.objects.all()<br>    serializer_class = BlogSerializer<br><br></pre><p>This will return an authentication token.</p><p>You can now access the blog endpoint by passing the token in the headers</p><pre>curl -H &quot;Authorization: Token &lt;token&gt;&quot; http://127.0.0.1:8000/blog/</pre><h4>3. Session Authentication:</h4><p>This uses the session framework to manage user sessions and authentication.</p><p>When a user logs in, a session is created for that user. The session ID is stored in a cookie on the client side.</p><p>For each subsequent request, the client includes this session ID cookie, which is sent to the server. The server uses this session ID to retrieve session data and check if the user is authenticated.</p><p>Session Authentication is beneficial for applications that already use Django’s session management system and where maintaining session state on the server is acceptable.</p><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework.authentication.SessionAuthentication&#39;,<br>    ],<br>}</pre><h4>4. JSON Web Token (JWT) Authentication:</h4><p>This provides a stateless (server does not need to maintain session data) way to authenticate users by issuing a token upon successful login, which clients can use in subsequent requests to access protected resources.</p><p>If the credentials are valid, the server generates a JWT, which includes encoded information such as the user ID, expiration time, and possibly other claims.</p><p>Authorization format:<strong> Bearer &lt;your-jwt-token&gt;</strong></p><pre>$ pip install djangorestframework-simplejwt</pre><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>        # Optionally add other authentication methods<br>    ],<br>}</pre><pre># authApp/urls.py<br><br>from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView<br><br><br><br>urlpatterns = [<br>    path(&#39;api/token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),<br>    path(&#39;api/token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>    # Other URL patterns<br>]</pre><p>visit <a href="http://127.0.0.1:8000/api/token/"><em>http://127.0.0.1:8000/api/token/</em></a> fill in the username and password.</p><p>This will generate</p><pre>{<br>    &quot;refresh&quot;: generated refresh token,<br>    &quot;access&quot;: generated access token<br>}</pre><p>You can now view the blogs with</p><pre>curl -H &quot;Authorization: Bearer your-access-token&quot; http://127.0.0.1:8000/blog/</pre><p>Additional settings</p><pre># settings.py<br><br>from datetime import timedelta<br><br>SIMPLE_JWT = {<br>  &#39;ACCESS_TOKEN_LIFETIME&#39;: timedelta(minutes=5),<br>  &#39;REFRESH_TOKEN_LIFETIME&#39;: timedelta(days=1),<br>  &#39;ROTATE_REFRESH_TOKENS&#39;: True,<br>  &#39;BLACKLIST_AFTER_ROTATION&#39;: True,<br>  &#39;ALGORITHM&#39;: &#39;HS256&#39;,<br>  &#39;SIGNING_KEY&#39;: SECRET_KEY,<br>  &#39;AUTH_HEADER_TYPES&#39;: (&#39;Bearer&#39;,),<br>  # Other options…<br>}<br><br># https://django-rest-framework-simplejwt.readthedocs.io/en/latest/</pre><h4>5. OAuth2.0 Authentication:</h4><p>OAuth 2.0 is an authorization framework that allows applications to grant limited access to user accounts on an HTTP service, such as Facebook, GitHub, Google, etc., without exposing the user’s credentials. It’s widely used for enabling secure delegated access and is the backbone of many “login with [service]” functionalities.</p><pre>$ pip install django-oauth-toolkit</pre><p>Navigate to the Django admin interface (http://127.0.0.1:8000/admin).</p><p>Find “Applications” under the OAuth2 Provider section.</p><p>Add a new application with the following details:</p><ul><li><strong>Client type:</strong> Confidential</li><li><strong>Authorization grant type:</strong> Authorization code</li><li><strong>Name:</strong> My App (or any name you prefer)</li><li><strong>Redirect URIs:</strong> <a href="http://127.0.0.1:8000/callback/">http://127.0.0.1:8000/callback/</a></li></ul><pre># settings.py<br><br>INSTALLED_APPS = [<br>    # Other apps...<br>    &#39;oauth2_provider&#39;,<br>    &#39;rest_framework&#39;,<br>]<br><br>MIDDLEWARE = [<br>    # Other middleware...<br>    &#39;oauth2_provider.middleware.OAuth2TokenMiddleware&#39;,<br>]<br><br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>        &#39;oauth2_provider.contrib.rest_framework.OAuth2Authentication&#39;,<br>    ],<br>}<br><br>OAUTH2_PROVIDER = {<br>    &#39;ACCESS_TOKEN_EXPIRE_SECONDS&#39;: 36000,<br>    &#39;AUTHORIZATION_CODE_EXPIRE_SECONDS&#39;: 600,<br>    &#39;OAUTH2_BACKEND_CLASS&#39;: &#39;oauth2_provider.oauth2_backends.OAuthLibCore&#39;,<br>    &#39;SCOPES&#39;: {&#39;read&#39;: &#39;Read scope&#39;, &#39;write&#39;: &#39;Write scope&#39;},<br>    &#39;CLIENT_ID_GENERATOR_CLASS&#39;: &#39;oauth2_provider.generators.ClientIdGenerator&#39;,<br>}<br><br></pre><pre># authApp/urls.py<br><br>from .views import start_oauth2_authorization, oauth_callback<br><br><br>urlpatterns = [<br>    path(&#39;o/&#39;, include(&#39;oauth2_provider.urls&#39;, namespace=&#39;oauth2_provider&#39;)),<br>    path(&#39;authorize/&#39;, start_oauth2_authorization, name=&#39;start_authorize&#39;),<br>    path(&#39;callback/&#39;, oauth_callback, name=&#39;oauth_callback&#39;),<br>    # Other URL patterns...<br>]</pre><pre># authApp/views.py<br><br>import base64<br>import hashlib<br>import os<br>from django.http import HttpResponse<br>import requests<br>from oauth2_provider.models import get_application_model<br><br>local_storage = {} # can use other database storage<br><br>def generate_code_verifier_and_code_challange():<br>    # # Generate code_verifier<br>    code_verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b&#39;=&#39;).decode(&#39;ascii&#39;)<br><br>    # Generate code_challenge<br>    code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).rstrip(b&#39;=&#39;).decode(&#39;ascii&#39;)<br><br>    return code_verifier, code_challenge<br><br>def generate_authorization_url(https://medium.com/request):<br>    <br>    code_verifier, code_challenge = generate_code_verifier_and_code_challange()<br>    session_key = request.session.session_key or request.session.create()<br>    local_storage[session_key] = code_verifier<br>    Application = get_application_model()<br>    application = Application.objects.get(name=&#39;My App&#39;)  # Replace &#39;My App&#39; with your app&#39;s name<br>    <br>    client_id = application.client_id<br>    redirect_uri = &#39;http://127.0.0.1:8000/callback/&#39;<br>    <br>    authorization_url = f&quot;http://127.0.0.1:8000/o/authorize/?response_type=code&amp;client_id={client_id}&amp;redirect_uri={redirect_uri}&amp;scope=read&amp;code_challenge={code_challenge}&amp;code_challenge_method=S256&quot;<br><br>    return authorization_url<br><br>def start_oauth2_authorization(request):<br>    try:<br>        authorization_url = generate_authorization_url(https://medium.com/request)<br>        return HttpResponse(f&quot;Authorization Url: &lt;a href=&#39;{authorization_url}&#39;&gt;Authorize&lt;/a&gt;&quot;)<br>    <br>    except Exception as e:<br>        return HttpResponse(f&quot;Authorization Failed: {e}&quot;)<br><br>def oauth_callback(request):<br><br>    code = request.GET.get(&#39;code&#39;)<br>    <br>    if not code:<br>        return HttpResponse(&#39;No code provided in the callback.&#39;)<br><br>    # Retrieve your application details<br>    Application = get_application_model()<br>    application = Application.objects.get(name=&#39;tt&#39;)  # Replace &#39;My App&#39; with your app&#39;s name<br><br>    # code_verifier, code_challenge = generate_code_verifier_and_code_challange()<br>    <br>    token_url = &#39;http://127.0.0.1:8000/o/token/&#39;  # The token endpoint<br>    client_id = application.client_id<br>    client_secret = application.client_secret<br>    redirect_uri = &#39;http://127.0.0.1:8000/callback/&#39;<br>    <br>    session_key = request.session.session_key<br>    code_verifier = local_storage.get(session_key)<br>    if not code_verifier:<br>        return HttpResponse(&#39;Code verifier not found.&#39;)<br><br>    response = requests.post(token_url, data={<br>        &#39;grant_type&#39;: &#39;authorization_code&#39;,<br>        &#39;code&#39;: code,<br>        &#39;redirect_uri&#39;: redirect_uri,<br>        &#39;client_id&#39;: client_id,<br>        &#39;client_secret&#39;: client_secret,<br>        &#39;code_verifier&#39;: code_verifier,<br>    })<br>    <br>    if response.status_code == 200:<br>        token_data = response.json()<br>        return HttpResponse(f&quot;Access Token: {token_data.get(&#39;access_token&#39;)}&quot;)<br>    else:<br>        return HttpResponse(f&quot;Failed to obtain token: {response.content}&quot;)</pre><pre>$ python manage.py migrate<br>$ python manage.py runserver</pre><p>Visit <a href="http://127.0.0.1:8000/authorize/">http://127.0.0.1:8000/authorize/</a> then click on the ‘authorize’ link displayed.</p><h4>6. <strong>Custom Authentication</strong>:</h4><p>If your application requires a unique authentication method, you can create a custom authentication class by subclassing BaseAuthentication and implementing the authenticate method.</p><p>You might want to implement custom authentication when:</p><ul><li><strong>Third-Party Authentication</strong>: You need to integrate with an external authentication service that requires a custom logic.</li><li><strong>Custom Tokens</strong>: You want to authenticate users with a token format or method that isn’t supported by default.</li><li><strong>Additional Security Measures</strong>: You have specific security protocols or checks that need to be incorporated into the authentication process.</li><li><strong>Multi-Factor Authentication (MFA)</strong>: You need to implement a multi-step authentication process.</li></ul><pre># settings.py<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;authApp.authentication.CustomTokenAuthentication&#39;,<br>    ),<br>}</pre><pre># authApp/authentication.py<br><br>from rest_framework.authentication import BaseAuthentication<br>from rest_framework.exceptions import AuthenticationFailed<br>from django.contrib.auth.models import User<br><br>class CustomTokenAuthentication(BaseAuthentication):<br>    def authenticate(self, request):<br>        token = request.META.get(&#39;HTTP_AUTHORIZATION&#39;)<br>        auth_header = request.META.get(&#39;HTTP_AUTHORIZATION&#39;)<br>        if not auth_header:<br>            return None<br>        <br>        try:<br>            # Assuming token format is &#39;Token &lt;token&gt;&#39;<br>            prefix, token = auth_header.split()<br>            if prefix.lower() != &#39;token&#39;:<br>                raise AuthenticationFailed(&#39;Invalid token prefix&#39;)<br>        except ValueError:<br>            raise AuthenticationFailed(&#39;Invalid token header&#39;)<br><br>        try:<br>            # Replace `auth_token` with your actual field if it&#39;s different<br>            user = User.objects.get(auth_token=token)<br>        except User.DoesNotExist:<br>            raise AuthenticationFailed(&#39;No such user&#39;)<br><br>        return (user, None)<br><br>        return (&quot;user&quot;, None)<br><br></pre><pre># authApp/views.py<br><br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework.permissions import IsAuthenticated<br><br>class CustomAuthView(APIView):<br>    permission_classes = [IsAuthenticated]<br><br>    def get(self, request):<br>        content = {&#39;message&#39;: &#39;This is a secure response.&#39;}<br>        return Response(content)</pre><pre>curl -H &quot;Authorization: Token your_token_here&quot; http://127.0.0.1:8000/custom-auth/</pre><h3>Conclusion:</h3><p>DRF’s authentication framework is versatile and extensible, allowing you to secure your API using a variety of authentication methods. Whether you need simple token-based authentication or a more complex scheme like JWT, DRF provides the tools necessary to implement secure and scalable authentication.</p><p>The best way to solidify your understanding of DRF Authentication and Authorization is through hands-on practice.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=138293e74b75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering URL Routing in Django REST Framework: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ukemeboswilson/mastering-url-routing-in-django-rest-framework-a-comprehensive-guide-4c7bc85d516d?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7bc85d516d</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[url]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 20:35:28 GMT</pubDate>
            <atom:updated>2024-11-04T07:37:33.031Z</atom:updated>
            <content:encoded><![CDATA[<p>Django Rest Framework (DRF) stands out as a powerful and flexible toolkit for building Web APIs in Django. When building APIs, Django Rest Framework (DRF) extends this routing system to make it easy to create RESTful endpoints.</p><p>Django’s URL routing system allows you to map URLs to views, enabling you to handle various HTTP methods (GET, POST, PUT, DELETE) and parameters.</p><p>URLs map incoming HTTP requests to the appropriate views, which handle the requests and return responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ji6Ihi7c8BqyMaxoFcaR0g.png" /></figure><p><strong>Let’s consider this analogy of a postal service to visualize DRF URLs.</strong></p><p>In a postal service, each house or building has a unique address. The post office receives letters and mails, sorts them, and sends each one to the correct address. After receiving the mail, the recipient can in turn send back another mail to the initial sender, and the post office will ensure the returned mail reaches the specific recipient.</p><p>In Django Rest Framework (DRF), each API endpoint has a unique URL, analogous to unique houses. This unique address helps identify the specific location where the mail (HTTP request) should be delivered. The router maps each URL to the appropriate view, acting like the post office. It receives incoming HTTP requests, determines the correct view to handle the request based on the URL, and sends the request to the appropriate view. Sending the mails corresponds to the HTTP requests, while the returned mails represent the HTTP responses.</p><h3>Types of URL Routing</h3><ol><li>Function-Based Views with urlpatterns</li><li>Basic URL Configurations with Class-Based API Views</li><li>Viewsets and Routers</li><li>Nested Routers</li><li>Custom Routers</li></ol><p>To demonstrate these views, lets quickly set up a Django project and a Django app called urlProject and urlApp respectively. (if you need more insight into Django projects and Django Apps, check <a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">here</a>)</p><pre>$ django-admin startproject urlProject .</pre><pre>$ python manage.py startapp urlApp</pre><p>Add the urlApp to the list of installed apps in settings.py file of the urlProject directory</p><pre>INSTALLED_APPS = [<br>    &quot;django.contrib.admin&quot;,<br>    &quot;django.contrib.auth&quot;,<br>    &quot;django.contrib.contenttypes&quot;,<br>    &quot;django.contrib.sessions&quot;,<br>    &quot;django.contrib.messages&quot;,<br>    &quot;django.contrib.staticfiles&quot;,<br>    &quot;rest_framework&quot;, # new<br>    &quot;urlApp&quot;  # new<br>]</pre><p>Set up a model. (check <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">here</a> for more details about models)</p><pre># urlApp/models.py<br><br>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br>    <br>    def __str__(self):<br>        return self.name<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    author = models.ForeignKey(Author, related_name=&#39;books&#39;, on_delete=models.CASCADE)<br>    num_pages = models.IntegerField()<br>    published = models.BooleanField(default=False) <br><br>    def __str__(self):<br>        return self.title</pre><p>Set up serializers. (check <a href="https://medium.com/@ukemeboswilson/mastering-django-rest-framework-an-in-depth-guide-to-serializers-5e6b94530c7a">here</a> for more details about serializers)</p><pre># urlApp/serializers.py<br><br>from rest_framework import serializers<br>from .models import Book, Author<br><br>class AuthorSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Author<br>        fields = [&#39;id&#39;, &#39;name&#39;]<br><br>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;author&#39;, &#39;num_pages&#39;, &#39;published&#39;]<br></pre><p>Set up the project urls.py</p><pre># urlProject/urls.py<br><br>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;&quot;, include(&quot;viewApp.urls&quot;))   <br>]</pre><h3><strong>1. Function-Based Views with </strong><strong>urlpatterns</strong></h3><p>This uses traditional function-based views to handle requests and defining URL patterns in the urlpatterns list for a simpler and more customized behavior.</p><pre># urlApp/views.py<br><br>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br><br>@api_view([&#39;GET&#39;, &#39;POST&#39;])<br>def book_list(request):<br>    if request.method == &#39;GET&#39;:<br>        books = Book.objects.all()<br>        serializer = BookSerializer(books, many=True)<br>        return Response(serializer.data, status=status.HTTP_200_OK)</pre><pre># urlApp/urls.py<br><br>from django.urls import path<br>from .views import book_list<br><br>urlpatterns = [<br>    path(&#39;books/&#39;, book_list, name=&#39;books&#39;),<br>]</pre><p>migrations</p><pre>python manage.py makemigrations</pre><pre>python manage.py migrate</pre><h3><strong>2. Basic URL Configurations with Class-Based API Views</strong></h3><p>This uses the class-based views (CBVs) for handling requests and defining URL patterns in the urlpatterns list.</p><pre># urlApp/views.py<br><br>from rest_framework.views import APIView, status<br>from rest_framework.response import Response<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookApiView(APIView):<br>    <br>    def get(self, request):<br>       books = Book.objects.all()<br>       serializer = BookSerializer(books, many=True)<br>       <br>       return Response({<br>           &quot;success&quot;: True,<br>           &quot;message&quot;: &quot;successful get&quot;,<br>           &quot;data&quot;: serializer.data<br>       }, status=status.HTTP_200_OK)<br><br></pre><pre># urlApp/urls.py<br><br>from django.urls import path<br>from .views import BookApiView<br><br>urlpatterns = [<br>    path(&#39;books/&#39;, BookApiView.as_view(), name=&#39;books&#39;),<br>]</pre><h3><strong>3. ViewSets and Routers</strong></h3><p>This automatically generate URL patterns for standard CRUD operations. The viewsets defines common actions (list, create, retrieve, update, delete) while the Router automatically generates the URL patterns.</p><pre># urlApp/views.py<br><br>from rest_framework import viewsets<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookModelViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><pre># urlApp/urls.py<br><br>from django.urls import path, include<br>from .views import BookModelViewSet<br><br>from rest_framework.routers import DefaultRouter<br><br>router = DefaultRouter()<br><br>router.register(r&quot;books&quot;, BookModelViewSet, basename=&quot;book&quot;)<br><br>urlpatterns = [<br>    path(&quot;&quot;, include(router.urls)),<br>]</pre><h3><strong>4. Nested Routers</strong></h3><p>Nested routers allow you to define URL patterns for nested resources in a hierarchical manner, making your API URLs more intuitive and organized</p><p>This allows the creation of URL patterns for resources with parent-child relationships.</p><pre>pip install drf-nested-routers</pre><pre># urlApp/views.py<br><br>from rest_framework import viewsets<br>from .models import Book, Author<br>from .serializers import BookSerializer, AuthorSerializer<br><br>class BookViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br>    <br>    def get_queryset(self):<br>        return Book.objects.filter(author_id=self.kwargs[&#39;author_pk&#39;])<br><br>class AuthorViewSet(viewsets.ModelViewSet):<br>    queryset = Author.objects.all()<br>    serializer_class = AuthorSerializer</pre><pre># urlApp/urls.py<br><br>from django.urls import path, include<br>from rest_framework.routers import DefaultRouter<br>from rest_framework_nested.routers import NestedDefaultRouter<br>from .views import BookViewSet, AuthorViewSet<br><br><br>router = DefaultRouter()<br>router.register(r&#39;authors&#39;, AuthorViewSet)<br><br>author_router = NestedDefaultRouter(router, r&#39;authors&#39;, lookup=&#39;author&#39;)<br>author_router.register(r&#39;books&#39;, BookViewSet, basename=&#39;author-books&#39;)<br><br>urlpatterns = [<br>    path(&quot;&quot;, include(router.urls)),<br>    path(&#39;&#39;, include(author_router.urls)),<br>]</pre><p>The NestedDefaultRouter generates nested URLs like <em>authors/&lt;author_pk&gt;/books/</em> , allowing access to books of a specific author.</p><h3><strong>5. Custom Routers</strong></h3><p>This gives you the ability to add more specific endpoints or actions to your API. This is done using the `@action` decorator from viewsets.</p><pre># urlApp/views.py<br><br>from rest_framework.decorators import action<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>from rest_framework import viewsets<br>from .models import Book, Author<br>from .serializers import BookSerializer, AuthorSerializer<br><br>class AuthorViewSet(viewsets.ModelViewSet):<br>    queryset = Author.objects.all()<br>    serializer_class = AuthorSerializer<br><br>    @action(detail=True, methods=[&#39;get&#39;])<br>    def books(self, request, pk=None):<br>        author = self.get_object()<br>        books = author.books.all()<br>        serializer = BookSerializer(books, many=True)<br>        return Response(serializer.data)<br><br><br>class BookViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br><br>    @action(detail=True, methods=[&#39;post&#39;])<br>    def publish(self, request, pk=None):<br>        book = self.get_object()<br>        book.published = True<br>        book.save()<br>        return Response({&#39;status&#39;: &#39;book published&#39;})<br><br></pre><pre># urlApp/urls.py<br><br>from rest_framework.routers import DefaultRouter<br>from django.urls import path, include<br>from .views import AuthorViewSet, BookViewSet<br><br>router = DefaultRouter()<br>router.register(r&#39;authors&#39;, AuthorViewSet)<br>router.register(r&#39;books&#39;, BookViewSet)<br><br>urlpatterns = [<br>    path(&#39;&#39;, include(router.urls)),<br>]</pre><p>You can specify whether the action applies to a single instance (detail=True) or the entire collection (detail=False) as well as the method that the action is being applied to.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, Django Rest Framework (DRF) provides a powerful and flexible way to manage URLs in your API. By leveraging viewsets and routers, you can easily define standard CRUD operations for your resources.</p><p>The use of viewsets allows you to encapsulate the logic for handling different HTTP methods in a single class, while routers automatically generate the necessary URL patterns.</p><p>For more customized and specific needs, the @action decorator allows you to add custom endpoints, enhancing the functionality of your API without complicating your URL configuration</p><p>The best way to solidify your understanding of DRF URL routing is through hands-on practice.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7bc85d516d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Implementing Views in Django Rest Framework]]></title>
            <link>https://medium.com/@ukemeboswilson/understanding-and-implementing-views-in-django-rest-framework-2184eceb7336?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2184eceb7336</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-views]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 00:41:49 GMT</pubDate>
            <atom:updated>2024-08-13T12:39:44.117Z</atom:updated>
            <content:encoded><![CDATA[<p>Django Rest Framework (DRF) stands out as a powerful and flexible toolkit for building Web APIs in Django, allowing developers to create performant and maintainable API endpoints with ease. One of the core components of DRF is the concept of views, which act as the bridge between HTTP requests and the underlying data models.</p><p>Django follows the <strong>Model-View-Template (MVT) </strong>architectural pattern which allows developers to build robust and scalable web applications efficiently. We earlier covered the <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">Model section</a> of it. We’ll be looking at the View component here.</p><p>The View in Django is responsible for handling the logic associated with processing a user’s request. It retrieves data from the Model and sends it to the Template. Views are Python functions or classes (Class-Based Views) that take a web request and return a web response.</p><p>This response can be the HTML contents of a web page, a redirect, a 404 error, an XML document, a JSON response etc. Views are usually put in a file called views.py located on your app’s folder (can be placed anywhere though).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztrZrQCJw-lSADq6H6JuGg.png" /></figure><p>Let’s consider this analogy:</p><p>Imagine a restaurant setting. The customer makes an order. The waiter takes the order to the chef/kitchen. The chef/kitchen prepares the food based on the customer’s order. After the food is prepared, the waiter takes the food right back to the customer.</p><p><strong>Customer Makes an Order:</strong></p><ul><li>This represents an HTTP Request from the user.</li></ul><p> <strong>Waiter Takes the Order:</strong></p><ul><li>The waiter represents the Django view handling the request.</li></ul><p> <strong>Chef/Kitchen Prepares the Food:</strong></p><ul><li>The chef/kitchen represents the business logic, such as database lookups and other Python processes.</li></ul><p> <strong>Waiter Delivers the Food:</strong></p><ul><li>The waiter (Django view) returns an HTTP response (food) to the user.</li></ul><h3>Types of Views:</h3><p>Views in DRF can be categorized into two main types: <strong>function-based views (FBVs)</strong> and <strong>class-based views (CBVs)</strong>.</p><p>To demonstrate these views, lets quickly set up a Django project and a Django app called viewProject and viewApp respectively. (if you need more insight into Django projects and Django Apps, check <a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">here</a>)</p><pre>django-admin startproject viewProject .</pre><pre>python manage.py startapp viewApp</pre><p>Add the viewApp to the list of installed apps in settings.py file of the viewProject directory</p><pre>INSTALLED_APPS = [<br>    &quot;django.contrib.admin&quot;,<br>    &quot;django.contrib.auth&quot;,<br>    &quot;django.contrib.contenttypes&quot;,<br>    &quot;django.contrib.sessions&quot;,<br>    &quot;django.contrib.messages&quot;,<br>    &quot;django.contrib.staticfiles&quot;,<br>    &quot;rest_framework&quot;, # new<br>    &quot;viewApp&quot;  # new<br>]</pre><p>Set up a model. (check <a href="https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588">here</a> for more details about models)</p><pre># models.py<br>from django.db import models<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=100)<br>    author = models.CharField(max_length=100)<br>    num_pages = models.IntegerField()<br><br>    def __str__(self):<br>        return self.title</pre><p>Set up a serializer. (check <a href="https://medium.com/@ukemeboswilson/mastering-django-rest-framework-an-in-depth-guide-to-serializers-5e6b94530c7a">here</a> for more details about serializers)</p><pre># serializers.py<br>from rest_framework import serializers<br>from .models import Book<br><br>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;author&#39;, &#39;num_pages&#39;]</pre><p>Set up urls.py</p><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;&quot;, include(&quot;viewApp.urls&quot;))   <br>]</pre><p>With these set up, let’s consider the two types of views</p><h3><strong>1. Function-Based Views (FBVs)</strong></h3><p>FBVs are simple Python functions that take a web request and return a web response. They provide a straightforward way to handle requests and are quite flexible. They are typically used for simpler use cases where the overhead of class-based views might not be necessary.</p><pre># views.py<br>from rest_framework.decorators import api_view<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br><br>@api_view([&#39;GET&#39;, &#39;POST&#39;])<br>def book_list(request):<br>    if request.method == &#39;GET&#39;:<br>        books = Book.objects.all()<br>        serializer = BookSerializer(books, many=True)<br>        return Response(serializer.data)<br>    <br>    if request.method == &#39;POST&#39;:<br>        serializer = BookSerializer(data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><pre># urls.py<br><br>from django.urls import path<br>from .views import book_list<br><br>urlpatterns = [<br>    path(&quot;view/&quot;, book_list, name=&quot;my-view&quot;),<br>]</pre><p>migrations</p><pre>python manage.py makemigrations</pre><pre>python manage.py migrate</pre><p><strong>Advantages of FBVs</strong></p><ul><li><strong>Simplicity</strong>: FBVs are simple and easy to understand, making them a good starting point for beginners.</li><li><strong>Flexibility</strong>: They provide fine-grained control over the request handling process.</li></ul><p><strong>Disadvantages of FBVs</strong></p><ul><li><strong>Code Duplication</strong>: Handling different HTTP methods can lead to duplicated code.</li><li><strong>Less Reusability</strong>: FBVs can become less reusable and harder to maintain as the application grows.</li></ul><h3><strong>2. Class-Based Views (CBVs)</strong></h3><p>CBVs provide a more object-oriented approach and are built upon Python classes. They promote code reuse and organization by using inheritance and mixins.</p><p>There are primarily 3 distinct views from DRF imported as</p><p>a. from rest_framework import views # basic views</p><p>b. from rest_framework import generics # generic views</p><p>c. from rest_framework import viewsets # viewsets</p><h4><strong>A. from rest_framework import views</strong></h4><p><strong>views.APIView:</strong></p><p>This is the base class for all class-based views in DRF. It provides a structure for handling HTTP methods such as GET, POST, PUT, DELETE, etc., and can be customized to handle specific types of requests.</p><pre>from rest_framework.views import APIView, status<br>from rest_framework.response import Response<br><br>from viewApp.models import Book<br>from viewApp.serializers import BookSerializer<br><br>class BookApiView(APIView):<br>    <br>    def get(self, request):<br>       books = Book.objects.all()<br>       serializer = BookSerializer(books, many=True)<br>       <br>       return Response({<br>           &quot;success&quot;: True,<br>           &quot;message&quot;: &quot;successful get&quot;,<br>           &quot;data&quot;: serializer.data<br>       }, status=status.HTTP_200_OK)<br>       <br>    def post(self, request):<br>        data = request.data<br>        serializer = BookSerializer(data=data)<br>        <br>        if serializer.is_valid():<br>            serializer.save()<br>            <br>            return Response({<br>                &quot;success&quot;: True,<br>                &quot;message&quot;: &quot;successful post&quot;,<br>                &quot;data&quot;: serializer.data<br>            },  status=status.HTTP_201_CREATED)<br>        else:<br>            return Response({<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;failed post&quot;,<br>                &quot;data&quot;: serializer.errors<br>            }, status=status.HTTP_400_BAD_REQUEST)<br><br>class BookApiInstanceView(APIView):<br>    <br>    def get(self, request, pk):<br>        try:<br>            book = Book.objects.get(pk=pk)<br>            serializer = BookSerializer(book)<br>            <br>            return Response({<br>                &quot;success&quot;: True,<br>                &quot;message&quot;: &quot;successful get&quot;,<br>                &quot;data&quot;: serializer.data<br>            }, status=status.HTTP_200_OK)<br>    <br>        except Book.DoesNotExist:<br>            return Response({<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;Pk does not exist&quot;,<br>                &quot;data&quot;: &quot;&quot;<br>            }, status=status.HTTP_400_BAD_REQUEST)<br>            <br>    def patch(self, request, pk):<br>        try:<br>            book = Book.objects.get(pk=pk)<br>            data = request.data<br>            serializer = BookSerializer(data=data)<br>            if serializer.is_valid():<br>                book.title = serializer.data[&#39;title&#39;]<br>                book.content = serializer.data[&#39;content&#39;]<br>                book.save()<br>                <br>                return Response({<br>                    &quot;success&quot;: True,<br>                    &quot;message&quot;: &quot;successful patch&quot;,<br>                    &quot;data&quot;: serializer.data<br>                },  status=status.HTTP_201_CREATED)<br>            <br>        except Book.DoesNotExist:<br>            return Response({<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;Pk does not exist&quot;,<br>                &quot;data&quot;: &quot;&quot;<br>            }, status=status.HTTP_400_BAD_REQUEST)<br>            <br>    def delete(self, request, pk):<br>        try:<br>            book = Book.objects.get(pk=pk)<br>            book.delete()<br>            return Response({<br>                    &quot;success&quot;: True,<br>                    &quot;message&quot;: &quot;successful delet&quot;,<br>                    &quot;data&quot;: &quot;&quot;<br>                },  status=status.HTTP_204_NO_CONTENT)<br>            <br>        except Book.DoesNotExist:<br>            return Response({<br>                &quot;success&quot;: False,<br>                &quot;message&quot;: &quot;Pk does not exist&quot;,<br>                &quot;data&quot;: &quot;&quot;<br>            }, status=status.HTTP_400_BAD_REQUEST)</pre><p>From this long block of code, we can see that the APIView helps to define HTTP verbs to perform CRUD operations</p><p> <strong>BookApiView</strong>:</p><ul><li><strong>GET</strong>: Retrieves all books and returns them with a success message.</li><li><strong>POST</strong>: Creates a new book with the provided data, returning success if the data is valid, or errors if not.</li></ul><p> <strong>BookApiInstanceView</strong>:</p><ul><li><strong>GET</strong>: Retrieves a specific book by primary key (pk) and returns it if found, otherwise returns an error message.</li><li><strong>PATCH</strong>: Partially updates a specific book’s title and content if found and data is valid, otherwise returns an error message.</li><li><strong>DELETE</strong>: Deletes a specific book by pk if found, returning success, otherwise returns an error message.</li></ul><pre># urls.py<br><br>from django.urls import path<br>from .views import BookApiView, BookApiInstanceView <br><br>urlpatterns = [<br>    path(&quot;view/&quot;, BookApiView.as_view()),<br>    path(&quot;view/&lt;str:pk&gt;&quot;, BookApiInstanceView.as_view()),<br>]</pre><h4><strong>B. from rest_framework import generics</strong></h4><p><strong>i. generics.GenericAPIView:</strong></p><p>This extends APIView and adds commonly used attributes and methods, such as queryset and serializer_class, to simplify building views for working with models</p><pre>from rest_framework.generics import GenericAPIView<br>from rest_framework.response import Response<br>from rest_framework import status<br><br>from viewApp.models import Book<br>from viewApp.serializers import BookSerializer<br><br>class BookGenericAPIView(GenericAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br><br>    def get(self, request):<br>        serializer = self.get_serializer(self.get_queryset(), many=True)<br>        return Response(serializer.data)<br>    <br>    def post(self, request):<br>        serializer = self.get_serializer(data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)</pre><p><strong>ii. mixins:</strong></p><p>We can add mixins alongside the GenericAPIView.</p><p>DRF provides several mixins for common actions:</p><ul><li>CreateModelMixin</li><li>ListModelMixin</li><li>RetrieveModelMixin</li><li>UpdateModelMixin</li><li>DestroyModelMixin</li></ul><pre>from rest_framework.generics import GenericAPIView<br>from rest_framework.mixins import ListModelMixin, CreateModelMixin<br><br>from viewApp.models import Book<br>from viewApp.serializers import BookSerializer<br><br>class BookListCreateAPIView(ListModelMixin, CreateModelMixin, GenericAPIView):<br>     queryset = Book.objects.all()<br>     serializer_class = BookSerializer<br> <br>     def get(self, request, *args, **kwargs):<br>         return self.list(request, *args, **kwargs)<br> <br>     def post(self, request, *args, **kwargs):<br>         return self.create(request, *args, **kwargs)</pre><p><strong>iii. concrete generic views:</strong></p><p>Going a step further, we can combine the <strong>GenericAPIView </strong>with the appropriate mixins to provide simpler built in views.</p><p> <strong>CreateAPIView</strong>: Provides a view for creating model instances.</p><p> <strong>ListAPIView</strong>: Provides a view for listing model instances.</p><p> <strong>RetrieveAPIView</strong>: Provides a view for retrieving a model instance.</p><p> <strong>DestroyAPIView</strong>: Provides a view for deleting a model instance.</p><p> <strong>UpdateAPIView</strong>: Provides a view for updating a model instance.</p><p> <strong>ListCreateAPIView</strong>: Provides a view for listing and creating model instances.</p><p> <strong>RetrieveUpdateAPIView</strong>: Provides a view for retrieving and updating a model instance.</p><p> <strong>RetrieveDestroyAPIView</strong>: Provides a view for retrieving and deleting a model instance.</p><p> <strong>RetrieveUpdateDestroyAPIView</strong>: Provides a view for retrieving, updating, and deleting a model instance.</p><pre>from rest_framework.generics import ListCreateAPIView<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookListCreateView(ListCreateAPIView):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><h4><strong>C. from rest_framework import viewsets</strong></h4><p><strong>viewsets.ModelViewSet:</strong></p><p>This groups related actions into a single class. It reduces the amount of code needed to write multiple views for a resource and is particularly useful for building RESTful APIs.</p><pre># views.py<br>from rest_framework import viewsets<br><br>from .models import Book<br>from .serializers import BookSerializer<br><br>class BookModelViewSet(viewsets.ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer</pre><pre># urls.py<br>from django.urls import path, include<br>from .views import BookModelViewSet<br><br>from rest_framework.routers import DefaultRouter<br><br>router = DefaultRouter()<br><br>router.register(r&quot;view&quot;, BookModelViewSet, basename=&quot;book&quot;)<br><br>urlpatterns = [<br>    path(&quot;&quot;, include(router.urls)),<br>]</pre><p>Viewsets uses routers to automatically generate the URL patterns for a set of related views. This significantly reduces the amount of boilerplate code required and ensures a consistent and RESTful URL structure.</p><p>Testing with Postman. (You can use the web interface provided by DRF too)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKAnI9nNQV46f4D6fO9uBQ.png" /></figure><p>Passing the title, author and num_pages, we get a “201 created” for the post request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yf_yMk0qE4fhpTt8Ln0CA.png" /></figure><p>The GET request retrieves the record with a status code of 200 created from the POST request</p><h3><strong>Conclusion</strong></h3><p>In this article, we’ve explored the various types of views available in Django Rest Framework (DRF) and how they can be leveraged to build powerful and scalable APIs. From the simplicity of function-based views (FBVs) to the flexibility of class-based views (CBVs) and the high-level abstraction provided by viewsets, DRF offers a range of tools to suit different development needs.</p><p>By choosing the appropriate view type based on your project’s requirements, you can build APIs that are both powerful and easy to manage.</p><p>I hope this guide has provided valuable insights and practical examples to help you master DRF views.</p><p>The best way to solidify your understanding of DRF Views is through hands-on practice.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2184eceb7336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Django REST Framework: An In-depth Guide to Serializers]]></title>
            <link>https://medium.com/@ukemeboswilson/mastering-django-rest-framework-an-in-depth-guide-to-serializers-5e6b94530c7a?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e6b94530c7a</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 18:15:52 GMT</pubDate>
            <atom:updated>2024-07-13T18:15:52.770Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of web development, creating robust and efficient APIs is crucial for seamless data exchange between the server and client applications.</p><p>At the heart of Django REST Framework (DRF) lies the concept of serializers, which serve as the bridge between complex data types and easily consumable JSON or XML formats.</p><p>In this article, we will delve into the intricacies of DRF serializers, exploring their features, types, and practical use cases to help you build more effective and maintainable APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vfzWQ94BCBPJ1T4s2YbVA.png" /></figure><p>Serializers helps in converting complex data types, such as querysets and model instances, into native Python datatypes that can then be easily rendered into JSON, XML, or other content types. They also handle deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data</p><p><strong>Consider this analogy:</strong> You work at a mailing company, and a little child wants to write an essay to the president of an organization. The child uses pencils and crayons to scribble down some words, which are not very clear or logical. You, the mailman, rewrite what you think the child means, making it wordy and logical before passing it to the president.</p><p>The president reads it and decides to reply to the child, but his response is too complex for the child to understand. So, you, the mailman, get a pencil and crayons and try to describe to the child what the president responded.</p><p>In this analogy:</p><p>✔The child represents the client making a request.</p><p>✔The president represents the server processing the request and generating a response.</p><p>✔The mailman represents the DRF serializers handling the conversion of data between the client and server.</p><p>✔The scribbled words represent the raw unstructured data coming from the client</p><p>✔The complex response represents a Django model instance or a complex query result</p><h3><strong>Types of Serializers</strong></h3><p>a. Serializer</p><p>b. ModelSerializer</p><p>c. HyperlinkedModelSerializer</p><p>d. ListSerializer</p><p>e. BaseSerializer</p><p>To create a basic serializer one needs to import the serializers class from rest_framework.</p><pre>from rest_framework import serializers</pre><h3><strong>A. serializers.Serializer</strong></h3><p>This is the most basic class for creating serializers. It builds on top of BaseSerializer. It provides more control and flexibility but requires explicit field definitions and handling.</p><p>It can be used for non-model data or to customize the serialization behavior. It serves as the base class for defining custom serializers.</p><p>You define the fields you want to include in the serialized output.</p><pre># models.py<br>from django.db import models<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=50)<br>    pages = models.IntegerField()<br>    best_seller = models.BooleanField(default=True)<br>    <br>    def __str__(self) -&gt; str:<br>        return self.title<br>    <br><br># serializers.py<br>from rest_framework import serializers<br><br>class BookSerializer(serializers.Serializer):<br>    id = serializers.IntegerField(read_only=True)<br>    title = serializers.CharField(max_length=50)<br>    pages = serializers.IntegerField()<br>    best_seller = serializers.BooleanField(default=True)<br><br>    def create(self, validated_data):<br>        return Book.objects.create(**validated_data)<br>    <br>    def update(self, instance, validated_data):<br>        instance.title = validated_data.get(&#39;title&#39;, instance.title)<br>        instance.pages = validated_data.get(&#39;pages&#39;, instance.pages)<br>        instance.best_seller = validated_data.get(&#39;best_seller&#39;, instance.best_seller)<br>        <br>        instance.save()<br>        </pre><p>The id field is read-only, meaning it cannot be set during deserialization.</p><pre>book_data = {<br>    &#39;title&#39;: &#39;A nice title&#39;,<br>    &#39;pages&#39;: 300,<br>    &#39;best_seller&#39;: False<br>}<br><br>serializer = BookSerializer(data=book_data)<br><br>if serializer.is_valid():<br>    book = serializer.save()<br>    print(book.id)<br>else:<br>    print(serializer.errors)</pre><p>When you instantiate <em>BookSerializer</em> with <em>data=book_data</em>, it prepares the data for validation.</p><p>Calling <em>is_valid()</em> runs the validation logic, checking that all required fields are present and valid.</p><p>If the data is valid, <em>serializer.save()</em> creates or updates a User instance based on the validated data.</p><p><strong>Optional Custom Methods:</strong></p><p>·<strong> create:</strong> Define how to create a new instance when saving deserialized data.</p><p><strong>· update:</strong> Define how to update an existing instance when saving deserialized data.</p><p>If you are using serializers.Serializer for read-only operations (e.g., just to serialize data for an API response), you do not need to define create and update. However, if you intend to use the serializer for creating or updating objects based on incoming data, you will need to define these methods to specify how the data should be transformed into model instances.</p><p><strong>field-level validation: </strong>When performing field-level validation in a serializers.Serializer, the method name must follow the specific naming convention validate_&lt;field_name&gt; where &lt;field_name&gt; is the name of the field you want to validate. This allows Django REST Framework (DRF) to automatically call this method when validating that field.</p><pre>def validate_pages(self, value):<br>        if value &lt; 3:<br>            raise serializers.ValidationError(&quot;The Number of pages is too small.&quot;)<br>        return value</pre><p><strong>object level validation:</strong> To perform object level validation on the entire data, you can validate instead.</p><pre>def validate(self, data):<br>        if data[&#39;pages&#39;] &lt; 3:<br>            raise serializers.ValidationError(&quot;The Number of pages is too small.&quot;)<br>        return data</pre><h3><strong>B. serializers.ModelSerializer</strong></h3><p>This serializer provides a shortcut for creating serializers that deal with model instances and querysets. It automatically generates a set of fields and simple validation rules for you.</p><p>It automatically creates a Serializer class with fields that correspond to the Model fields and it includes methods to create and update model instances.. It is a subclass of serializers.Serializer</p><pre>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;pages&#39;, &#39;best_seller&#39;]</pre><p><strong>Attributes of the Meta class:</strong></p><p><strong>field:</strong> field attribute in the Meta calls can be specified as a list, a tuple or using the special value __all__</p><pre>fields = [&#39;id&#39;, &#39;title&#39;, &#39;pages&#39;, &#39;best_seller&#39;]<br>        # or<br>fields = (&#39;id&#39;, &#39;title&#39;, &#39;code&#39;, &#39;linenos&#39;, &#39;language&#39;, &#39;style&#39;)<br>        # or<br>fields = &quot;__all__&quot;</pre><p><strong>exclude:</strong> Specifies the fields to exclude from the serializer.</p><pre>exclude = (&#39;best_seller&#39;,)</pre><p><strong>read_only_fields: </strong>Specifies fields that should be read-only, meaning they will be included in the serialized output but not in the deserialized input.</p><pre>read_only_fields = (&#39;id&#39;,)</pre><p><strong>extra_kwargs: </strong>A dictionary of additional keyword arguments to apply to specific fields. This can be used to set attributes such as required, read_only, validators, etc., on individual fields</p><pre>extra_kwargs = {<br>            &#39;best_seller&#39;: {&#39;required&#39;: False} <br>        }</pre><h3><strong>C. serializers.HyperlinkedModelSerializer</strong></h3><p>This extends the functionality of the standard ModelSerializer. Unlike ModelSerializer, which uses primary keys to represent relationships, HyperlinkedModelSerializer uses hyperlinks to represent relationships between resources.</p><p>Automatically generates URLs for each resource based on the URL patterns defined in your Django application.</p><pre>from rest_framework import serializers<br><br><br>class BookSerializer(serializers.HyperlinkedModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = [&#39;id&#39;, &#39;title&#39;, &#39;pages&#39;, &#39;best_seller&#39;]</pre><h3><strong>D. serializers.ListSerializer</strong></h3><p>This handles serialization and deserialization of lists of objects. It supports batch operations like creating, updating, and deleting multiple objects at once.</p><pre>from rest_framework import serializers<br><br><br>class BookListSerializer(serializers.ListSerializer):<br>    child = BookSerializer()<br><br>    def create(self, validated_data):<br>        items = [Book(**book) for book in validated_data]<br>        return Book.objects.bulk_create(items)<br><br>    def update(self, instance, validated_data):<br>        book_mapping = {book.id: book for book in instance}<br>        data_mapping = {book_data[&#39;id&#39;]: book_data for book_data in validated_data}<br><br>        ret = []<br>        for book_id, data in data_mapping.items():<br>            book = book_mapping.get(book_id, None)<br>            if book is not None:<br>                ret.append(self.child.update(book, data))<br>            else:<br>                ret.append(self.child.create(data))<br><br>        return ret</pre><h3><strong>Conclusion</strong></h3><p>In this article, we explored the fundamentals of DRF serialization, including the purpose of serializers, the types of serializers, how to create them, and various features like validation and custom serialization logic.</p><p>We’ve covered the basics and some advanced features, but there’s always more to learn. Consider diving deeper into custom serializers and performance optimization to further enhance your skills.</p><p>The best way to solidify your understanding of DRF serialization is through hands-on practice.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e6b94530c7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Magic of Data: An Introduction to Django Models]]></title>
            <link>https://medium.com/@ukemeboswilson/unlocking-the-magic-of-data-an-introduction-to-django-models-b43d9124c588?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43d9124c588</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 11:12:10 GMT</pubDate>
            <atom:updated>2024-08-04T21:01:16.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a world where your web applications can seamlessly manage and interact with databases without breaking a sweat. Welcome to the realm of Django Models, where the power of Python meets the elegance of streamlined data management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-bLiZXuVzj4E56sK2Bi-A.png" /></figure><p>A model is a Python class that represents a table in the database.</p><p>It is a definitive source of information about your data. It contains the essential fields and behaviors of the data you are storing. Generally, each model maps to a single database table.</p><p>Django models provide simplicity, consistency, version control, and advanced metadata handling.</p><p>To define a model, you create a class that inherits from django.db.models.Model.</p><h3><strong>Fields</strong></h3><p>A model can have an arbitrary number of fields, of any type — each one represents a column of data(database field) that we want to store in one of our database tables.</p><p>Lets consider this example.</p><pre>class Book(models.Model):<br>    title = models.CharField(max_length=50)<br>    pages = models.IntegerField()<br>    best_seller = models.BooleanField(default=True)<br>    cover_picture = models.ImageField()<br>    summary = models.TextField()<br>    price = models.FloatField()<br>    created_at = models.DateTimeField()<br>    <br>    def __str__(self) -&gt; str:<br>        return self.title</pre><p>We have created a model called Book. That is like creating a database table called Book. In this book table, we have specified several columns. Lets examine them</p><h3><strong>CharField:</strong></h3><p>This is a used for storing short-to-medium sized strings in a model. Typically maps to a VARCHAR column in the database.</p><p><strong>Parameters:</strong></p><p>max_length: Specifies the maximum length of the string. This parameter is required.</p><h3><strong>IntergerField:</strong></h3><p>This is suitable for storing numeric data where only whole numbers are required, such as counting items, representing IDs, or storing quantities. Typically maps to an INTEGER column in the database</p><h3><strong>BooleanField:</strong></h3><p>This is suitable for storing data that has only two possible states, such as flags, status indicators, or any binary choice. is a field used to store boolean values (True or False). Typically maps to a BOOLEAN or TINYINT(1) column in the database.</p><h3><strong>ImageField:</strong></h3><p>This is used to store image files in a model. Typically maps to a VARCHAR column in the database that stores the file path.</p><p><strong>Parameters:</strong></p><p>upload_to: Specifies the directory within the MEDIA_ROOT where files will be uploaded.</p><p>height_field: Optionally stores the height of the image.</p><p>width_field: Optionally stores the width of the image.</p><h3><strong>TextField:</strong></h3><p>This is used to store large text data in a model. Typically maps to a TEXT column in the database.</p><h3><strong>FloatField:</strong></h3><p>This is used to store floating-point numbers in a model. Typically maps to a FLOAT column in the database.</p><h3><strong>DateTimeField:</strong></h3><p>This is used to store date and time information in a model. Typically maps to a DATETIME</p><p><strong>Parameters:</strong></p><p>auto_now: If True, the field is automatically set to the current date and time every time the object is saved.</p><p>auto_now_add: If True, the field is automatically set to the current date and time when the object is first created.</p><h3><strong>EmailField:</strong></h3><p>This is used to store and validate email addresses.</p><p>Other fields include:</p><pre>&quot;AutoField&quot;<br>&quot;BLANK_CHOICE_DASH&quot;<br>&quot;BigAutoField&quot;<br>&quot;BigIntegerField&quot;<br>&quot;BinaryField&quot;<br>&quot;CommaSeparatedIntegerField&quot;<br>&quot;DateField&quot;<br>&quot;DurationField&quot;<br>&quot;FilePathField&quot;<br>&quot;GenericIPAddressField&quot;<br>&quot;IPAddressField&quot;<br>&quot;NOT_PROVIDED&quot;<br>&quot;NullBooleanField&quot;<br>&quot;PositiveBigIntegerField&quot;<br>&quot;PositiveIntegerField&quot;<br>&quot;PositiveSmallIntegerField&quot;<br>&quot;SlugField&quot;<br>&quot;SmallAutoField&quot;<br>&quot;SmallIntegerField&quot;<br>&quot;TimeField&quot;<br>&quot;URLField&quot;<br>&quot;UUIDField&quot;</pre><h3><strong>Common Field Arguments (Optional):</strong></h3><p><strong>default:</strong> Sets a default value for the field each time a new record is created</p><p><strong>null:</strong> If True, the field can store NULL values. The default is False.</p><p><strong>blank:</strong> If True, the field is allowed to be empty. The default is False.</p><p><strong>unique: </strong>If True, the field must be unique across the database table. (Not applicable for Boolean)</p><p><strong>choices:</strong> A sequence of 2-tuples to use as choices for this field. (Not applicable for BooleanField, ImageField, DateTimeField)</p><p><strong>validators:</strong> A list of validators to apply to this field. (Not applicable for Boolean)</p><p><strong>help_text:</strong> Provides a help text for the field.</p><p><strong>verbose_name:</strong> A human-readable name for the field.</p><p><strong>db_index:</strong> If True, a database index is created for this field.</p><p><strong>editable:</strong> If True, the field is editable in forms.</p><p>Lets consider an example where we utilize some of these optional arguments</p><pre>from django.db import models<br>from django.core.validators import MinLengthValidator, MaxLengthValidator<br><br>class MyModel(models.Model):<br>    CATEGORY_CHOICES = [<br>        (&#39;tech&#39;, &#39;Technology&#39;),<br>        (&#39;health&#39;, &#39;Health&#39;),<br>        (&#39;edu&#39;, &#39;Education&#39;),<br>    ]<br><br>    name = models.CharField(max_length=100, null=True, blank=True, db_index=True, editable=True)<br>    category = models.CharField(choices=CATEGORY_CHOICES, verbose_name=&#39;Category Name&#39;, <br>                                validators=[MinLengthValidator(3), MaxLengthValidator(100)],<br>                                help_text=&#39;Enter the name of the category. Minimum length is 3 characters.&#39;,)<br>    email = models.EmailField(unique=True)</pre><h3><strong>Model Relationships:</strong></h3><p>Django allows you to define relationships between tables that are many to one(<strong>ForeignKey</strong>), one to one (<strong>OneToOneField</strong>), and many to many (<strong>ManyToManyField</strong>).</p><p><strong>ForeignKey:</strong></p><p>It establishes a one-to-many relationship, where one record in the source model (the model with the ForeignKey) can be associated with multiple records in the target model (the referenced model).</p><p>Example: If you have a Book model and an Author model, a ForeignKey from Book to Author represents that each book has exactly one author (many books can share the same author).</p><p>The ForeignKey field is typically used on the “many” side of the relationship (e.g., Book).</p><pre>from django.db import models<br><br>class Author(models.Model):<br>    name = models.CharField(max_length=100)<br><br>    def __str__(self):<br>        return self.name<br><br>class Book(models.Model):<br>    title = models.CharField(max_length=200)<br>    author = models.ForeignKey(Author, on_delete=models.CASCADE)<br><br>    def __str__(self):<br>        return self.title</pre><pre>from folder_name/models import Author, Book<br><br>author = Author.objects.create(name=&quot;Ukeme Wilson&quot;)<br>book = Book.objects.create(title=&quot;Introduction to Django Models&quot;, author=author)<br><br>book = Book.objects.get(id=1)<br>author = book.author  # This gives you the related Author instance<br>print(author.name)</pre><p><strong>OneToOneField:</strong></p><p>This is used to create a one to one relationship between two models. It is essentially a special case of a ForeignKey with unique=True.</p><pre>from django.db import models<br><br>class Person(models.Model):<br>    name = models.CharField(max_length=100)<br>    age = models.IntegerField()<br><br>class Passport(models.Model):<br>    person = models.OneToOneField(Person, on_delete=models.CASCADE)<br>    passport_number = models.CharField(max_length=20)<br>    issue_date = models.DateField()<br>    expiry_date = models.DateField()</pre><pre>from folder_name/models import Person, Passport<br><br>person = Person.objects.get(id=1)<br>passport = person.passport<br><br>passport = Passport.objects.get(id=1)<br>person = passport.person</pre><p>The basic difference between the above two relationships can be illustrated with examples. In the case of the book-author relationship (one-to-many/foreign-key), each book will have only one author, but an author can have several books. In contrast, in the case of the person-passport relationship (one-to-one), each person will have only one passport, and each passport will belong to only one person.</p><p><strong>ManyToManyField:</strong></p><p>This is used to define a many-to-many relationship between two models. This means that each instance of one model can be related to multiple instances of another model, and vice versa. Django handles this relationship using an intermediary join table that maintains the associations between the related models.</p><pre>class Language(models.Model):<br><br>    name = models.CharField(max_length=50)<br>    <br>    def __str__(self):<br>        return self.name<br><br>class Programmer(models.Model):<br>    name = models.CharField(max_length=50)<br>    languages = models.ManyToManyField(Language)<br>    <br>    def __str__(self) -&gt; str:<br>        return self.name</pre><p>This implies that each programmer can know multiple languages. Also each language can be known by multiple programmers.</p><pre>from folder_name/models import Programmer, Language<br><br>programmer = Programmer.objects.get(name=&#39;Alice&#39;)<br>languages = programmer.languages.all()  # Returns a QuerySet of Language objects<br>print(languages)<br><br>language = Language.objects.get(name=&#39;Python&#39;)<br>programmers = language.programmer_set.all()  # Returns a QuerySet of Programmer objects<br>print(programmers)<br></pre><h3><strong>Metadata:</strong></h3><p>You can declare model-level metadata for your Model by declaring class Meta, as shown.</p><pre>class Meta:<br>  ordering = [&#39;-my_field_name&#39;] # Sort the table by &#39;my_field_name&#39; in descending order. The &quot;-&quot; before the field name signifies descending order.<br>  verbose_name = &#39;BetterName&#39; # Human-readable name for the model in singular form<br>  abstract = True # To treat the class as an abstract class (No table will be created for it))<br>  db_table = &quot;music_album&quot; # The name of the database table to use for the model</pre><p>These fields in the Meta class are optional.</p><h3><strong>Wrapping Up</strong></h3><p>In this article, we’ve explored the versatility and efficiency of Django models. From defining fields and relationships to leveraging the power of Django’s ORM, models form the backbone of any Django application, making data handling seamless and intuitive.</p><p>Combining this knowledge with the other different components of Django will provide a robust framework that simplifies your development process and enhances your application’s functionality.</p><p>Happy coding!</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43d9124c588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST Framework]]></title>
            <link>https://medium.com/@ukemeboswilson/django-rest-framework-7fc0995c0797?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc0995c0797</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 08:59:37 GMT</pubDate>
            <atom:updated>2024-08-19T08:58:37.597Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re looking to create robust and flexible APIs with Django, the Django REST framework (DRF) is your go-to toolkit.</p><p>Django REST framework is a powerful and flexible toolkit for building Web APIs. It simplifies the process of creating and managing APIs by providing a comprehensive suite of features.</p><p>Django REST framework adopts implementations like class-based views, forms, model validators, the QuerySet API, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F60-kjoaKemo7O11GTdasA.jpeg" /></figure><p>REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.</p><p>DRF integrates with Django’s core features — models, views, and URLs — making it simple and seamless to create RESTful HTTP resources.</p><p>Some key concepts in Django rest framework includes,</p><h3><strong>Serialization</strong>:</h3><p>Serialization is the process of converting complex data types, such as Django models, into native Python data types that can then be easily rendered into JSON, XML, or other content types. Also, before deserializing the data, for incoming payloads, serializers validate the shape of the data.</p><pre># serializers.py<br>from rest_framework import serializers<br>from .models import YourModel<br><br>class YourModelSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = YourModel<br>        fields = &#39;__all__&#39;</pre><h3><strong>Views:</strong></h3><p>DRF has three different types of views:</p><p><strong>APIView:</strong> This is a class-based view designed for building RESTful APIs, offering more control and flexibility compared to function-based views. It allows developers to define HTTP methods like GET, POST, PUT, and DELETE directly within the class, facilitating cleaner and more organized code</p><p><strong>Generic View:</strong> This provide pre-built, reusable view classes that handle common web development tasks, such as displaying a list of objects or handling form submissions. They significantly reduce boilerplate code, enabling developers to quickly implement common functionalities by simply configuring the view with minimal code</p><p><strong>ViewSet:</strong> A higher-level abstraction that combines the logic for handling multiple actions (such as list, create, retrieve, update, and delete) in a single class.</p><p>While Django views typically serve up HTML templates, DRF views return a JSON response.</p><h3><strong>Routers:</strong></h3><p>Routers provide an easy way of automatically determining the URL configuration for your API. They work well with ViewSets to create RESTful endpoints without much boilerplate code. They reduce repetitive code by handling the URL routing for common CRUD operations, enabling a more organized and maintainable project structure.</p><pre># urls.py<br>from django.urls import path, include<br>from rest_framework.routers import DefaultRouter<br>from .views import YourModelViewSet<br><br>router = DefaultRouter()<br>router.register(r&#39;yourmodels&#39;, YourModelViewSet)<br><br>urlpatterns = [<br>    path(&#39;&#39;, include(router.urls)),<br>]</pre><h3><strong>Filtering, Searching, and Ordering:</strong></h3><p>DRF provides a powerful framework for filtering, searching, and ordering querysets:</p><p>Filtering: Allows you to restrict the queryset based on criteria.</p><p>Searching: Adds simple search capabilities to your API.</p><p>Ordering: Provides control over the ordering of results.</p><pre>pip install django-filter</pre><pre>INSTALLED_APPS = [   ... <br>                    &#39;rest_framework&#39;, <br>                    &#39;django_filters&#39;, ]<br><br>REST_FRAMEWORK = { ...<br>&#39;DEFAULT_FILTER_BACKENDS&#39;: [ &#39;django_filters.rest_framework.DjangoFilterBackend&#39;, &#39;rest_framework.filters.SearchFilter&#39;, &#39;rest_framework.filters.OrderingFilter&#39;, ], <br>}</pre><h3><strong>Pagination:</strong></h3><p>DRF supports various pagination styles, allowing large querysets to be divided into smaller chunks. The built-in pagination classes include PageNumberPagination, LimitOffsetPagination, and CursorPagination.</p><p>e.g</p><pre># settings.py<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.PageNumberPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 10<br>}</pre><h3><strong>API Documentation:</strong></h3><p>DRF can integrate with tools like Swagger or ReDoc to provide interactive API documentation. These tools automatically generate documentation based on your API views, serializers, and models.</p><p>This can be set up using drf_yasg (Yet Another Swagger Generator) or drf_spectacular.</p><h3><strong>Testing:</strong></h3><p>DRF provides utilities for testing your API, including test cases for making requests and checking responses.</p><h3><strong>QUICK DEMO</strong></h3><pre>$ pip install django<br>$ pip install djangorestframework</pre><p>Create a project</p><pre>$ django-admin startproject drf_proj .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*l-Z7L4XIx_tGun5thhegxQ.png" /></figure><p>Create an app</p><pre>$ python manage.py startapp product</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*aZCj4iEYKAflF7euA6rC4g.png" /></figure><p>Edit the “settings.py” file inside the project and add “rest_framework” and “product” to the INSTALLED_APPS list</p><pre>INSTALLED_APPS = [<br>    &#39;django.contrib.admin&#39;,<br>    &#39;django.contrib.auth&#39;,<br>    &#39;django.contrib.contenttypes&#39;,<br>    &#39;django.contrib.sessions&#39;,<br>    &#39;django.contrib.messages&#39;,<br>    &#39;django.contrib.staticfiles&#39;,<br>    &#39;rest_framework&#39;,<br>    &#39;product&#39;<br>]</pre><p>Set Up Model</p><pre># product/models.py<br>from django.db import models<br><br># Create your models here.<br><br>class Product(models.Model):<br>    name = models.CharField(max_length=50)<br>    amount = models.FloatField()<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    <br>    def __str__(self) -&gt; str:<br>        return self.name</pre><p>Set Up Serializer</p><p>create a new file called “serializers.py” inside the product directory</p><pre># product/serializers.py<br>from rest_framework import serializers<br>from .models import Product<br><br>class ProductSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = [&quot;id&quot;, &quot;name&quot;, &quot;amount&quot;, &quot;created_at&quot;]</pre><p>Set up Views</p><pre># product/views.py<br>from rest_framework import viewsets<br>from rest_framework import permissions<br><br>from .serializers import ProductSerializer<br>from .models import Product<br><br># Create your views here.<br><br>class ProductView(viewsets.ModelViewSet):<br>    <br>    serializer_class = ProductSerializer<br>    permission_classes = [permissions.AllowAny]<br>    queryset = Product.objects.all()</pre><p>Set up product urls.py</p><pre># product/urls.py<br>from django.urls import path, include<br>from rest_framework.routers import DefaultRouter<br>from .views import ProductView<br><br><br>router = DefaultRouter()<br>router.register(r&quot;product&quot;, ProductView, basename=&quot;product&quot;)<br><br>urlpatterns = [<br>    path(&quot;&quot;, include(router.urls)),<br>]</pre><p>Set up project urls.py</p><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;api/&quot;, include(&quot;product.urls&quot;))<br>]</pre><p>Next step is to set up the db</p><pre>$ python manage.py makemigrations<br><br>$ python manage.py migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jdatimDxjS5Ppp9gP82hQ.png" /></figure><p>Next, we can then start the Django server</p><pre>$ python manage.py runserver</pre><p>Navigate to <a href="http://127.0.0.1:8000/api/product/"><em>http://127.0.0.1:8000/api/product/</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnOk1Uyw9_cUi5TCixIyiw.png" /></figure><p>Using the Django rest framework interface, you can perform CRUD functionalities</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1A6LXh_ipjvM4pewNfQQHw.gif" /></figure><p>Cool. This is a basic set up for Django rest framework.</p><h3><strong>Conclusion</strong></h3><p>This article dives into the different features of DRF, offering practical examples and tips to help you get started with DRF. Learn how to set up your first API endpoint, set up models, serializers and views</p><p>Ready to elevate your Django projects with RESTful APIs? Dive into our full article and start harnessing the full potential of Django REST framework today!</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><p><a href="https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616">Django Overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc0995c0797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Overview]]></title>
            <link>https://medium.com/@ukemeboswilson/django-overview-0dbfc1557616?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dbfc1557616</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 08:54:52 GMT</pubDate>
            <atom:updated>2026-01-07T11:21:02.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Essentials: What You Need to Know</h3><p><strong>What is Django? </strong><br> Django is a python web framework used in the creation of complex database driven websites. It makes it easy to create secure and maintainable websites using python. (Other python web frameworks are Flask and FastApi).</p><p>Web framework is a software framework designed to aid the development of web applications using web services, web resources and web APIs.</p><p>Django is versatile and follows the “Batteries included” principle where almost everything you need can be gotten from Django and you don’t have to build from scratch. It is able to deliver content in almost any format (HTML, RSS, JSON, XML).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*lI8dPIIz3sjGcPmNnLf20g.jpeg" /></figure><h3><strong>Getting started:</strong></h3><p>Django can be installed using a simple command on your terminal. It is expected that you have <a href="https://www.ionos.com/digitalguide/websites/web-development/install-python/">python</a> and pip already installed on your pc.</p><p><strong>Set up venv:</strong></p><pre><br>$ python -m venv venv</pre><p>or</p><pre>$ python3 -m venv venv</pre><p>This creates a virtual environment with a name called venv. (You should see a folder/directory created called “venv”).</p><p>The next step is to activate the virtual environment.</p><pre># windows<br>$ venv\Scripts\activate</pre><pre># linux, macOs<br>$ source venv/bin/activate</pre><p>Once activated, you can then install django.</p><pre>$ pip install Django<br><br># Or<br><br>$ pip3 install django</pre><p>If this runs well, you can verify by running and see something like this 5.0.6 (You may not have the exact number).</p><pre>$ python -m django - version</pre><h3><strong>Project and Apps</strong></h3><h3><strong>Project</strong></h3><p><strong>A Project </strong>in Django is a collection of configurations, applications and settings that work together to accomplish your goal/task of creating a web application. For example, you wish to create a website for books (can be any name though), that becomes your project. Since Django doesn’t want you to write everything about the “books” project, it sets up a directory for you containing some configurations and settings.</p><pre>$ django-admin startproject project_name</pre><p>You should see a folder/directory with this structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*gZGj7W5uKIZRgV1u_wexnQ.png" /></figure><p><strong>wsgi.py:</strong> This serves as the entry point for WSGI (WEB SERVER GATEWAY INTERFACE) compatible web server. It defines how web servers communicate with web applications allow them to handle http requests and responses. It serves as a bridge between web servers (NGINX, APACHE) and web applications in python.</p><p><strong>urls.py:</strong> This serves to route incoming request by creating a URL pattern mapping to view functions/classes. For example, when you go to a site <a href="https://xyz.com/">https://xyz.com/</a> or <a href="https://xyz.com/name">https://xyz.com/name</a>, the “/” or the “/name” are routes that are specified to carry out a particular task described in the view function.</p><p><strong>settings.py:</strong> This contains settings and configurations (databases, installed apps, middleware) needed for the project to run properly.</p><p><strong>__init__.py:</strong> This is an empty file that tells python to treat the folder as a python package.</p><p><strong>manage.py:</strong> This is a command line utility that lets you interact with the Django project such as creating Django apps, running the server and doing migrations.</p><h3><strong>Apps</strong></h3><p><strong>Apps (applications)</strong> are python packages that serves a specific function inside the project. A project would usually consist of multiple Apps. For example, a typical book could consist of numerous chapters, table of content, index page etc. This allows you to organize your project into separate reusable units.</p><pre>$ cd project_name<br>$ python manage.py startapp app_name<br></pre><p>You should now see a folder/directory with this structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*ktKpT3tlsoS6OUKWbDruJA.png" /></figure><p><strong>migrations/: </strong>Directory containing database migration files generated by Django when changes are made to models.</p><p><strong>__init__.py:</strong> Python package indicator file.</p><p><strong>admin.py:</strong> Configuration for registering models with the Django admin interface.</p><p><strong>apps.py: </strong>Configuration for the app itself, including metadata and configuration settings.</p><p><strong>models.py:</strong> Defines data models using Django’s ORM (Object-Relational Mapping) for interacting with the database such as to add, modify, delete and query records.</p><p><strong>tests.py:</strong> Contains unit tests for the app.</p><p><strong>views.py:</strong> Contains view functions or classes that handle HTTP requests and generate HTTP responses.</p><h3>Running the Server</h3><p>Now you can run the server by running.</p><pre>python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pI4J0aQD81CNL7cI8ZtvQ.png" /></figure><p>You should see “development server at http://127.0.0.1:8000/”. <br>Click on the link and this should display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0W5y5D0Qb4U-4-IshYHBg.png" /></figure><p>If you are able to get here, congrats. You have created your first Django project.</p><h3><strong>Conclusion</strong></h3><p>There are still a lot to learn and still a lot to do on your project, but this is a big step in the right direction for you.</p><p>Stick around as I uncover other areas you need to learn to make your project much better.</p><p>Let’s Get in Touch! Follow me on:</p><p>&gt;GitHub: @<a href="https://github.com/bosukeme/">bosukeme</a></p><p>&gt;Linkedin: <a href="https://www.linkedin.com/in/ukeme-wilson-4825a383/">Ukeme Wilson</a></p><p>You can read other of my Medium Articles <a href="https://medium.com/@ukemeboswilson">here</a></p><p><a href="https://medium.com/@ukemeboswilson/django-rest-framework-7fc0995c0797">Django REST Framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dbfc1557616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Requests module to scrape webpages]]></title>
            <link>https://medium.com/@ukemeboswilson/using-requests-module-to-scrape-webpages-7fabee9da12e?source=rss-efa157ed281d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fabee9da12e</guid>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[request]]></category>
            <category><![CDATA[requests-html]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[webpage]]></category>
            <dc:creator><![CDATA[Ukeme  Wilson]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 09:53:37 GMT</pubDate>
            <atom:updated>2020-07-06T10:14:57.993Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Using Requests Module to Scrape Webpages</strong></p><p>Hii. Getting certain information from webpages can be a cool and daunting challenge for a data scientist. In this tutorial I will be showing you how to do so with requests and requests_html modules.</p><p>Note you can also do this with selenium and webdriver. I have used both. Both are cool. Though requests seems to be faster and less complicated.</p><p>The requests module allows you to send HTTP requests using Python.</p><p>The HTTP request returns a <a href="https://www.w3schools.com/python/ref_requests_response.asp">Response Object</a> with all the response data (content, encoding, status, etc).</p><p>We will start by importing the modules (check the image). If none has already been installed in your pip, just type “<strong><em>pip install requests</em></strong>”, “<strong><em>pip install requests_html</em></strong>” etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*avv1FOqRRg11--VZ19SLpg.jpeg" /></figure><p>Next, you get the url of the site you wish to scrape and do a get requests on it. In this case, we want to get every instagram user bearing the name chelsea</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*IKQya3lrtRWKzf7rKk6acw.jpeg" /></figure><p>Then you go over to the webpage, right click on the mouse and click on “inspect elements”. Classes in html are referenced with a ‘.’ while ids are referenced with a ‘#’. In our case, the class “<strong><em>timg</em></strong>”, was what was used to store the users in the webpage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*2Qm3RjzWvN2SQ9Qij_xy_g.jpeg" /></figure><p>Then we pass in the class tag into the .html.find(). Then we do some list comprehension to save it into two separate list for easy usage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*axHEG-SpvRqJRGn8t7Lnng.jpeg" /></figure><p>We will also like to get the average likes each user gets on their instagram page.</p><p><strong><em>headers = {‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36’}</em></strong>. Using the above header, tells the program that the request is coming from a recognized browser and not from any bot.</p><p>The ‘html.parser’ serves as the basis for parsing text files formatted in HTML</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*dcPGAAdt3YzaedfIrSOxfg.jpeg" /></figure><p>so we inspect our site to find how the avearge likes are saved. The class “tallyb” was used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUcZ5RNpThAtARdx9G2ojQ.jpeg" /></figure><p>We pass in the class “tallyb”, covert to a string, do a regex on it and convert to an interger</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*lfBcR1O7WEg9Vz-HzM-wsg.jpeg" /></figure><p>finally, we present it as a pandas df</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*KtR2aSZq0P7kocNnvG08qA.jpeg" /></figure><p>the df should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*WIG8v6m7wuxCqLLn-CHA7g.jpeg" /></figure><p>I hope you followed through. The full code can be found on my github</p><p><a href="https://github.com/bosukeme/instagram_users_request/blob/master/instagram_users.py">bosukeme/instagram_users_request</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fabee9da12e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>