<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Somtochukwu</title>
    <description>The latest articles on DEV Community by Somtochukwu (@somto).</description>
    <link>https://dev.to/somto</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F419225%2F9f7b7275-0a91-4a52-87e3-50e4f70295fd.jpg</url>
      <title>DEV Community: Somtochukwu</title>
      <link>https://dev.to/somto</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/somto"/>
    <language>en</language>
    <item>
      <title>Swagger Implementation using function based views drf</title>
      <dc:creator>Somtochukwu</dc:creator>
      <pubDate>Sat, 07 May 2022 12:29:08 +0000</pubDate>
      <link>https://dev.to/somto/swagger-implementation-using-function-based-views-drf-4i1l</link>
      <guid>https://dev.to/somto/swagger-implementation-using-function-based-views-drf-4i1l</guid>
      <description>&lt;p&gt;Hello friends, in this article we will be going over swagger UI implementation with function based views in django rest framework (drf).&lt;/p&gt;

&lt;p&gt;I decided to write an article on this because recently I faced different problems when trying to add in basic functionalities of swagger UI into my API, I was using function based views instead of the more popular classed based view approach. &lt;/p&gt;

&lt;p&gt;In this article we will be building a basic product API with CRUD applications, using function based views and then adding swagger UI to make our API more presentable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting up Our Development Environment
&lt;/h3&gt;

&lt;p&gt;We need to create our django project, but we need to setup our development environment.&lt;/p&gt;

&lt;p&gt;Firstly create a working directory and in it, create a virtual environment, using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir django-swagger
cd django-swagger
virtualenv env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to activate our virtual environment, use the appropriate code that works for your OS, using any of the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Windows --&amp;gt; env\Scripts\activate 
Linux --&amp;gt; source env/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we install our dependencies, using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django djangorestframework
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we start our django project and then create an app, using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startproject main .
python manage.py startapp prodcuts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Creating Our Models
&lt;/h3&gt;

&lt;p&gt;We have successfully created our development environment, now we need to create the model(s) we will work with. We only need a simple &lt;code&gt;Product&lt;/code&gt; model with a few fields. Add this to your &lt;code&gt;models.py&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Product(models.Model):
    title = models.CharField(max_length=224)
    description = models.CharField(max_length=255)

    def __str__(self):
        return self.title
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating Our Serializers
&lt;/h2&gt;

&lt;p&gt;Now, we run our &lt;code&gt;makemigrations&lt;/code&gt; command so as to populate our database with the &lt;code&gt;Product&lt;/code&gt; table.&lt;br&gt;
Next we create our &lt;code&gt;serializers.py&lt;/code&gt; file in our &lt;code&gt;product&lt;/code&gt;, and add the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework import seriailizers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product 
        fields = "__all__"

class UpdateProductSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product 
        fields = ["title", "description"]

    def update(self, instance, validated_data):
        instance.title = validated_data.get("title", instance.title)
        instance.description = validated_data.get("description", instance.description)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now have our models and serializers ready. We now need to create &lt;code&gt;CRUD&lt;/code&gt; views in our &lt;code&gt;views,py&lt;/code&gt; file. Add this block of code to your &lt;code&gt;views.py&lt;/code&gt; file.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create Product View
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from .models import Product 
from .serializers import ProductSerializer

@api_view(['POST'])
def create_product(request):
    if request.method == 'POST':
        create_product = ProductSerializer(data=request.data)
        if create_product.is_valid():
            title = create_product.validated_data.get('title')
            description = create_product.validated_data.get('description')
            product = Product.objects.create(title=title, description=description)
            product.save()
            return Response(create_product.data, status=status.HTTP_201_CREATED)
        else:
            return Response(create_product.errors, status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({"Error": "Invalid request type"}, status=status.HTTP_400_BAD_REQUEST)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Read Product View
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['GET'])
def read_product(request):
    if request.method == 'GET':
        all_products = Product.objects.all()
        serialized_products = ProductSerializer(all_products, many=True)
        return Response(serialized_products.data,    status=status.HTTP_200_OK)
    else:
        return Response(serialized_products.errors, status=status.HTTP_400_BAD_REQUEST)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update Product View
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@pi_view(['PATCH'])
def update_product(request, id):
    if request.method == 'PATCH':
        try: 
            product = Product.objects.get(id=id)
            update_seriailizer = UpdateProductSerializer(product, data=request.data, partial=True)
             if update_serializer.is_valid():
                update_serializer.save()
                return Response({"Message": "Product updated"}, status=status.HTTP_200_OK)
             else:
                 return Response(update_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({"Error": f"Unexpected error {e} occurred.", status=status.HTTP_400_BAD_REQUEST)
    else:
        return Response({"Error": "Invalid request type", status=status.HTTP_400_BAD_REQUEST})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Delete Product View
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@api_view(['POST'])
def delete_view(request):
    if request.method == 'POST':
        all_products = Product.objects.all()
        all_product.delete()
        return Response({"Message": "All Products have been deleted"}, status=status.HTTP_200_OK)
    else:
        return Response({"Error": "Invalid request type"}, status=status.HTTP_400_BAD_REQUEST)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Product View Urls
&lt;/h3&gt;

&lt;p&gt;Now, we need to create urls to help us access our endpoints. In our &lt;code&gt;product&lt;/code&gt; directory we need to create a &lt;code&gt;urls.py&lt;/code&gt; file and populate it with this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path 
from . import views 

urlpatterns = [
    path('create', views.create_product, name='create-product'),
    path('read', views.read_product, name='read-all-products'),
    path('update/&amp;lt;int:id&amp;gt;', views.update_product, name='update-products'),
    path('delete', views.delete_view, name='delete-product')
] 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we need to add our url configuration to the root directory &lt;code&gt;urls.py&lt;/code&gt; file by adding this to the existing &lt;code&gt;urlpatterns&lt;/code&gt; list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;path('product/', include('product.urls'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also make sure to import &lt;code&gt;include&lt;/code&gt; alongside &lt;code&gt;path&lt;/code&gt; from &lt;code&gt;django.urls&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Swagger Implementation
&lt;/h2&gt;

&lt;p&gt;We're done with building our products API, now, we will see how to use swagger UI with our API we have built. Firstly we need to install a package called &lt;code&gt;drf_yasg&lt;/code&gt;, this will help us with the swagger UI implementation. The &lt;code&gt;yasg&lt;/code&gt; stands for &lt;code&gt;Yet Another Swagger Generator&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To install it, let's open our terminal and enter this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install drf_yasg
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After the installation add it to your installed apps in your, like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
   'drf_yasg',
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have added the package to our installed apps, now to see the magic happen we need to add a few routes to our root &lt;code&gt;urls.py&lt;/code&gt; file. &lt;/p&gt;

&lt;p&gt;Add this block of code to your root &lt;code&gt;urls.py&lt;/code&gt; file, right below the &lt;code&gt;django.urls&lt;/code&gt; import:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="Products API",
      default_version='v1',
      description="Description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="&amp;lt;your-gmail&amp;gt;@gmail.com"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this block of code does is to convert our generic django rest framework UI into swagger UI anytime we check our API in the browser. It will be much cleaner  and easier to understand.&lt;/p&gt;

&lt;p&gt;We need to add this block of code too, this should go into the &lt;code&gt;urlpatterns&lt;/code&gt; list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    path('', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    path('json/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is what will help us view the swagger UI using routes.&lt;/p&gt;

&lt;p&gt;Now if we run our server we should see this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftumnmgd8v3x164b2z361.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftumnmgd8v3x164b2z361.png" alt="Swagger Image 1"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffn0lzgiw10h1ypwi1spv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffn0lzgiw10h1ypwi1spv.png" alt="Swagger Image 2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What we have done up to this point is to convert our drf UI into swagger UI in the browser, we haven't really implemented. &lt;/p&gt;

&lt;p&gt;If you check you can only see the endpoints our API has, to allow our API send &lt;code&gt;POST&lt;/code&gt; and &lt;code&gt;UPDATE&lt;/code&gt; requests we need to configure that too.&lt;br&gt;
Here is an example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj5k915p5it99s52ztlga.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj5k915p5it99s52ztlga.png" alt="Swagger Image 3"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We should be able to send &lt;code&gt;POST&lt;/code&gt; requests for our &lt;code&gt;create-product&lt;/code&gt; endpoint but we can't, we can see that there are no fields for us to add our data for out &lt;code&gt;POST&lt;/code&gt; request, but we can change that.&lt;/p&gt;

&lt;p&gt;We need to add this import to our &lt;code&gt;views.py&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from drf_yasg.utils import swagger_auto_schema
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;swagger_auto_schema&lt;/code&gt; is a decorator that helps us add the requests functionalities we need to our function based views. It takes several parameters, but the ones we're interested in are &lt;code&gt;method&lt;/code&gt; and &lt;code&gt;request_body&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;method&lt;/code&gt; specifies the type of request that is being sent to our endpoint.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;request_body&lt;/code&gt; specifies the serializer that the endpoint is going to use to send different requests, mainly used with &lt;code&gt;POST&lt;/code&gt;, &lt;code&gt;PUT&lt;/code&gt;, &lt;code&gt;PATCH&lt;/code&gt;, and &lt;code&gt;DELETE&lt;/code&gt; methods.&lt;/p&gt;

&lt;p&gt;To our &lt;code&gt;Create Product View&lt;/code&gt; we need to add this block of code above our &lt;code&gt;api_view&lt;/code&gt; decorator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@swagger_auto_schema(method='POST', request_body=ProductSerializer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After adding this, head on to your browser and see the effect of the change you've made, you should see this now: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiy9q1c9kkf9uqlmg1jxz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiy9q1c9kkf9uqlmg1jxz.png" alt="Swagger Image 5"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc8a3zoylbp8x7akasjev.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc8a3zoylbp8x7akasjev.png" alt="Swagger Image 6"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can see that there is a &lt;code&gt;required data object&lt;/code&gt; with the fields we specified in our serializer class which we will use to send a &lt;code&gt;POST&lt;/code&gt; request. To send a request, click on the &lt;code&gt;Try it out&lt;/code&gt; button and fill in the data object (if necessary) and hit &lt;code&gt;Execute&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We now need to do the same thing we did to our &lt;code&gt;Create Product View&lt;/code&gt; to our other views. Adding the &lt;code&gt;swagger_auto_schema&lt;/code&gt; decorator above the &lt;code&gt;api_view&lt;/code&gt; decorator of each view with their corresponding methods and request_body serializer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Read Product View
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@swagger_auto_schema(method='GET')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Update Product View
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@swagger_auto_schema(method='PATCH', request_body=UpdateProductSerializer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Delete Product View
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@swagger_auto_schema(method='POST', request_body=ProductSerializer)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now run your server and see the new changes take effect. &lt;br&gt;
With this you can now implement swagger UI into drf using function based views.&lt;br&gt;
If you find this article interesting and informative, kindly leave a like and share, and if you still have any questions, leave them in the comment section below. &lt;br&gt;
Cheers!!&lt;/p&gt;

</description>
      <category>django</category>
      <category>python</category>
    </item>
    <item>
      <title>Junior Developer</title>
      <dc:creator>Somtochukwu</dc:creator>
      <pubDate>Tue, 30 Jun 2020 23:05:38 +0000</pubDate>
      <link>https://dev.to/somto/junior-developer-1iea</link>
      <guid>https://dev.to/somto/junior-developer-1iea</guid>
      <description>&lt;p&gt;What does it take to be a junior developer? This has been the question I have been asking myself &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Why I code with python </title>
      <dc:creator>Somtochukwu</dc:creator>
      <pubDate>Mon, 29 Jun 2020 06:29:55 +0000</pubDate>
      <link>https://dev.to/somto/why-i-code-with-python-4051</link>
      <guid>https://dev.to/somto/why-i-code-with-python-4051</guid>
      <description>&lt;p&gt;Good morning guys, Somto here I'm here to share the reasons why I code with python and hope you'll also find it convenient to do so. I started learning python some time last year when I new to programming, my cousin adviced me to do so if I want to get started with any programming language because it was easy to understand. So after a while of python I decided to learn another language Java and man Java syntax wasn't funny things were strongly typed only to print out Hello world in Java I needed to have full understanding of OOP but in python all you need to do is enclose your Hello world text withing quotes (single or double) and within parentheses that's all. Asides that python is an all rounder you can use it can be applied in different areas ML and AI, backend development, Hacking, Game Dev, GUI and so on you name it, I'm just happy I started my programming career with python I can't wait to see what other things it has to offer &lt;/p&gt;

</description>
      <category>python</category>
      <category>devlive</category>
      <category>motivation</category>
    </item>
  </channel>
</rss>
