<?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 Fabricio Saavedra on Medium]]></title>
        <description><![CDATA[Stories by Fabricio Saavedra on Medium]]></description>
        <link>https://medium.com/@fabricio.saavedra91?source=rss-4eb7d0d22c8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wSM4xwQbf4Nt2PHNfaERUA.jpeg</url>
            <title>Stories by Fabricio Saavedra on Medium</title>
            <link>https://medium.com/@fabricio.saavedra91?source=rss-4eb7d0d22c8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:45:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fabricio.saavedra91/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[Using Django REST Framework to Quickly Get a Working API: part III]]></title>
            <link>https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-iii-8828a547dae6?source=rss-4eb7d0d22c8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8828a547dae6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 16:12:19 GMT</pubDate>
            <atom:updated>2023-07-13T16:12:19.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbY5lfwK-4KLUOcuCIgxDA.png" /></figure><p>As a conclusion for this three-part series of articles on “how to use the DRF (Django Rest Framework)” to get a working API, we will focus on two crucial yet overlooked (mostly by beginners) concepts for your API, authentication and permissions, also referenced as authorization. As stated in the conclusion of part II, up until this point, our API accepts requests from any origin, and it allows unrestricted modification of the information stored in the database, which won’t be the case for most projects, so we will check some of the tools the DRF has to improve the resource administration.</p><h3>Authentication and authorization as concepts</h3><p>Before we do any Django REST Framework documentation reference, let’s establish what it means to have an authorized request in the context of a microservices architecture since that will help us better understand the implementation in our simple mechanic shop API project.</p><p>According to<a href="https://auth0.com/docs/get-started/identity-fundamentals/authentication-and-authorization"> auth0 by Okta</a>,</p><blockquote>authentication is the process of verifying who a user is, while authorization is the process of verifying what they have access to.</blockquote><p>It’s just like when you visit a hotel — you let them know you’ve arrived, and depending on your reservation and payment information, you may or may not be able to access the mini-bar.</p><p>How does this get translated into our project? First, we’d like to know who is trying to access our API, so we’ll see how we incorporate authentication using what the DRF provides us.</p><h3>Authentication with DRF</h3><p>According to the <a href="https://www.django-rest-framework.org/api-guide/authentication/#authentication">very efficient documentation of the DRF</a>,</p><blockquote>authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with.</blockquote><p>Without having to install any third-party package, the DRF has support for five types of authentication schemes:</p><ol><li>BasicAuthentication is generally only appropriate for testing.</li><li>TokenAuthentication suits client-server setups and fits like a glove with what we are developing.</li><li>SessionAuthentication is meant for AJAX clients running in the same session context as your website.</li><li>RemoteUserAuthentication, which allows you to delegate authentication to your web server (APACHE or NGINX).</li><li>Custom authentication (implemented by subclassing the BaseAuthentication class and overriding the authenticate method).</li></ol><p>How do we specify the authentication scheme we want to use? We will always define them using a list of classes. Then the DRF will attempt to authenticate with each class in the list, and it will set request.user and request.auth using the return value of the first class that successfully authenticates.</p><p>Based on the nature of your project you can:</p><ol><li>Declare the list of authentication classes globally.</li><li>Set that list of authentication classes.</li></ol><p>Since the endpoints we have set are somewhat sensitive, we will set the authentication globally in the settings.py module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*M7IKisjoqJo-cXsR" /><figcaption>A reminder for where settings.py is located.</figcaption></figure><p>In that module, we will add a piece of configuration. In this case, as we previously stated, the TokenAuthentication class is what we want, so your configuration will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80849f150ccf9dbb59ea286bc2dbca7c/href">https://medium.com/media/80849f150ccf9dbb59ea286bc2dbca7c/href</a></iframe><p>Plus, this authentication scheme requires us to add the authtoken app to the INSTALLED_APPS configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8869172c0043cbf2152e8c86d3be3de9/href">https://medium.com/media/8869172c0043cbf2152e8c86d3be3de9/href</a></iframe><p>Having the rest_framework.authtoken app registered in the installed apps will provide some migration files to create a table to store the generated tokens, so you, as a very aware person, will know that we need to apply those migrations by running python manage.py migrate :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OY2WgjgQK9QyB8mU" /><figcaption>Migrations that were applied after adding the Token authentication config.</figcaption></figure><p>Before moving on, let’s attempt one of the requests we’ve made in part II to see what functional changes have been introduced by the additional configuration we’ve set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8jQKIbIlvxrLMCY" /><figcaption>Getting the vehicles list after adding TokenAuthentication.</figcaption></figure><p>We still are allowed to get the list of vehicles despite not providing any credentials that validate who we are. That’s because<strong> authentication by itself won’t allow or disallow an incoming request; it simply identifies the credentials with which the request was made</strong>. In this case, since we’re not providing information about who we are, the request.user variable will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. With that cleared out, we will consider the options we have to generate the tokens that inform the API of our identity.</p><h3>Generating a token</h3><p>a. in Django, you can have ‘listeners’ that act before or after a certain action or process with instructions that fit your needs, called signals. For example, we can make sure that after saving a User instance, a Token instance is generated and saved for the newly created user. IMHO, using signals can become rather tangled pretty quickly for moderately complex projects, and if you’re a beginner with Django, you probably are better off without using them.</p><p>b. Exposing an endpoint: when using TokenAuthentication , generating a token using a username-password pair seems rather convenient, so the DRF provides a built-in view to provide it by using the obtain_auth_token function. obtain_auth_token will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON.</p><p>c. Using Django admin: we didn’t mention this given the nature of our project, but Django has this useful interface that allows creating objects from models we defined using a built-in admin panel. Considering we’re building this API from a microservices standpoint, there’s not much use to it.</p><p>d. Using Django manage.py command: the CLI utility that gave us the ability to start the project and add apps to it, generating migration files and applying them, also makes it possible (for version ≥ 3.6.4) to generate a user token by running:</p><p>python manage.py drf_create_token &lt;username&gt;</p><p>which will return the API token for the requested user, generating one if it doesn’t exist yet.</p><p>The option that better fits our requirements, both didactically and functionality-wise, is generating the token with the built-in view obtain_auth_token. To reach that functionality, we need to specify a path for it in the URL patterns we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b2fd8286b2073536af30ef757c42d0/href">https://medium.com/media/31b2fd8286b2073536af30ef757c42d0/href</a></iframe><p>Then we will generate an ad-hoc user to get a token and present a general Django tool that I use quite frequently in my projects and find helpful, which is the<a href="https://docs.djangoproject.com/en/4.1/ref/django-admin/#shell"> “Django shell</a>.” The Django shell allows us to open an interactive Python interpreter with the context of the Django project we’re in, so doing the following is totally valid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*q73GvAhLnvdazktU" /><figcaption>Using the Django shell to create a user.</figcaption></figure><p>Notice that we’re leveraging the create_user method of the User model (<a href="https://docs.djangoproject.com/en/4.1/ref/contrib/auth/">another feat of Django)</a>, instead of directly using the create method. Otherwise, we wouldn’t get a hash of the password we specified, and our information would be compromised if anyone found a vulnerability in our system.</p><p>Ok, now let’s try to get a token for Salvatore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*RB4xNfS7Vf1-p56y" /><figcaption>Obtaining a token for Salvatore.</figcaption></figure><p>Yes! By obtaining a token, we can authenticate our requests to the API. As we noted before, we didn’t specify any authorization scheme yet, so our requests are still passing, but now the request.user will be correctly set to an instance of the User model (Salvatore in this case) once we include the token in our request headers, which will be fundamental to testing our permission classes.</p><p>To summarize, in a client-server architecture, we would:</p><ol><li>Obtain a token by making a POST request to /api/api-token-auth and retain or store that somewhere (when using a browser, we tend to store it in localStorage).</li><li>Set that token in the header for all our subsequent requests as follows:</li></ol><pre>&quot;Authorization&quot;: Token 81e584aebd6ccf9771ececd44234fb660aabc8a</pre><p>3. Send the request we want or need.</p><h3>Authorization (permissions)</h3><p>Along with authentication and<a href="https://technical-qa.com/what-is-request-throttling/"> throttling</a> (out of the scope of this series), permissions determine whether a request should be granted or denied access (even though what access is, is a relatively open definition).</p><p>Similar to authentication, permissions checks are always run before the main block of code of the view (usually the method handler for POST, GET, etc.) and will be typically associated with the identity established in the authentication process and stored in the request.user and/or request.auth objects</p><p>As stated in the<a href="https://www.django-rest-framework.org/api-guide/permissions/#permissions"> documentation</a>,</p><blockquote>The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.</blockquote><p>So, similarly to authentication, we’re using classes to establish permission either globally or per view, and before running the main body of the view, every class in the list is checked. If any permission check fails, a PermissionDenied or NotAuthenticated exception will be raised, and the main block of code won’t run.</p><p>Back to our project, let’s suppose that for some reason, you can use the endpoint to list the vehicles just by verifying your identity, which in our project, is achieved by passing the token in the Authorization header. Having that in mind, we’re going to import and set the IsAuthenticated permission class to the permission_classes list in the VehiclesList class-based view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab84fd3fd405df36ae8cb5e4504f0598/href">https://medium.com/media/ab84fd3fd405df36ae8cb5e4504f0598/href</a></iframe><p>Now, we are going to start the Django application and send a GET request to api/vehicles endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RJ73MKxTAg_JhejJ" /><figcaption>GET request after adding the IsAuthenticated permission class.</figcaption></figure><p>We got a 401 status code (Not Authorized) and a very clear message stating that we didn’t provide authentication credentials, which is true since we didn’t provide the Authorization header. So let’s try the same request after doing that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HPuLd_h1GDDqL0P5" /><figcaption>Successful request after properly authenticating.</figcaption></figure><p>Your day ends better when things go that smoothly. Why did that work? Inspecting the IsAuthenticated class might help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*Xr2fysx-OMiN3jz2" /><figcaption>IsAuthentication class definition.</figcaption></figure><p>Simple and effective. As that simple line reads, having truthy values for request.user and request.user.is_authenticated is enough to have permission, thanks to the TokenAuthentication class.</p><p>Ok, you might say holding your chin with your fist, but this is some generous permission policy to apply to a serious project, how can we implement something more specific? Glad you ask!</p><p>You can define any logic you want in a custom permission class. To write your own permission class, you just need to subclass the BasePermission class and implement has_permission and/or has_object_permission with the following signatures:</p><ul><li>has_permission(self, request, view)</li><li>has_object_permission(self, request, view, obj)</li></ul><p>The implemented methods should return True if the permission to access the resource is granted, and False if not.</p><p>To give a colorful example, let’s assume that Salvatore is an exemplary employee and Mario is not, so we don’t want Mario snooping around. We will create a permission class that implements some logic to prevent Mario from accessing resources. But since Mario doesn’t exist yet in our database, we need to add him using the User model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*w4jJ-SwIYYjbMhEJ" /><figcaption>Adding Mario.</figcaption></figure><p>Now, we need to create our custom permission class. We will add a new permission_classes module in the customers app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*iNHkUIECnXs2zew6" /><figcaption>New permission classes module.</figcaption></figure><p>The logic we want to implement is the following:</p><ul><li>If the request doesn’t have an authenticated user, reject it.</li><li>If the request is authenticated, but the user is Mario, reject it.</li><li>If the request is authenticated, and the user is not Mario, allow it.</li></ul><p>So that will translate into:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1401982d55331d3cf1881c4630818fbe/href">https://medium.com/media/1401982d55331d3cf1881c4630818fbe/href</a></iframe><p>You’ll notice that the last condition is exactly the same that is used in the IsAuthenticated class, so in theory, we could subclass it, and then call the super method, but to illustrate the custom class and avoid extending on<a href="https://www.geeksforgeeks.org/python-super/"> inheritance</a>, we will stick to our current approach.</p><p>To test our new class, we need to add it to the permission_classes list in the CustomersList class-based view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30ddae80f0a4c0835421155cfddf346/href">https://medium.com/media/a30ddae80f0a4c0835421155cfddf346/href</a></iframe><p>A non-authenticated request will throw a classic 401, as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FtFRpo2sJUhG-tXc" /><figcaption>Not authenticated request.</figcaption></figure><p>What will happen with a “Mario-authenticated” request? After obtaining a token for Mario and making a request to get the customers list, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-TO-l_5fwRWyscPk" /><figcaption>Authenticated request for Mario.</figcaption></figure><p>We got a 403 status code, which means the request is authenticated (we know Mario is behind it), but it’s not authorized (Mario is not allowed). Finally, we are going to attempt a request to the same endpoint but for Salvatore (notice that the token now belongs to him):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*GkVU-gUr35YeUNFH" /><figcaption>Authenticated request to api/customers for Salvatore.</figcaption></figure><p>Working as expected! Our custom permission class:</p><ol><li>Does not allow unauthenticated requests.</li><li>Does not allow authenticated requests from Mario.</li><li>Allows authenticated requests from anyone else.</li></ol><h3>Conclusion</h3><p>Congrats! You made it through this series of articles. Hopefully, you now have a deeper understanding of how we can:</p><ol><li>leverage the DRF to keep out code DRY by using class-based views,</li><li>represent information that resembles the structure of the models we defined,</li><li>and lift a basic yet effective wall against curious people with a simple yet illustrative example project.</li></ol><p><strong>Next steps? Try some of these:</strong></p><ul><li>Look up how we can expose locally our API to have it listen to requests coming from a client (a frontend app).</li><li>Try to nest representations of information by using custom serializers as fields.</li><li>Connect an email server to send information from your Django app whenever a new user is created.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8828a547dae6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-iii-8828a547dae6">Using Django REST Framework to Quickly Get a Working API: part III</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django REST Framework to Quickly Get a Working API: part II]]></title>
            <link>https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-ii-c19b950e86f3?source=rss-4eb7d0d22c8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c19b950e86f3</guid>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 19:02:34 GMT</pubDate>
            <atom:updated>2022-11-09T19:02:34.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCGNgvDm3czzdqL2PaZ43g.png" /></figure><p>In the <a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95">first part</a> of this three-part series of articles, we set up the base of a Django project to build an API leveraging some tools provided by the DRF. In this article, we’ll pick up where we left off. We’ll introduce you to the views responsible for request handling.</p><h3>Views</h3><p>Django uses a <a href="https://developer.mozilla.org/en-US/docs/Glossary/MVC">Model View, Controller (MVC) architecture</a>. The Django dev team <a href="https://docs.djangoproject.com/en/4.1/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names">gives their interpretation</a> of what this means for its project, but basically:</p><ul><li>The model is how we organize information in the database. Django uses the model abstraction to establish how the database tables are organized and how they relate to each other.</li><li>The view describes the data that gets presented to the user. It’s not necessarily how the data looks but which data is presented. This is achieved with Python callback functions, such as the functions we specified in the urlpatterns variable.</li><li>The controller is the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.</li></ul><p>The rules the views use to decide what information needs to be presented to the user can be expressed by decorators or by <a href="https://www.tutorialspoint.com/python/python_classes_objects.htm">class members</a> if we’re using class-based views. And just like that, we got into naming one of the cool features that come from using the DRF: <strong>class-based views</strong>.</p><p>For fairly simple APIs, we use Django to perform repetitive CRUD operations on tables, that is, on rows in a relational database. Writing the instructions to perform those operations can quickly become time-consuming, and the statements themselves can end up being quite verbose, even with a concise programming language, like Python. To mitigate that, the DRF comes with a set of generic API views, classes from which you can inherit to avoid writing repetitive code by specifying class members to fit the needs of your business logic. As we have pointed out, views are functions, so to comply with this, we call the as_view method on the classes that inherit from the generics when we pass them as arguments to the path function call. Remember this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06486a01ffa3974712ac1ba96e80ebff/href">https://medium.com/media/06486a01ffa3974712ac1ba96e80ebff/href</a></iframe><p>If we go through the DRF<a href="https://www.django-rest-framework.org/api-guide/views/"> documentation for API views</a>, we will see that the DRF offers two ways to build a view:</p><ol><li>Class-based views (CBV from here on).</li><li>Function-based views (FBV from here on).</li></ol><p>Both take a Request object and return a Response object (instead of Django’s HttpRequest and HttpResponse respectively), but their use cases are different.</p><p>With FBV, what you see is what you get. Method handling is done by conditional branching and reusability is implemented by using decorators (not without some considerable limitations). For simple views, you can’t complain about them. Take this example<a href="https://www.django-rest-framework.org/tutorial/2-requests-and-responses/#pulling-it-all-together"> from the documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*pK6cTgcKbFfn1_f9T-c7jQ.png" /><figcaption>A FBV to handle snippets objects.</figcaption></figure><h3>Class-Based Views and Serializers</h3><p>You’ll want to use CBV to improve method separation and keep your code DRY. The views module from rest_framework provides the APIView class, which subclasses the Django View class. As we previously stated, the APIView class takes a Request object and returns a Response object (rigorously, the handle methods of the APIView class does that), but also API exceptions will be caught and mediated into appropriate responses. Last but not least, incoming requests will be authenticated, and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. This seems like a lot of features just from inheriting from the APIView class, but that is the beauty of using CBV, and they leverage on mixins and multiple inheritances. To illustrate that, we’ll come back to our project.</p><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95">In part I of this series</a>, we defined VehiclesList and CustomersList and we knew that they were CBV, but not much more than that. For this simple project, I’d write the following VehicleList class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*2Wv69aEgu7nWqkoN_hHZhw.png" /><figcaption>The class definition for the view.</figcaption></figure><p>Ok, what’s that? What is serializer_class? What is ListCreateAPIView? What is VehicleSerializer? That’s just 10 lines long, but many concepts are packed in there, so let’s break them down. Since generics it is imported from the rest_framework module, I think it’s fair to start from this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2pN0780QNAjdj-sIry3Baw.png" /><figcaption>The class definition for ListCreateAPIView.</figcaption></figure><p>The<a href="https://peps.python.org/pep-0257/#what-is-a-docstring"> docstring</a> is pretty straightforward. That’s what it does, but how? We see that ListCreateAPIView has definitions for handling the GET HTTP method and the POST HTTP method. Both HTTP methods rely on instance methods (list and create), but we can’t see any definition for them directly. The class signature states that ListCreateAPIView inherits from ListModelMixin, CreateModelMixin, and GenericAPIView , so it seems logical to keep pulling the thread on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*r83YBpq37Flv0BCiGEtpww.png" /><figcaption>Class definition for ListModelMixin.</figcaption></figure><p>Ok, now we know where that list instance method came from in the ListCreateAPIView class. Just by reading the method definition, we can get an idea of what it does. Somehow, we get a<a href="https://docs.djangoproject.com/en/4.1/topics/db/queries/#retrieving-objects"> queryset</a> and then filter it to store it in the queryset variable. If the paginate_queryset method returns a truthy value, the list method returns a paginated response of the serializer data, which, oversimplifying, is the queryset in an understandable format for Javascript. If page is a falsy value, we return a non-paginated response with the serializer data. We still haven’t got a formal definition of what a serializer is, but that was some nice piece of self-documented code. Notice that we don’t see any definition for get_serializer, get_queryset, filter_queryset, and so on, but given that this is a<a href="https://www.pythontutorial.net/python-oop/python-mixin/"> mixin</a>, it makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Hq23snBcvmeqFOmcFQzrqw.png" /><figcaption>The class definition for CreateModelMixin.</figcaption></figure><p>Intuitively, the CreateModelMixin would be the place where we could find a definition for the create instance method. It gets a serializer, but instead of passing a queryset or a page to the get_serializer method, it passes a data keyword argument with the request data as a value. Then it validates the serializer, saves it (assuming everything is ok with the validation), and returns the serializer data in an Response object. Why do we have to run a validation on the data in this case? We’ll get to that later on.</p><p>Finally, if we inspect the GenericAPIView class, we’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*uJ7q1C2sjByPmuF5i4auug.png" /><figcaption>Class definition for GenericAPIView.</figcaption></figure><p>Ok, that’s a lot, but you can see that this class has the method definitions we saw both in ListModelMixinand CreateModelMixin. Let’s inspect the most important ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*kU_tSZcVhhnJwgZtnW7R5g.png" /><figcaption>get_queryset function definition.</figcaption></figure><p>get_queryset makes an initial check on the presence of a queryset class member. If it exists, it checks that it is in fact, a queryset, evaluates, and returns it. I compressed the docstring for readability, but it basically says<a href="https://www.django-rest-framework.org/api-guide/generic-views/#attributes"> why we need to get the queryset using this method</a>, especially if we’re overriding the method handlers. What about get_serializer?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*mLjZUnzskYlUU6Xq_8ulNg.png" /><figcaption>get_serializer function definition.</figcaption></figure><p><em>Docstring</em> gave it all away here, get_serializer takes whatever arguments it receives and generates a serializer instance with that. Calling get_serializer_class just returns the serializer_class class member defined in the CBV that inherits from GenericAPIView, after asserting it is not “None”.</p><p>Still, <strong>what is this serializer we’ve been mentioning?</strong> The <em>docstring</em> indicates that a serializer instance <em>should be used for validating and deserializing input, and for serializing output.</em> Furthermore, the<a href="https://www.django-rest-framework.org/api-guide/serializers/"> documentation</a> indicates:</p><blockquote>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</blockquote><p>It couldn’t be clearer than that. The VehiclesList CBV has two HTTP method handlers.</p><ul><li>When it receives a GET request, the get function will perform a list the operation, which is meant to read information or strictly talking, serializing output, from Django querysets and objects to Python datatypes, which can be rendered into JSON (as to say, understandable to a React app).</li><li>On the other hand, when it receives a POST request, the post function will perform a create operation, which “creates information” by validating input and creating Django model instances.</li></ul><p>So, by defining a serializer class and passing information to it, we can:</p><p>a. Convert Django objects and Python datatypes to JSON, XML, etc.</p><p>b. Convert input into a Django object if said input complies with the validation</p><p>In our brief but conceptually strong example, we defined the serializer_class class member with, but didn’t get to see how the latter was defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*4iIOPAfg17iJlGynKfkwgQ.png" /><figcaption>VehicleSerializer serializer definition.</figcaption></figure><p>We’re clearly taking advantage of the DRF since we’re importing from rest_framework the serializers module, and then inheriting from the ModelSerializer class attribute.<a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer"> Another peek at the documentation</a> will shed some light on what a ModelSerializer is:</p><blockquote>Often you’ll want serializer classes that map closely to Django model definitions.</blockquote><blockquote>The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.</blockquote><p>So the ModelSerializer comes in really handy when we want to serialize and deserialize information in fields which resemble a Django Model we have defined.</p><p>In the Meta class, we define some basic information to tell the serializer how it should behave (actually this is a Django pattern, not a serializer thing since we can define Meta for a model definition too). In this case, we specify that the model we want to map is Vehicle. The fields Meta member will specify which model fields we want the serializer to use by defining a tuple or list of strings with field names. You can set this attribute to the special value __all__ to say that all model fields should be used. Since version 3.3.0, it’s mandatory to define this class member (or its counter-part exclude).</p><p>A ModelSerializer provides three really useful features:</p><ol><li>It will create a series of serializer fields from the model.</li><li>It will include a validator for each of the fields.<br> — Do you remember that when we were using the create method of the CreateModelMixin, it had to run a validation on data? That’s because, for new objects, it needs to make sure the input data doesn’t break the rules for the target model.</li><li>It will include default implementations for create and update (the former will be called if we’re not passing an existing instance to the serializer class along with the request data, and the latter if we do).</li></ol><p>Before we test the functionality of our VehiclesList view (that sounds very far at this point, right?), we need to update the Vehicle model. We’d like to illustrate something cool about serializers. But first, we need to add a field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTNAnPH8N4EBIWTPfQdEvA.png" /><figcaption>Updated definition of Vehicle model.</figcaption></figure><p>In the initial definition of Vehicle, we didn’t say <em>“we want this vehicle to be related to this customer”</em>. Imagine the mechanic shop has wealthy customers. There is a chance that a customer will have many vehicles, but a vehicle can only be owned by a customer. This kind of relation is a one-to-many relationship, and it’s commonly represented by using a ForeignKey field. In relational databases, it means a row in the table customers is related to many rows in the table vehicles. Since we’re altering the Vehicle model definition, we need to generate a migration file to communicate this change to the database schema. Then migrate will commit the newest migration files:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>By now, you should be able to<a href="https://docs.djangoproject.com/en/4.1/ref/django-admin/#runserver"> start a development server</a> by running:</p><pre>python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p7rZ3Lmy-Luxc1TrqrO3g.jpeg" /><figcaption>Successful start of the development server.</figcaption></figure><p>By default, this development server runs on port 8000. If you’re getting a log similar to the one in the picture above, it means your server started without errors, but that doesn’t mean it won’t crash when we actually make requests to it.</p><p>We will use<a href="https://www.postman.com/downloads/"> Postman</a> to see what happens when we make some requests to the paths we have previously exposed. You can use curl or any other utility to make the request, but for the sake of illustration, I’ll prefer a GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzYb4POUf6rJ8Aoz2Qbltg.png" /><figcaption>GET request for /api/vehicles.</figcaption></figure><p>If you remember, making a GET request to the /api/vehicles path performed a list operation from the VehiclesList CBV, returning the serialized data from the queryset of that view. Since we didn’t create any vehicle, it’s natural to receive an empty array as a response. It’s in our hands to have the GET request to return something more interesting. Let’s try to make a POST request to the same path, but we’re going to have an empty body for this attempt to see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_Hyp01NafKXx-x3-t91ZA.gif" /><figcaption>POST request to /api/vehicles/ with empty body.</figcaption></figure><p>That’s a very informative response. We got a 400 status code (bad request) and an indication of the fields required to make a successful request. At this point, it’s only saying “we need you to define these fields” but it doesn’t say anything about the data types for the values of those fields. Let’s send a more convenient POST body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dk8tGbSkImP36hgrzoaHcw.png" /><figcaption>POST request to /api/vehicles/ with validation complying data.</figcaption></figure><p>That returned a 200 status code and a serialized representation of the Django object created. We see that it automatically added a id field with a value 1 for it. That means we did a successful insertion in the vehicles table and that the information was saved in a row with an id equal to 1.<a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#primary-key"> Django has that default behaviour</a>, and you can review or update that in the VehiclesConfig class that was generated when we started the vehicles service/app, or globally if you want to change the behaviour across the entire project.</p><p>Ok, that seems pretty easy, we send the fields required, and we create a Django object, right? Let’s try to insert another car, but this time let’s pass the kilometers as a string, and the last oil check date in another format (MM/DD/YYYY):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OzmAen92M1N_MBpOQ5CKw.png" /><figcaption>POST request to /api/vehicles/ with different input.</figcaption></figure><p>Bad request on sight! The built-in validation from using a ModelSerializer is very clear, the last_oil_check datetime field does not accept that format right out of the gate. It didn’t bother about passing the kilometers as string, presumably because it did a type cast, but it had its concerns about the datetime format, so let’s accommodate that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FjdA8rFLSH1WHncR9ZW3g.png" /><figcaption>POST request to /api/vehicles/ with corrected payload.</figcaption></figure><p>Another successful insertion! Two things to notice here. First, it inserted the second object with id equal to 2. Cool! In the first insertion and this one, we received responses customer equal to null. That’s because the customer field we defined in the Vehicle model took blank=True and null=True as arguments, or, in other words, we didn’t make it a required field. We didn’t create a single customer before making the POST request to the vehicles endpoint neither, so we wouldn’t know what to send there. Still, being a SQL-type database, we can’t omit that “column” when we save the data.</p><p>If you were following along and you try a GET request now, things will look different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3-QF_vsJN1UOWrBgnQ0_w.png" /><figcaption>GET request to /api/vehicles.</figcaption></figure><p>Those ten lines of code in the vehicles/views.py module, plus the serializer definition, gave us the ability to list and create Vehicle objects. For simple operations, using the appropriate generic view will be enough most of the time.</p><p>What if we try to define a customer while inserting a vehicle? We must define the CBV for listing and creating Customer objects first, but that’s pretty similar to what we’ve done for the Vehicle objects, so I won’t write the details and you can take that as an exercise or<a href="https://github.com/fabriccio27/drf_tutorial/commit/c0d3fa926efde61937b895e8711dcae6f517a0de"> check the repo</a> to make sure you got the idea. Once we defined the serializer class and the CBV CustomersList we can make an insertion like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmxIng_kDKcLE-Q0-U1hfg.gif" /><figcaption>POST request to /api/customers/</figcaption></figure><p>Ok, now that we successfully inserted an Customer object, how would we specify that a vehicle belongs to a certain customer while inserting? We know that Vehicle it has a foreign key field for customer, so maybe we can try the following request body:</p><pre>{<br>    &quot;name&quot;: &quot;Civic&quot;,<br>    &quot;brand&quot;: &quot;Honda&quot;,<br>    &quot;kilometers&quot;: 7000,<br>    &quot;last_oil_check&quot;: 2021-12-31,<br>    &quot;customer&quot;: 1<br>}</pre><p>If you make a POST request to /api/vehicles/ with that body, you’ll get a 201 status code. Don’t believe me?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKnM2v03FyEzwGYNTYPVTg.png" /><figcaption>POST request to /api/vehicles/ defining a customer.</figcaption></figure><p>Yeah, it worked, but wouldn’t it be more intuitive to define customer_id = 1 while specifying the relationship? Probably, but by default, while using the ModelSerializer,<a href="https://www.django-rest-framework.org/api-guide/relations/#inspecting-relationships"> serializer fields and relationships will be automatically generated for you</a>. ForeignKey fields use the PrimaryKeyRelatedField serializer field by default, so that’s the reason why we directly pass an id to customer. Of course, you could override this behaviour to pass a customer_id, and exclude the automatically generated customer serializer field.</p><p>Another pertinent question: is it useful to receive a response with customer represented by an id? It’d be more practical to receive a response with more descriptive information about the customer (name, address, etc). You can write<a href="https://www.django-rest-framework.org/api-guide/relations/#nested-relationships"> nested representations</a> to achieve that, but that would require us to override the get method in the CBV to use a different serializer class from the one used to perform create operations, and I believe that would be a little out of the scope of the present article.</p><p><strong>That was a lot.</strong> We need to digest this as if it was a big plate of spaghetti. Just a last question playing the part of a digestive expresso. Do you think it is cool to have your API exposed <strong>so that anyone</strong> with its URLs can get to read and insert data in your database? Most definitely, it is not. Authentication and permissions are the next and last topic in this three-part series on building an API with DRF, so stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c19b950e86f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-ii-c19b950e86f3">Using Django REST Framework to Quickly Get a Working API: part II</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some takeaways on jumping to the remote developer train]]></title>
            <link>https://medium.com/@fabricio.saavedra91/some-takeaways-on-jumping-to-the-remote-developer-train-7637a8b15b46?source=rss-4eb7d0d22c8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7637a8b15b46</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[remote-working]]></category>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 01:35:54 GMT</pubDate>
            <atom:updated>2022-09-27T11:17:19.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Wmc-UKp1Bnh78rUfHNedg.jpeg" /></figure><p>It’s been a year since I started working as a software engineer in <a href="https://www.linkedin.com/company/nicasource/">Nicasource</a> and let me tell you when you do what you like in a great environment time flies. A year ago, Adriana gave me a call saying that the tech team liked what I presented in my technical assessment and saw my potential (bear in mind, I’m a 30 a y.o. chem engineering grad with no relevant formal experience at that timeframe so I’m kind of a gamble). The tale of a guy with no tech background (and in my case no programming bootcamp) is so old it tells itself but believe it or not, people (friends, other professionals, other devs) come and ask me, how can I get a job in tech, what programming language should I learn first, how do you improve your skills while working. I don’t think there’s an absolute answer for that type of question, nor that I’m fully capacitated to shed light on them but I’m going to lay out some takeaways based on my personal experience in case anyone finds them useful</p><h3>Pre-job:</h3><p>Learn English. Can you be a decent software engineer without knowing it? Probably. Will knowing English (speaking and writing) make the learning process smoother? Absolutely.</p><p><strong>Try free courses before spending money on bootcamps or paid certifications</strong>. Maybe programming isn’t for you (you appreciate a healthy back or fancy going to bed without thinking about that bug you couldn’t solve). Jokes aside, there are tons of free resources to use (freecodecamp, CS50, algorithms course from Robert Sedgewick, youtube in general, free ebooks) to dip your toes into before reaching your wallet, especially if you’re unemployed.</p><p><strong>Build a relevant portfolio</strong>. Having a portfolio with the same projects everyone has doesn’t cut it. Put your own twist on it, or create pieces of software that although may not have marketability, will demonstrate to the recruiters that you can come up with solutions on your own.</p><p><strong>Learn Git</strong>. If you have a relevant portfolio you probably know your way around basic git, but take a course or tutorial to be familiar with how to do a cherry-pick or solve merge conflicts.</p><p><strong>Practice the interview questions</strong>. Believe it or not part II, I interviewed people that wanted a position in the company, and there are not many things more mind-boggling than people that don’t do their research. Do you want that React dev position? Know your hooks, know asynchronous programming. Google “react interview questions”, they will be asked, and not knowing ANY of them will stand as a massive red flag. Additionally, be prepared to answer those questions in English too.</p><h3>In the job:</h3><p><strong>Understand the codebase</strong>. You landed the job, your family is happy for you, and you took your partner to a nice place for dinner in celebration, but now it’s time to earn your paycheck. Some tips on how to hit the ground running? Use the piece of software and understand the flow of information, write notes on paper if necessary (probably won’t need them later, but will let you know if you truly understand what is happening). If you don’t have a mentor in your induction process, look for one and ask him/her, which are the key classes, services, or components in the project and play with them.</p><p><strong>Understand the tasks you’re given</strong>. If the team works with Scrum, read the acceptance criteria. Don’t waste time doing things you weren’t asked for (unless you finished all of your highest priority duties). If the task is too big, break it into smaller chunks. Double-check the expectations on the work to be done.</p><p><strong>Learn as you go</strong>. Sometimes as a jr or a trainee, you’ll have cold feet on whether to apply to a job or not because of your current expertise with the tools you handle, but IMHO, you’ll learn the most while working. Leverage code that was written by other devs to incorporate tricks or patterns for your toolbox. If you find yourself struggling with a concept or type of task, watch a video on the subject. E.g. I ran into a wall when trying to override styles on MUI components or making nice-looking components altogether → took a Udemy course and started to apply new things. Try to find things on your own before asking where changes should be done (this is also a great opportunity to check if you understood the codebase. If so, you’ll know where to tighten the screws).</p><h3>All the time:</h3><p>Go into Medium from time to time to read an article. You often find interesting notes on new releases or optimizations for the tools you use. I said from time to time because there’s a chance that a Medium overdose might increase your FOMO levels.</p><p><strong>Don’t do things that don’t add value</strong>. If you feel like there’s not enough time to get the skills you need to get a job or get better at it, try to spend less time on social media or streaming platforms. If you need the time to relax while watching a screen maybe watch a documentary on computer science or something similar.</p><p><strong>Measure you against you</strong>. There will be times when you will be tempted to scream at your screen while debugging or feel sieged by impostor syndrome waves. Take a moment to see where you were standing a week or a month ago. Hopefully, you’ll come to see that you’re more skilled or tackling more complex problems.</p><p><strong>There’s no bible.</strong> If you’re new and you’re receiving advice, try to discern what is a good practice and what is a personal preference from the advisor. What works for you may not for others so don’t break a sweat if the recommendations you received feel awkward for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7637a8b15b46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django REST Framework to Quickly Get a Working API]]></title>
            <link>https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95?source=rss-4eb7d0d22c8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe5dec69d95</guid>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 18:01:38 GMT</pubDate>
            <atom:updated>2022-08-30T19:00:09.176Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sGDlF2xltBoASAVYQN33w.png" /></figure><p>Despite starting as a <a href="https://www.artima.com/articles/the-making-of-python">successor of a “teachable” programming language</a> project, Python has made a long way and, by <a href="https://www.infoworld.com/article/3632862/python-slithers-toward-top-of-language-popularity-index.html">2022 is still one of the most popular</a> and <a href="https://levelup.gitconnected.com/programming-languages-with-the-highest-amount-of-listings-indeed-glassdoor-linkedin-and-upwork-549a1c4618be">required programming languages in job openings</a> with no sight of a trend turn.</p><p><a href="https://bit.ly/dev-Python-NS9"><strong>bit.ly/dev-Python-NS9</strong></a></p><p>In web development, there are trendy frameworks written in Python and used in different scenarios. One of the most robust options is Django, which allows us to build complete web applications (front-end and backend) with an ORM included for SQL-type databases (no need to install external libraries to develop).</p><p>Despite having the ability to build interfaces, it doesn’t mean you need to build the front-end using plain Django. Dynamic content may be tricky if you’re unfamiliar with templates similar to <a href="https://jinja.palletsprojects.com/en/3.1.x/">Jinja.</a> If you know some front-end library or framework, you could pair that with an API built in Django; that’s where things get interesting! You can power up your web app with the features of React. The <em>Django REST Framework</em> (DRF) is a library that provides multiple tools to quickly set up a working API, including class-based views and serializers.</p><p>In this three-part series of articles, we’ll build this API for a mechanic shop by setting up the project, describing some endpoints, and laying out permission classes for them.</p><h3>1) Setting up the project</h3><p>I’ll assume you’re working with a UNIX-like system, so you’ll probably want to make a new folder for this project and create a Python environment with the tool you deem suitable. I’ll use venv:</p><pre>mkdir mechanicshop<br>cd mechanicshop<br>python -m venv env<br>source env/bin/activate<br>pip install django djangorestframework</pre><p>In the environment, you will be able to start a project (a group of apps/services) by executing:</p><pre>django-admin startproject mechanicapi</pre><p>The command will add a series of folders and files inside the mechanicapi directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*nMgNzWCvGlrGrl9a" /><figcaption>Initial directory structure.</figcaption></figure><p>Out of the above shown structure, two modules are fundamental, settings.py and manage.py. In the first one, you will describe configurations for your project, such as database connections, middleware, and installed apps (apps that will run in this project). In the latter, we have a command-line utility to interact with the project differently. By using the manage.py utility, we will add apps to our project. Say we want our app to handle the vehicles inventory of a mechanical shop.</p><p>We will start by adding a vehicles to the app:</p><pre>python manage.py startapp vehicles</pre><p>We will then want a service to handle the customers’ data:</p><pre>python manage.py startapp customers</pre><p>By running the previous command, we will add some template files to a folder. The files will be named after each app we created in the previous steps. As a result, we will have a directory with a similar structure to the one shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*abm9RWr0rg5k1TsYMvhWFg.png" /><figcaption>The mechanicapi project contains two services: customers and vehicles.</figcaption></figure><p>If we want Django to recognize the services, we need to include them in the settings.py module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*mEWMvNvrEDrJzRqlaRmDYw.jpeg" /></figure><p>Above you can see how it should look in the settings.py module.</p><p>The next step will be to add the URL config to the project’s URL for each service we defined. The previous needs to be made because we will be hitting the endpoints by making requests to URLs. For example, to add the URL config for the customer service:</p><ul><li>Go to the service directory and create a urls.py module.<br>– We’ll then revisit this section.</li><li>Then go to the project level urls.py module, import the customers module, and add the service URL config.</li></ul><p>Repeat the process above for the vehicles service, and you’ll end up with something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/559c7a05cd66240d16fd00e53b85b99d/href">https://medium.com/media/559c7a05cd66240d16fd00e53b85b99d/href</a></iframe><p>Now, we are ready to define models for each service. Usually, models translate to a table in your database (<a href="https://docs.djangoproject.com/en/4.0/ref/models/options/#available-meta-options">unless you say otherwise</a>). For the sake of this article, we’ll define only two models, one for each service.</p><ol><li>The Vehicle model, which is meant to represent cars, but motorcycles could also be considered eligible.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac35f6ce31ddb0633d18a12e2b143f40/href">https://medium.com/media/ac35f6ce31ddb0633d18a12e2b143f40/href</a></iframe><p>2. The Customer model will represent the customers’ contact information. We won’t have them signing up in any place, so it won’t be a one-to-one relation with the user model from django.contrib.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3b581622bedfb796adce009627e610a/href">https://medium.com/media/c3b581622bedfb796adce009627e610a/href</a></iframe><p>To wrap up this first part of the series, we’ll return to the URL config of the services. If the front-end app hits the endpoints from the API, the data will persist in our database . In the URL config module for the vehicles service, we’ll add paths (as a list called urlpatterns) so that a client can make requests to those paths and get or modify information related to vehicles.</p><p>The path function takes four arguments, out of which, <a href="https://docs.djangoproject.com/en/4.0/ref/urls/#path">two are required</a>.</p><ul><li>The first argument is the route.<br>– In this example, you’d request <a href="https://somedomain.com/api/vehicles),">https://somedomain.com/api/vehicles/</a></li><li>The second one is the view.<br>– These are functions or classes responsible for handling the request.</li><li>The third and fourth are keyword arguments.<br>– The order in which you specify them doesn’t matter as long as you prepend the correct key for them. The arguments will have default values if you don’t define the actual parameter in your function call, which makes them optional. Following the function signature from the documentation, the third argument is kwargs, meant to receive a python dictionary with additional information. The fourth is a developer-friendly name (so you can refer to this path more easily while testing, for example).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5f4aa1f8e2848e1fc4bdd3f21d1a94d/href">https://medium.com/media/d5f4aa1f8e2848e1fc4bdd3f21d1a94d/href</a></iframe><p>As you may have noticed, to pass the second argument, we had to (1) import the views module, (2) call its attribute VehiclesList, and then (3) call the as_view method on it.</p><p>What does that mean?…<br>You could go and read the docs, or … wait until part II of this series!</p><p>But before I let you go, let’s make some manual checks!</p><p>To ensure that the models we have defined comply with the rules expected by the Django ORM, we’ll generate the migration files for each service. The <a href="https://docs.djangoproject.com/en/4.0/topics/migrations/#module-django.db.migrations">migration</a> files describe the changes in the models that we want to propagate to the database schema. Making these kinds of changes is a two-step process. First, we will tell Django to generate the migration files for all the installed apps based on model changes we defined (<a href="https://docs.djangoproject.com/en/4.0/ref/django-admin/#makemigrations">unless you tell it</a> differently):</p><pre>python manage.py makemigrations</pre><p>If everything goes okay, you’ll see a summary of the migration files created in your terminal and new modules in the migration directory for each app with model changes. If, on the contrary, something fails, you’ll get some exception displayed that will put you in the right direction to fix eventual issues. <strong>Pro tip:</strong> If you are new to Django, it probably be something related to the field definitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Rf6qEA2h5tJs8sInL2N5wA.png" /><figcaption>0001_initial.py denotes the creation of the database table based on the model description</figcaption></figure><p>Then, we’ll want to ‘commit’ the changes described in the migration files to our database schema, by <a href="https://docs.djangoproject.com/en/4.0/ref/django-admin/#django-admin-migrate">migrating</a>, which is synchronizing the database state with the current set of models and migrations.</p><pre>python manage.py migrate</pre><p>This last command will generate a SQLite3 database, <a href="https://docs.djangoproject.com/en/4.0/ref/databases/#databases">unless you have changed the database configuration</a> in the settings.py module.</p><p>At this point, you’d be tempted to run the app, but so far, we didn’t define VehiclesList, so if you went and tried to run the app, some error might have jumped at you. But don’t worry, that result is normal at this point. At least we have our models and database ready to start storing information.</p><p>In part II, we’ll review the juice of this series of articles: class-based views and serializers. We’ll realize how these resources allow us to combine information from different models in one object.</p><p>See you again in part II!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe5dec69d95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95">Using Django REST Framework to Quickly Get a Working API</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>