<?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 Abdelrahmen Ayman on Medium]]></title>
        <description><![CDATA[Stories by Abdelrahmen Ayman on Medium]]></description>
        <link>https://medium.com/@abdelrahmenayman7?source=rss-36dc2987e85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QkW2b5jnrHuGwDSYy_1SmA.jpeg</url>
            <title>Stories by Abdelrahmen Ayman on Medium</title>
            <link>https://medium.com/@abdelrahmenayman7?source=rss-36dc2987e85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:00:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdelrahmenayman7/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[How to integrate Django ORM with FASTAPI]]></title>
            <link>https://towardsdev.com/how-to-integrate-django-orm-with-fastapi-8451b6335b42?source=rss-36dc2987e85------2</link>
            <guid isPermaLink="false">https://medium.com/p/8451b6335b42</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Abdelrahmen Ayman]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 21:41:15 GMT</pubDate>
            <atom:updated>2023-02-17T12:34:06.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Django ORM with FASTAPI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tEjHVqT7FPzICWf6" /><figcaption>Photo by <a href="https://unsplash.com/@artturijalli?utm_source=medium&amp;utm_medium=referral">Artturi Jalli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>ORM which is short for object relational manager is a way to use relational databases through OOP languages, you can create tables, add , update or delete records without having to write a single line of SQL, you can do it all through a piece of software that works as a bridge between the SQL code and the OOP code. You can think of it as a separate layer that isolates all database operations logic and expose it through easy and intuitive to use API. One of the most popular orms is the Django ORM, I personally like it for its simplicity and flexibility, if you’re coming from Django framework like me you’ll probably have the same feeling, and you’ll be interested too to know how to use it with FAST API, specially that Django 4 now supports async behaviour with ORM, I am not going to use the async feature in this article, but feel free to explore it on your own. Without further ado, let’s dig in.</p><blockquote>NB: This tutorial is the third part of a FastAPI series that I am currently writing, you might need to read the previous parts to be able to follow this one, but if you have some background with FastAPI you should be fine.</blockquote><blockquote>You can find <a href="https://towardsdev.com/introduction-6a83744897e2">the first part here</a> and <a href="https://medium.com/towardsdev/how-to-implement-authentication-in-fastapi-566cc17eb286">the second part here</a>.</blockquote><h3>Setup Project</h3><p>First, we will create our root folder:</p><p>mkdir myproject</p><p>Then we initiate our environment like this:</p><p>poetry init</p><p>As always I like to use <a href="https://python-poetry.org/"><em>poetry</em></a> as my dependency management tool, feel free to use any other tool you find better. Next we install django, since django-orm is part of the django system:</p><p>poetry add django</p><p>After django finishes installing, we initiate our project:</p><p>poetry run django-admin startproject myproject</p><p>Now if you check your project structure you will see the following:</p><p>As you can see this command creates a bunch of files for us:</p><ul><li>manage.py : This is the file that we can use to interact with any django part.</li><li>myproject : This folder is what we call an app, this one is usually used for configuration purposes</li></ul><p>Next we create another app to contain our code, we’ll call it todo:</p><p>poetry run django-admin startapp todo</p><p>Now you will find this new folder created, and the structure is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OYsyA4STIloy3GkIk--KQ.png" /></figure><p>Now let’s install fastapi:</p><p>poetry add “fastapi[all]”</p><p>Next we have to add the two apps we have to the INSTALLED_APPS setting in <em>settings.py</em> for django to know that it has to look inside these apps for models when migrating, it’s useful for other stuff too but that’s what matters to us in this tutorial, we do it like this:</p><p><em>myproject/settings.py</em></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;myproject&#39;,<br>    &#39;todo&#39;,<br>]</pre><p>Then we create the application entrypoint by adding this code to <em>myproject/asgi.py</em>:</p><pre>&quot;&quot;&quot;<br>ASGI config for myproject project.<br><br>It exposes the ASGI callable as a module-level variable named ``application``.<br><br>For more information on this file, see<br>https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/<br>&quot;&quot;&quot;<br><br>import os<br><br>from django.core.asgi import get_asgi_application<br>from fastapi import FastAPI<br><br><br>os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;myproject.settings&quot;)<br><br>application = get_asgi_application()<br><br>def get_application() -&gt; FastAPI:<br>    app = FastAPI()<br>    return app<br><br><br>app = get_application()</pre><p>Now try running the application:</p><p>poetry run uvicorn myproject.asgi:app — reload</p><p>Test that the server is working by going to<strong><em> localhost:8000/docs .</em></strong></p><h3>Implementation</h3><p>Now we start writing our logic code, define models, write views and tests.</p><p>Let’s implement the todo app that we implemented in <a href="https://medium.com/towardsdev/introduction-6a83744897e2">the first article</a> in this series, to demonstrate how to use django ORM with fastapi.</p><p>we will implement 2 endpoints:</p><ol><li>add todo item</li><li>read item</li></ol><h4>Models</h4><p>We have only one model in this simple tutorial, which is Item representing our todos:</p><p><em>todo/models.py</em></p><pre>from django.db import models<br><br><br>class Item(models.Model):<br>    created_at = models.DateTimeField(auto_now_add=True)<br><br>    title = models.CharField(max_length=200)<br>    description = models.CharField(max_length=300)</pre><p>This is a simple definition of a django model, when we run migrations, this will create a table in our database with fields corresponding to the variables that we defined inside our Item class. If you’re not familiar with django orm, you can read about it in their <a href="https://docs.djangoproject.com/en/4.1/topics/db/models/">docs</a>, it’s really easy to pick up.</p><p>Now we make migrations which creates a bunch of scripts that later when executed, create or update tables in our database, you can find the generated script at <em>todo/migrations</em>:</p><p>poetry run python manage.py makemigrations</p><p>Then we run migrations to execute the generated script in the previous step, this will create the database since this is our first time running a migration and create our only defined table mapping to the Item model:</p><p>poetry run python manage.py migrate</p><h4>Schemas</h4><p>create a new file <em>todo/schemas.py </em>where we will define our schemas. We will have two schemas, one for adding item operation and another for reading item operation.</p><p><em>todo/schemas.py</em></p><pre>from pydantic import BaseModel<br>from datetime import datetime<br><br><br>class AddItem(BaseModel):<br>    title: str<br>    description: str<br><br><br>class ReadItem(BaseModel):<br>    id: int<br>    title: str<br>    description: str<br>    created_at: datetime</pre><p>The difference between both schemas, is that the created_at field is generated automatically, so we don’t want the user to send it when creating a new item, yet we want to return it when someone requests the item.</p><h4>API</h4><p>Finally we create the API operations, we write them in the <em>todo/views.py</em> file, if you want you can rename it to <em>api.py, </em>for me I will leave it as it is.</p><p><strong><em>Add item endpoint</em></strong></p><p><em>todo/views.py</em></p><pre>from fastapi import APIRouter<br><br>from todo.models import Item<br>from todo.schemas import AddItem, ReadItem<br><br>router = APIRouter()<br><br><br>@router.post(&quot;/items&quot;, response_model=ReadItem)<br>def add_item(item: AddItem):<br>    item_obj = Item.objects.create(**item.dict())<br>    return ReadItem(**item_obj.__dict__)</pre><p>We create a router to include all of our endpoints at the top of the file. The add_item view is pretty simple, the function takes a request body as a parameter, it validates it using the pydantic model AddItem, then we create an item using the validated data stored in the item variable. Finally we return that item, but only the fields we want the user to see, we restrict the returned fields using the pydantic model ReadItem.</p><blockquote>The .__dict__ syntax, is only a variable storing a dict that contains all the variables in the model object. We are using it to pass the object as a dict, which is what’s accepted by pydantic models to validate any data.</blockquote><p><strong><em>Read item endpoint</em></strong></p><p><em>todo/views.py</em></p><pre>from fastapi import APIRouter, HTTPException<br><br>from todo.models import Item<br>from todo.schemas import AddItem, ReadItem<br><br>router = APIRouter()<br><br><br>@router.post(&quot;/items&quot;, response_model=ReadItem)<br>def add_item(item: AddItem):<br>    item_obj = Item.objects.create(**item.dict())<br>    return ReadItem(**item_obj.__dict__)<br><br><br>@router.get(&quot;/items/{item_id}&quot;, response_model=ReadItem)<br>def read_item(item_id: int):<br>    try:<br>        item = Item.objects.get(pk=item_id)<br>    except Item.DoesNotExist:<br>        raise HTTPException(status_code=404, detail=&quot;Item with such id does not exist&quot;)<br>    return ReadItem(**item.__dict__)</pre><p>This endpoint gets an item by id, it takes the item id as a path parameter. It returns an error of <strong><em>404 Not Found </em></strong>when an id that does not exist is requested from the endpoint. Otherwise, it returns the item normally using the same pydantic model we used in the previous endpoint.</p><blockquote>You can indicate a path parameter by adding the parameter name in the path between curly braces, then add it in the function signature as a parameter, this way FastAPI will understand that this is a path parameter and it will extract its value from the url into the function’s parameter. You can read more about path parameters <a href="https://fastapi.tiangolo.com/tutorial/path-params/">here</a>.</blockquote><h4>Include Router</h4><p>Up until now, FastAPI doesn’t know anything about the endpoints or the router that we defined. If you go to <em>localhost:8000/docs </em>you will find it empty. To change this we should include the router to our FastAPI app.</p><blockquote>When FastAPI app handles a new request, it examines the requested url, if the app doesn’t directly know about that url, it starts asking every router that’s included in the app, if it has that endpoint included in it, when it finds the endpoint it lets it handle the request. To read more about APIRouter checkout the docs <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/#apirouter">here</a>.</blockquote><p><em>myproject/asgi.py</em></p><pre>&quot;&quot;&quot;<br>ASGI config for myproject project.<br><br>It exposes the ASGI callable as a module-level variable named ``application``.<br><br>For more information on this file, see<br>https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/<br>&quot;&quot;&quot;<br><br>import os<br><br>from django.core.asgi import get_asgi_application<br>from fastapi import FastAPI<br><br><br>os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;myproject.settings&quot;)<br><br><br>application = get_asgi_application()<br><br>from todo.views import router<br><br><br>def get_application() -&gt; FastAPI:<br>    app = FastAPI()<br>    app.include_router(router)<br><br>    return app<br><br><br>app = get_application()</pre><p>As you can see we added the line app.include_router(router) and the router import. Before you ask, yes the import is placed where it should be, because the django asgi app has to be loaded before importing anything from any django app.</p><h4>Test</h4><p>Now if you run the app and go to <em>localhost:8000/docs </em>you will find the defined endpoints documented there, and you can try them out using the interactive documentation. And voila, we integrated django’s ORM with FastAPI.</p><p>If you want to learn more about Django’s ORM, and how to write more complex models than the one we created here, feel free to checkout it their documentation, it’s a very rich <a href="https://docs.djangoproject.com/en/4.1/topics/db/models/">documentation</a>, worth your time.</p><p>You should also checkout <a href="https://fastapi.tiangolo.com/">FastAPI documentation</a> for more info about the concepts we used in this tutorial’s code, we didn’t explain in great detail most of the code here, since this is not the focus of this tutorial.</p><p>I hope you enjoyed following this tutorial as much as I enjoyed writing it, if you have any questions or notes, please feel free to contact me on any of my social media accounts or in the comments section below and I will get back to you as soon as I can,</p><p>Cheers.</p><h3>Conclusion</h3><p>We integrated Django’s ORM with FastAPI, we learned how to use django models with FastAPI operations, and also how and where to include FastAPI app creation in Django’s typical files structure. We created two simple endpoints to add and read todo items, you can checkout the result <a href="https://github.com/abdelrahmenAyman/How-to-use-django-orm-with-fast-api">here</a>.</p><h3>External Links</h3><ol><li>First Tutorial: <a href="https://towardsdev.com/introduction-6a83744897e2">https://towardsdev.com/introduction-6a83744897e2</a></li><li>Second Tutorial: <a href="https://medium.com/towardsdev/how-to-implement-authentication-in-fastapi-566cc17eb286">https://medium.com/towardsdev/how-to-implement-authentication-in-fastapi-566cc17eb286</a></li><li>poetry: <a href="https://python-poetry.org/">https://python-poetry.org/</a></li><li>Django models: <a href="https://docs.djangoproject.com/en/4.1/topics/db/models/">https://docs.djangoproject.com/en/4.1/topics/db/models/</a></li><li>Path Parameters: <a href="https://fastapi.tiangolo.com/tutorial/path-params/">https://fastapi.tiangolo.com/tutorial/path-params/</a></li><li>FastAPI Routers: <a href="https://fastapi.tiangolo.com/tutorial/bigger-applications/#apirouter">https://fastapi.tiangolo.com/tutorial/bigger-applications/#apirouter</a></li><li>github repo: <a href="https://github.com/abdelrahmenAyman/How-to-use-django-orm-with-fast-api">https://github.com/abdelrahmenAyman/How-to-use-django-orm-with-fast-api</a></li><li>FastAPI docs: <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8451b6335b42" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-integrate-django-orm-with-fastapi-8451b6335b42">How to integrate Django ORM with FASTAPI</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement authentication in FastAPI]]></title>
            <link>https://towardsdev.com/how-to-implement-authentication-in-fastapi-566cc17eb286?source=rss-36dc2987e85------2</link>
            <guid isPermaLink="false">https://medium.com/p/566cc17eb286</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abdelrahmen Ayman]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 00:07:02 GMT</pubDate>
            <atom:updated>2023-01-11T14:21:54.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Chained Door" src="https://cdn-images-1.medium.com/max/1024/0*wZIrvJnSKaVhmpiL" /><figcaption>Photo by <a href="https://unsplash.com/@jsalvino?utm_source=medium&amp;utm_medium=referral">John Salvino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>When we create a new web application, one of the most important aspects that we should worry about is security. Security basically means protecting the user’s data from being accessed or modified by someone who shouldn’t be authorized to do so. You don’t want to have a stranger reading your Whatsapp messages for example. This is why we use different methods to protect our users data and privacy, luckily for us FastAPI has made it easy for to implement most of the well established security methods in the web development craft. In this article we are going to discover how to implement one of the most popular authentication methods which is token authentication .</p><p>This tutorial is the second part of a FastAPI series that I am currently writing, you don’t need to read the first part to be able to follow this one, but if you’d like you can check out the first part <a href="https://towardsdev.com/introduction-6a83744897e2">here</a>.</p><h3>OpenAPI</h3><p>OpenAPI is the open specification for building APIs. FastAPI is based on OpenAPI . OpenAPI has a way to define multiple security schemes, the one we’re interested in is OAuth2, which has what we call security flows. There are multiple flows to use in OAuth2 like implicit, clientCredentials, AuthorizationCode and the one we’re actually interested in, the password flow.</p><h3>The Password Flow</h3><p>To better understand how the <strong><em>password flow</em></strong> works, let’s look at the whole picture and what happens since the user types his username and password in the browser:</p><ol><li>The user opens a web browser, goes to our frontend web page, types in his username and password, then clicks login.</li><li>The browser takes the credits the user just typed, creates a POST request to our API using the /tokenendpoint.</li><li>The API will check if the username/password combination matches anything in our database.</li><li>If there was no match found, the user is not authenticated and therefore can not fetch protected data from the API.</li><li>If a match was found, the API will return a token that can be used as a key to access protected areas in our API.</li><li>The browser will store the token for later usage, and when the user wants to fetch some data from the API, the browser will attach the token to the request as a header called Bearer.</li><li>When the backend receives the request, it will check if there is a header called Bearer, it validates the token and if it’s valid then the user is authenticated and can use our API.</li><li>If the token is not valid, was forged or modified somehow, the API will tell the user that he’s not authenticated and no protected data will be returned to him.</li></ol><h3>Essential concepts</h3><p>We talked about a few concepts in the last paragraph that you should understand before we go any further, feel free to skip to the next part if you’re already familiar with these concepts.</p><h4>Token</h4><p>A token is basically an encoded string that holds a piece of information. When decoded with the right algorithm, it returns the information stored in it. A standard type of token is JWT (JSON Web Token), you can store JSON data inside a JWT token, assign it an expiry date, sign it digitally to make sure that the token’s integrity was not compromised. Tokens are great in authentication, because they are self sufficient, they can hold all the information needed for authentication and it can be verified without needing anything else except the token. You can read more about tokens <a href="https://auth0.com/learn/token-based-authentication-made-easy">here</a> and JWT tokens <a href="https://jwt.io/introduction">here</a>.</p><h4>Headers</h4><p>A header is an HTTP request field that can be used to add additional context and meta-data information about the request. It can be used to indicate the data type the browser expects to receive in the response, or as in our case add an authentication token. There are some well known headers that every browser expects, or you can implement your own custom header as well. It’s very simple to use since it uses a key-value pairs methodology. You can read more about headers <a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header#:~:text=An%20HTTP%20header%20is%20a,format%20of%20the%20returned%20body.">here</a>.</p><h4>Hashing</h4><p>Normally, we need to store users passwords in the database to use it later to check if users are really are who they claim to be, but we can not store passwords just like that in the database. Storing plain passwords in the database is very dangerous, if an attacker manages to steal our database or parts of it, he can use it freely until the user notices and change the password, who knows when will he notice if that ever happens. Another risk is that many users use the same password for multiple applications, if that password is stolen, we didn’t just allow the attacker to compromise the user’s account in our application only, but also in all his other accounts, we don’t want that!</p><p>To solve this problem we use hashing, hashing is simply an operation that given a string it transforms it into another string that looks like gibberish, the beauty of hash functions is that they are one way only, you can’t recover the password again once it’s been hashed. This means when a thief steals the database, he will end up with gibberish passwords not the actual ones, and he can’t use them. Then how can I check that this password is valid when a user is trying to login ? Hash functions are one way yes, but given the same string they will always produce the same gibberish, so we can verify the password by applying the same hash function to it, then compare the hashed result to the one we have in our database.</p><p>You can read more about hashing <a href="https://auth0.com/blog/hashing-passwords-one-way-road-to-security/">here</a>.</p><h3>Implementation</h3><h4>JWT Tokens</h4><p>To generate and verify JWT tokens we need to install python-jose, to install it type this in your terminal: poetry add “python-jose[cryptography]” <br>python-jose required a cryptographic backend as an extra, so here we’re using the recommended one cryptography.</p><p>We will create a file called jwt.py to include all our JWT logic, first thing we will do is write a function that will create access tokens to be used in authentication with our API.</p><pre>from datetime import datetime, timedelta<br>from jose import jwt<br><br><br>SECRET_KEY = &quot;b94f8e6272fcef848060d16721461f19439147462768dadfaf9e132b5e7d5dca&quot;<br>ALGORITHM = &quot;HS256&quot;<br><br><br>def create_access_token(payload: dict, expires_delta: timedelta | None = None):<br>    payload_copy = payload.copy()<br>    if expires_delta:<br>        expires = datetime.utcnow() + expires_delta<br>    else:<br>        expires = datetime.utcnow() + timedelta(minutes=15)<br>    payload_copy.update({&quot;exp&quot;: expires})<br>    token = jwt.encode(payload_copy, SECRET_KEY, algorithm=ALGORITHM)<br>    return token</pre><p>The create_access_token function takes two arguments:</p><ul><li>payload: A dictionary containing all key-value pairs to be stored in the token.</li><li>expires_delta: A timedelta object to be used as the expiration period for the token, it can be None.</li></ul><p>The function basically copies the payload dictionary to avoid changing the input, if there is a timedelta object to use as expiration period, we use it, if not we set the expiration to be 15 minutes. We then update the payload to include the expiration period as a field called exp , the reason we include it in the token’s payload is that when it’s sent later to our API as an authentication token, we can check its exp field to check if it’s still valid.</p><p>finally we use the utility provided by python-jose to encode the token, we are using a secret and a chosen encoding algorithm, then we return the token.</p><p><em>FYI: Using a secret key is what makes us sure that the token has not been changed, let’s say an attacker changed the data and encoded the token back with the wrong secret key, when we try to decode it will indicate that it’s invalid, this way we created our own digital signature for any token that we return from our API.</em></p><p><em>NB: SECRET_KEY and ALGORITHM variables are normally stored inside the environment, not stored plainly in the code, we’re not doing that here to make things simple for you.</em></p><p>Now add the decode function to retrieve back the token’s payload would be as simple as this:</p><pre>def decode_token(token: str):<br>    return jwt.decode(token, SECRET_KEY, ALGORITHM)</pre><p>The core/<strong><em>jwt.py</em></strong> file now looks like this:</p><pre>from datetime import datetime, timedelta<br>from jose import jwt<br><br><br>SECRET_KEY = &quot;b94f8e6272fcef848060d16721461f19439147462768dadfaf9e132b5e7d5dca&quot;<br>ALGORITHM = &quot;HS256&quot;<br><br><br>def create_access_token(payload: dict, expires_delta: timedelta | None = None):<br>    payload_copy = payload.copy()<br>    if expires_delta:<br>        expires = datetime.utcnow() + expires_delta<br>    else:<br>        expires = datetime.utcnow() + timedelta(minutes=15)<br>    payload_copy.update({&quot;exp&quot;: expires})<br>    token = jwt.encode(payload_copy, SECRET_KEY, algorithm=ALGORITHM)<br>    return token<br><br><br>def decode_token(token: str):<br>    return jwt.decode(token, SECRET_KEY, ALGORITHM)</pre><h4>Hashing</h4><p>As we explained earlier, we need to hash passwords before storing them into our database, and we also need to be able to verify if the hashed password stored in our database matches the password the user is trying to login with.</p><p>To hash passwords we need to install passlib. The recommended algorithm is bcrypt, to do that we use the following command:</p><p>poetry add &quot;passlib[bcrypt]&quot;</p><p><strong><em>core/authentication.py</em></strong></p><pre>from passlib.context import CryptContext<br><br><br>pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)<br><br><br>def get_password_hash(password: str) -&gt; str:<br>    return pwd_context.hash(password)<br><br><br>def verify_password(plain_password: str, hashed_password: str) -&gt; bool:<br>    return pwd_context.verify(plain_password, hashed_password)</pre><p>Firstly we create a context to use it to hash and verify passwords. Then there is get_password_hash which simply takes a password and returns its hash. The next function is verify_password which accepts as arguments a plain password and a hashed one and verifies the password using pwd_context.verify , then returns true if they match, false otherwise. Simple enough isn’t it !!</p><pre>def authenticate_user(fake_db: dict, username: str, password: str):<br>    user = get_user(fake_db, username)<br>    if not user:<br>        return False<br>    if not verify_password(password, user.hashed_password):<br>        return False<br>    return user</pre><p>Now we add the function responsible for authentication, let’s break it down to see what it does:</p><ol><li>The function accepts 3 arguments , username, password and fake_db which is a dict acting as our database where users can be retrieved by username through the get_user function.</li><li>If the database doesn’t have a username that matches the one we’re looking for, we return False.</li><li>Then we verify the password with the one associated to the user we found, if it doesn’t match we return False.</li><li>If the credits are valid, then we return the user object.</li></ol><p>Finally the<strong><em> core/authentication.py</em></strong> file looks like this:</p><pre>from passlib.context import CryptContext<br>from .utilities import get_user<br><br><br>pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)<br><br><br>def get_password_hash(password: str) -&gt; str:<br>    return pwd_context.hash(password)<br><br><br>def verify_password(plain_password: str, hashed_password: str) -&gt; bool:<br>    return pwd_context.verify(plain_password, hashed_password)<br><br><br>def authenticate_user(fake_db: dict, username: str, password: str):<br>    user = get_user(fake_db, username)<br>    if not user:<br>        return False<br>    if not verify_password(password, user.hashed_password):<br>        return False<br>    return user</pre><p>You will notice we’re importing get_user from .utilities , this function is simply retrieving the user item from the fake db and returing it as an object using <strong><em>pyadntic.</em></strong></p><p><strong><em>core/utilities.py</em></strong></p><pre>class UserInDB(BaseModel):<br>    username: str<br>    email: str | None = None<br>    full_name: str | None = None<br>    disabled: bool | None = None<br>    hashed_password: str<br><br>def get_user(db, username: str):<br>    if username in db:<br>        user_dict = db[username]<br>        return UserInDB(**user_dict)</pre><h4>checkpoint</h4><p>Now since we implemented quite a few things, let’s try things out at this point. let’s create our fake db then try to call authenticate with different username values.</p><pre>fake_users_db = {<br>    &quot;johndoe&quot;: {<br>        &quot;username&quot;: &quot;johndoe&quot;,<br>        &quot;full_name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW&quot;,<br>        &quot;disabled&quot;: False,<br>    },<br>    &quot;alice&quot;: {<br>        &quot;username&quot;: &quot;alice&quot;,<br>        &quot;full_name&quot;: &quot;Alice Wonderson&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;fakehashedsecret2&quot;,<br>        &quot;disabled&quot;: True,<br>    },<br>}</pre><p>open a terminal and run a python shell, import the authenticate_user function, create the fake_users_db and call authenticate_user with different values.</p><h4>Login Endpoint</h4><p>let’s describe what our login endpoint does so that it would be easier to understand what it does when we see its code:</p><ol><li>The endpoint path will be /token and normally it will expect POST requests only.</li><li>It expects the user to send a username and password.</li><li>The endpoint will authenticate the user using the credits it received and raise a 400 if something goes wrong during authentication.</li><li>If the user is authenticated correctly we will create an access token for him with a suitable expiration time.</li><li>Finally we return the token to the user as a proof that this particular user is authenticated, he can use this token anywhere in our API to access protected data later.</li></ol><p><strong><em>core/main.py</em></strong></p><pre>from datetime import timedelta<br><br>from fastapi import Depends, FastAPI, HTTPException<br>from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm<br>from pydantic import BaseModel<br><br><br>fake_users_db = {<br>    &quot;johndoe&quot;: {<br>        &quot;username&quot;: &quot;johndoe&quot;,<br>        &quot;full_name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW&quot;,<br>        &quot;disabled&quot;: False,<br>    },<br>    &quot;alice&quot;: {<br>        &quot;username&quot;: &quot;alice&quot;,<br>        &quot;full_name&quot;: &quot;Alice Wonderson&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;fakehashedsecret2&quot;,<br>        &quot;disabled&quot;: True,<br>    },<br>}<br><br><br>app = FastAPI()<br><br>oauth2_scheme = OAuth2PasswordBearer(tokenUrl=&quot;token&quot;)<br><br>class Token(BaseModel):<br>    access_token: str<br>    token_type: str<br><br><br>@app.post(&quot;/token&quot;, response_model=Token)<br>async def login(form_data: OAuth2PasswordRequestForm = Depends()):<br>    user = authenticate_user(fake_users_db, form_data.username, form_data.password)<br>    if not user:<br>        raise HTTPException(<br>            status_code=401,<br>            detail=&quot;Incorrect username or password&quot;,<br>            headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>        )<br>    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)<br>    access_token = create_access_token(<br>        payload={&quot;sub&quot;: user.username}, expires_delta=access_token_expires<br>    )<br>    return {&quot;access_token&quot;: access_token, &quot;token_type&quot;: &quot;bearer&quot;}</pre><p>Let’s break down what’s happening here in this file:</p><ol><li>We are using OAuth2PasswordBearer which is a class offered by FastAPI to just tell it that the endpoint with the path /token is the one used in our security scheme, and we are using the security scheme <em>Token Bearer</em>.</li><li>We define a Token pydantic model to use in describing our endpoint respond model.</li><li>We then define the endpoint and use FastAPI dependency injection system and another class offered by FastAPI to make the endpoint accept username and password:<br>a. A dependency is simply a function that must run first before the caller function starts executing, the dependency function returned value can be used by the caller function as an argument.<br>b. OAuth2PasswordRequestForm is a class offered by FastAPI to collect the user’s credentials as a form data, we use it as a dependency so we can be sure that when executing our function, the username and password are present in the variable form_data . <strong><em>You need to install </em></strong><strong><em>python-multipart for form data to work.</em></strong></li><li>Then we authenticate the user, if authentication fails we return a 400 error response.</li><li>If Authentication succeeds we create an access token with the suitable expiration time.</li><li>We store the username inside the payload in a field called sub because that’s what JWT specification tells us to do, to store the user’s identification inside a sub field, but you’re free to use any variable name you want.</li><li>Finally we return the access token.</li></ol><p>Now if you go to <a href="http://localhost:8000/docs">http://localhost:8000/docs</a> you can try out the new endpoint. You should now see an <strong><em>authorize </em></strong>button that you can use to authenticate yourself.</p><h4>Get Current User</h4><pre>class TokenData(BaseModel):<br>    username: str | None = None<br><br><br>async def get_current_user(token: str = Depends(oauth2_scheme)):<br>    credentials_exception = HTTPException(<br>        status_code=400,<br>        detail=&quot;Could not validate credentials&quot;,<br>        headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>    )<br>    try:<br>        payload = decode_token(token)<br>        username: str = payload.get(&quot;sub&quot;)<br>        if username is None:<br>            raise credentials_exception<br>        token_data = TokenData(username=username)<br>    except JWTError:<br>        raise credentials_exception<br>    user = get_user(fake_users_db, username=token_data.username)<br>    if user is None:<br>        raise credentials_exception<br>    return user</pre><p>This function decodes the token to check for its integrity, and returns the user from database based on the username encoded inside the token. The function depends on oauth2_scheme the security scheme we defined earlier, since this is an instance of an OAuth2 class, FastAPI will know that this is a security scheme, and this endpoint will require authentication through that security scheme first.</p><p>So nothing special happened here, now you can use this function as a dependency to any endpoint we have, to provide authentication for that endpoint, and you will have the user instance inside the endpoint’s function, so you can make any custom authorization you want at the function level.</p><pre>class User(BaseModel):<br>    username: str<br>    email: str | None = None<br>    full_name: str | None = None<br>    disabled: bool | None = None<br><br><br>@app.get(&quot;/users/me&quot;)<br>async def read_users_me(current_user: User = Depends(get_current_user)):<br>    return current_user</pre><p>Since we now have many pydantic models, let’s move them all to one file.</p><p><strong><em>schemas.py</em></strong></p><pre>from pydantic import BaseModel<br><br><br>class User(BaseModel):<br>    username: str<br>    email: str | None = None<br>    full_name: str | None = None<br>    disabled: bool | None = None<br><br><br>class UserInDB(User):<br>    hashed_password: str<br><br><br>class Token(BaseModel):<br>    access_token: str<br>    token_type: str<br><br><br>class TokenData(BaseModel):<br>    username: str | None = None</pre><p>Finally the <strong><em>main.py </em></strong>file should look like this:</p><pre>from datetime import timedelta<br><br>from fastapi import Depends, FastAPI, HTTPException<br>from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm<br>from jose import JWTError<br><br>from core.authentication import authenticate_user<br>from core.jwt import create_access_token, decode_token<br>from core.schemas import Token, TokenData, User<br>from core.utilities import get_user<br><br>ACCESS_TOKEN_EXPIRE_MINUTES = 30<br><br>fake_users_db = {<br>    &quot;johndoe&quot;: {<br>        &quot;username&quot;: &quot;johndoe&quot;,<br>        &quot;full_name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;johndoe@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW&quot;,<br>        &quot;disabled&quot;: False,<br>    },<br>    &quot;alice&quot;: {<br>        &quot;username&quot;: &quot;alice&quot;,<br>        &quot;full_name&quot;: &quot;Alice Wonderson&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;,<br>        &quot;hashed_password&quot;: &quot;fakehashedsecret2&quot;,<br>        &quot;disabled&quot;: True,<br>    },<br>}<br><br><br>app = FastAPI()<br><br>oauth2_scheme = OAuth2PasswordBearer(tokenUrl=&quot;token&quot;)<br><br><br>async def get_current_user(token: str = Depends(oauth2_scheme)):<br>    credentials_exception = HTTPException(<br>        status_code=400,<br>        detail=&quot;Could not validate credentials&quot;,<br>        headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>    )<br>    try:<br>        payload = decode_token(token)<br>        username: str = payload.get(&quot;sub&quot;)<br>        if username is None:<br>            raise credentials_exception<br>        token_data = TokenData(username=username)<br>    except JWTError:<br>        raise credentials_exception<br>    user = get_user(fake_users_db, username=token_data.username)<br>    if user is None:<br>        raise credentials_exception<br>    return user<br><br><br>@app.get(&quot;/users/me&quot;)<br>async def read_users_me(current_user: User = Depends(get_current_user)):<br>    return current_user<br><br><br>@app.post(&quot;/token&quot;, response_model=Token)<br>async def login(form_data: OAuth2PasswordRequestForm = Depends()):<br>    user = authenticate_user(fake_users_db, form_data.username, form_data.password)<br>    if not user:<br>        raise HTTPException(<br>            status_code=401,<br>            detail=&quot;Incorrect username or password&quot;,<br>            headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>        )<br>    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)<br>    access_token = create_access_token(<br>        payload={&quot;sub&quot;: user.username}, expires_delta=access_token_expires<br>    )<br>    return {&quot;access_token&quot;: access_token, &quot;token_type&quot;: &quot;bearer&quot;}</pre><p>And now we’re done! You can check out the final result with a some bonus features at the tutorial’s <a href="https://github.com/abdelrahmenAyman/How-to-implement-authentication-in-FastAPI">repository</a>.</p><h3>Conclusion</h3><p>We have learned how to add security to our endpoints using the OAuth2 Bearer security scheme. We used the security tools that FastAPI offers us to implement the password flow without almost writing any code on our own. We learnt how to create access tokens, hash passwords and verify them and finally how to integrate all of that into a login endpoint and a get the current user endpoint. You can checkout the result at this <a href="https://github.com/abdelrahmenAyman/How-to-implement-authentication-in-FastAPI">repository</a>.</p><p>You can always read more on your own if you feel like in <a href="https://fastapi.tiangolo.com/">FastAPI documentation</a>, it’s very well written and it’s a great place to start learning FastAPI.</p><p>I hope you enjoyed following this tutorial as much as I enjoyed writing it, if you have any questions or notes, please feel free to contact me on any of my social media accounts or in the comments section below and I will get back to you as soon as I can,</p><p>Cheers.</p><h3>External Links</h3><ol><li><a href="https://auth0.com/learn/token-based-authentication-made-easy">https://auth0.com/learn/token-based-authentication-made-easy</a></li><li><a href="https://jwt.io/introduction">https://jwt.io/introduction</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header#:~:text=An%20HTTP%20header%20is%20a,format%20of%20the%20returned%20body">https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header#:~:text=An%20HTTP%20header%20is%20a,format%20of%20the%20returned%20body</a>.</li><li><a href="https://auth0.com/blog/hashing-passwords-one-way-road-to-security/">https://auth0.com/blog/hashing-passwords-one-way-road-to-security/</a></li><li><a href="https://fastapi.tiangolo.com/tutorial/security/first-steps/">https://fastapi.tiangolo.com/tutorial/security/first-steps/</a></li><li><a href="https://github.com/abdelrahmenAyman/How-to-implement-authentication-in-FastAPI">https://github.com/abdelrahmenAyman/How-to-implement-authentication-in-FastAPI</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566cc17eb286" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-implement-authentication-in-fastapi-566cc17eb286">How to implement authentication in FastAPI</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a simple FastAPI app]]></title>
            <link>https://towardsdev.com/introduction-6a83744897e2?source=rss-36dc2987e85------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a83744897e2</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Abdelrahmen Ayman]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 20:19:11 GMT</pubDate>
            <atom:updated>2022-12-24T00:48:19.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zMEJTdqwN9ZdLmDm" /><figcaption>Photo by <a href="https://unsplash.com/@laurenmancke?utm_source=medium&amp;utm_medium=referral">Lauren Mancke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>FastAPI is gaining huge popularity in the devs community right now due to how fast it performs compared to all other python frameworks. Not only that but it also provides a great editor support and way faster development time compared to the older web frameworks. FastAPI gives a huge flexibility while choosing what tools you want to use much like what Flask does, which might be a little bit overwhelming for new comers to web development, but I think it’s worth it taking in mind how well it performs in scalable applications and all the benefits we just mentioned. So without further ado, let’s find out how to start using FastAPI.</p><h3>Prerequisites</h3><ol><li>Basic web development knowledge.</li><li>Python basics.</li><li>Python installation on your machine.</li></ol><h3>Installation</h3><p>The first thing we need to do to get started is to install FastAPI and its dependencies, you can do this with one simple command:</p><pre>poetry add &quot;fastapi[all]&quot;</pre><p>This command installs <em>fastapi </em>along with its dependencies like uvicorn which is an ASGI webserver<em>. Y</em>ou’re probably wondering what is <em>poetry</em>, it’s simply a dependency management tool similar to <em>pipenv</em>, but I like <em>poetry</em> better because it’s more elegant and it can be used in publishing a package too. You can read more about <em>poetry</em> through their <a href="https://python-poetry.org/">official web page</a> and same goes for <em>pipenv</em> you can visit their official web page <a href="https://pipenv.pypa.io/en/latest/">here</a>. Here’s a <a href="https://remaster.com/blog/pip-pipenv-poetry-comparison">comparison</a> between all the package management tools used in python recently.</p><h3>First Endpoint Implementation</h3><p>In your project’s root create a <em>main.py</em> which will be the entry point to your application and we can create our first endpoint as simple as adding this snippet of code to your main.py:</p><pre>from fastapi import FastAPI<br><br><br>app = FastAPI()<br><br><br>@app.get(&quot;/first-endpoint&quot;)<br>async def root():<br>    return {&quot;message&quot;: &quot;Hello World&quot;}</pre><p>This is a very simple `get endpoint` <em>a</em>s you can see returns a JSON object that contains a “message” key holding the string “Hello World”. Let’s break it down:</p><ol><li>first we define app = FastAPI() which will be the entry point to our whole application.</li><li>We define a function that will be called when someone visits our endpoint, in our case we implemented a function that only returns a simple JSON object containing a welcome message. Don’t worry about the async keyword for now, it means that this function is asynchronous but it doesn’t matter in this case.</li><li>The decorator used on the function is defining a path operation, it takes as an argument the endpoint’s path which in this case is /first-endpoint , once someone visits this path, <em>the </em><em>root function</em> will be executed. If you’re not familiar with what a decorator is, it’s simply another function that we use to wrap the function we’re writing to add some extra behaviour to it. You can read more about decorators in this <a href="https://realpython.com/primer-on-python-decorators/">great extensive article</a>.</li><li>In this endpoint we used app.get which marks the endpoint as a get endpoint. We can use other functions as decorators like app.post or app.put for example, each function corresponds to an HTTP Method.</li><li>Now to run the application open a command line window and write the following command: <br>uvicorn main:app --reload <br>This tells uvicorn that our entry point is a variable called app and it can be found in a file called main, the --reload is a flag telling it to reload the server on any change.</li><li>Now if you go to <a href="http://127.0.0.1:8000/first-endpoint">localhost:8000/first-endpoint</a> you will find the hello world greeting message there, and if you go to <a href="http://127.0.0.1:8000/docs">localhost:8000/docs</a> you will find Interactive documentation auto generated by Swagger UI, you can also find an alternative documentation if you go to <a href="http://127.0.0.1:8000/redoc">localhost:8000/redoc</a> . You don’t need to do anything for this to happen, all what you need to do is define your endpoint and FastApi already takes care of everything else for you.</li></ol><h3>What we are going to build</h3><p>Now that we saw how we can implement a very basic endpoint with FastAPI using just a few lines of code, let’s start exploring the things that FastAPI allows us to do with the same simplicity and elegance, to do that we are going to build a simple To-do app using FastAPI. At the end of the article we should have a small app capable of adding a new to-do, fetch all your to-dos or a single to-do only, and delete a to-do.</p><p>If you want to check out the final result you can find it here in this <a href="https://github.com/abdelrahmenAyman/How-to-create-a-simple-FastAPI-app">github repository</a>.</p><h3>Initial setup</h3><p>To start off our application, let’s start with creating the app entry point like we did before, create a fake database where we are going to store our to-do items and then implement the simplest endpoint in our app, a GET endpoint responsible for listing all the items found in our fake database.</p><ol><li>Create a list to act as a fake database and populate it with dictionaries where each one represents a to-do item:</li></ol><pre>from fastapi import FastAPI<br><br><br>app = FastAPI()<br>ITEMS = [<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;title&quot;: &quot;Learn FastAPI&quot;,<br>        &quot;description&quot;: &quot;Learn how to use all the cool features found in FastAPI&quot;,<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;title&quot;: &quot;Buy food&quot;,<br>        &quot;description&quot;: &quot;Buy some food on your way home because you have no time to cook today, you have to learn FastAPI&quot;,<br>    },<br>]</pre><p>2. Define the path operation or the endpoint that’s going to serve the list of to-do items in our database:</p><pre>@app.get(&quot;/items/&quot;)<br>async def get_items():<br>    return ITEMS</pre><p>We define the path operation using the app.get decorator and we tell FastAPI the path to our endpoint by passing the string “/items/” to the decorator, when this path is requested please execute the decorated function below, which in this case is get_items. In the function’s body we simply return the items list. Now if you go to <a href="http://127.0.0.1:8000/docs">localhost:8000/docs</a> and try the endpoint out, you will find it returning the list of items as we expected.</p><p>If you don’t know what decorators work you can read about them more <a href="https://realpython.com/primer-on-python-decorators/"><strong>here</strong></a>, they are basically some python magic that changes the way a function behaves without modifying its structure.</p><h3>Path Parameters</h3><p>Let’s say for some reason we want our API to serve a single to-do item instead of all the items that we have, for this purpose we have to implement a different endpoint that uses an item’s id field to retrieve it, but how exactly are we going to tell FastAPI please fetch me the item with this id ? This is where “path operations” come into play, we are going to pass the id inside the endpoint’s path, and we can do it like this:</p><pre>@app.get(&quot;/items/{item_id}&quot;)<br>async def get_item(item_id: int):<br>    return ITEMS[item_id - 1]</pre><p>This endpoint is fairly similar to the endpoint fetching all the items in the database, except for one small change. You can see in the path passed to the app.get decorator that we added {item_id} inside the string, which is a similar syntax to what python f-strings use. We then add an argument item_id of type int to the function executing our endpoint’s logic. This way when we go to for example /items/1 FastAPI knows that it has to call get_item and pass it item_id=1 . In the function’s body we use the item_id as an index for the ITEMS list just for the sake of simplicity.</p><p>Now if you go to <a href="http://127.0.0.1:8000/docs">localhost:8000/docs</a> you will find the endpoint is well documented, what type of parameters it expects. If you try to request the endpoint with a string item id like this /items/foo you will receive a validation error that it must be of type integer, this happens because we added type annotation to the item_id argument in the endpoint.</p><p>Try it out with one of the ids that exists in our database, we didn’t handle the case of ids that don’t exist in the database just for the sake of simplicity, in another article we are going to connect an actual database, and we will do it there, it’s going to be more relevant to the topic of the article.</p><p>So you also get automatic validation with just using type hints which is by the way something you should do, it makes your life a lot easier on the long run, Believe me !</p><h3>Pydantic Models</h3><p>In order to proceed with the rest of the tutorial, we will have to get introduced to Pydantic. I think that the definition provided by the people who made <a href="https://pydantic-docs.helpmanual.io/">Pydantic</a> is the best way to introduce it to you:</p><blockquote>Data validation and settings management using Python type annotations. <em>pydantic</em> enforces type hints at runtime, and provides user friendly errors when data is invalid.</blockquote><p>Now that we know what Pydantic is, we can proceed to the following step. The next endpoint we are planning to implement is a POST endpoint that adds a new to-do item, and to do that we will have to accept user input, and of course we need to validate this data and that’s what <em>pydantic </em>is going to help us with.</p><p>To add a new item you need to provide a title and a description, we can force this structure by defining a schema or what pydantic calls a model:</p><pre>from pydantic import BaseModel<br><br><br>class BaseTodoItem(BaseModel):<br>    title: str<br>    description: str</pre><p>By inherting from pydantic’s BaseModel we now have our custom model. Next we start defining fields that we want the user to send to our endpoint and define their type using python type hints. From this simple implementation, pydantic is going to detect that title and description are required fields and their respective types are string and string.</p><p>By using BaseTodoItem with any data we can start validating this data, for instance try running BaseTodoItem(title=&quot;some title&quot;) you will get a validation error stating that description field is required but found missing.</p><h3>Request Body</h3><p>Now that we have the data validation part implemented, let’s actually implement the add item endpoint and use the data validation model in that endpoint. As we did with the GET endpoints we are going to use app.post decorator to indicate a POST endpoint, it will also have the path /items/ :</p><pre>ITEMS = []<br><br>@app.post(&quot;/items/&quot;)<br>async def add_item(item: BaseTodoItem):<br>    ITEMS.append(item)<br>    return item</pre><p>Now what we did here is just passing a new argument item and we gave it the type of the BaseTodoItem that we defined before, using this FastAPI knows that this is meant as a request body, and it doesn’t confuse it with path parameters, because there is no {} found in the path we passed to app.post which is the syntax used to indicate a path parameter in FastAPI.</p><p>The item variable holds the request data in the form of python object of type BaseTodoItem which we add to the empty ITEMS list and we return it as a response.</p><p>We have a small problem, now our items do not have an id, we need to auto generate our id fields, for the sake of simplicity we’re going to use the item’s index in the list as its own id too :</p><pre>@app.post(&quot;/items/&quot;)<br>async def add_item(item: BaseTodoItem):<br>    item_dict = item.dict()<br>    item_dict.update({&quot;id&quot;: len(ITEMS)})<br>    ITEMS.append(item)<br>    return item</pre><p>To alter the item and add a new field we had to get its dict representation and add the id field to it. But now we are adding a dictionary to the ITEMS list and we are returning a dictionary too, this is bad because we lose the autocomplete privileges that pydantic helps us with. to fix this we are going to create another Pydantic model that accepts an id too, which is going to inherit from BaseTodoItem and we are going to convert the dictionary back to a python object using the new model:</p><pre>class TodoItem(BaseTodoItem):<br>    id: int<br><br><br>@app.post(&quot;/items/&quot;)<br>async def add_item(item: BaseTodoItem):<br>    item_dict = item.dict()<br>    item_dict.update({&quot;id&quot;: len(ITEMS)})<br>    modified_item = TodoItem(**item_dict)<br><br>    ITEMS.append(modified_item)<br>    return modified_item</pre><p>With this we get data validation for request body before assigning it to the item variable and we also get auto complete features for the item object thanks to pydantic.</p><h3>Response Model</h3><p>Now our application is working fine but we have a final touch to add. The documentation now has no idea what our response is supposed to look like, to solve this problem we can use another feature that FastAPI provides with the help of pydantic which is <strong><em>response models.</em></strong></p><p>Add an argument to the endpoint decorator called response_model and assign it the TodoItem pydantic model we defined earlier, which is also the type of the object we’re returning from our endpoint, FastAPI is going to use this pydantic model in auto generating the docs for you. and the final code should look like this:</p><pre>from fastapi import FastAPI<br>from pydantic import BaseModel<br><br><br>app = FastAPI()<br><br>ITEMS = []<br><br><br>class BaseTodoItem(BaseModel):<br>    title: str<br>    description: str<br><br><br>class TodoItem(BaseTodoItem):<br>    id: int<br><br><br>@app.get(&quot;/items/{item_id}&quot;, response_model=TodoItem)<br>async def get_item(item_id: int):<br>    return ITEMS[item_id]<br><br><br>@app.get(&quot;/items/&quot;)<br>async def get_items():<br>    return ITEMS<br><br><br>@app.post(&quot;/items/&quot;, response_model=TodoItem)<br>async def add_item(item: BaseTodoItem):<br>    item_dict = item.dict()<br>    item_dict.update({&quot;id&quot;: len(ITEMS)})<br>    modified_item = TodoItem(**item_dict)<br><br>    ITEMS.append(modified_item)<br>    return modified_item</pre><p>The add_item endpoint request body has BaseTodoItem as a type because we don’t want the user to send us the id and this model doesn’t require the user to provide one, while when returning the item we want to show the user the item’s id so that he can use it in fetching the item later.</p><h3>What’s Next ?</h3><p>I am planning on making this like a small series about FastAPI, the next article should include some other FastAPI features like connecting our application to a real database and using an ORM like <em>sqlalchemy </em>and migrate that database using <em>alembic.</em></p><h3>Conclusion</h3><p>We saw how we can very quickly with a single python file implement a simple to-do web app application using FastAPI framework. We explored how we can define path operations and how to use the auto generated documentation for the endpoints provided by FastAPI. We also explored some of the basic web concepts and how FastAPI implements them like adding path parameters and handling request body how we can help the documentation with what the response structure should look like.</p><p>You can always read more on your own if you feel like in <a href="https://fastapi.tiangolo.com/">FastAPI documentation</a>, it’s very well written and it’s a great place to start learning FastAPI.</p><p>I hope you enjoyed this article, if you have any questions or anything that you’d like to share with me, please feel free to leave a comment in the comments section or reach out to me using any of my social media accounts,</p><p>Cheers</p><h3>References:</h3><ol><li>Poetry Home: <a href="https://python-poetry.org/">https://python-poetry.org/</a></li><li>Pipenv Home: <a href="https://pipenv.pypa.io/">https://pipenv.pypa.io/</a></li><li>Package managers comparison: <a href="https://remaster.com/blog/pip-pipenv-poetry-comparison">https://remaster.com/blog/pip-pipenv-poetry-comparison</a></li><li>Decorators Article: <a href="https://realpython.com/primer-on-python-decorators/">https://realpython.com/primer-on-python-decorators/</a></li><li>Project Repo: <a href="https://github.com/abdelrahmenAyman/How-to-create-a-simple-FastAPI-app">https://github.com/abdelrahmenAyman/How-to-create-a-simple-FastAPI-app</a></li><li>Pydantic docs: <a href="https://pydantic-docs.helpmanual.io/">https://pydantic-docs.helpmanual.io/</a></li><li>FastAPI docs: <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a83744897e2" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/introduction-6a83744897e2">How to create a simple FastAPI app</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nested Pagination]]></title>
            <link>https://medium.com/dreidev/nested-pagination-md-6414a85b5501?source=rss-36dc2987e85------2</link>
            <guid isPermaLink="false">https://medium.com/p/6414a85b5501</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Abdelrahmen Ayman]]></dc:creator>
            <pubDate>Sun, 22 Apr 2018 09:13:32 GMT</pubDate>
            <atom:updated>2020-10-25T00:19:09.012Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately, I faced a problem while working on a RESTful API using Django and DRF, my mentor was thinking that it was solvable in one line of code, but then we googled the issue only to find that it had been addressed in several questions on Stackoverflow with <em>no accepted answer</em>, and <strong>BOOM</strong> that is where the adventure started.</p><h3>What was the problem?</h3><p>Actually the problem at first glance seems easy, <em>Paginating a set of objects inside another object</em>. Suppose we have an Author, and a Book with a <em>foreign key</em> to the Author, simple and straight forward. Now, we want to send a response containing the list of authors we are holding in our beloved database, one of the instances is representing a legendary author that has wrote a thousand books, well of course we don’t want the response to display thousand books all at once and leave no space for any other content to be displayed.</p><h3>Available solutions</h3><p>At this point we want to do something that is solvable in many ways, the most intutive solutions were:</p><ul><li>Create a separate endpoint for books and apply pagination to this endpoint.</li><li>Find a way to paginate books inside the author instance. The first solution is easy, and won’t actually take five minutes to implement, but this is not our goal here, instead, we want to make sure that our code is as clean as possible. Additionally, we wanted the books to be displayed within the author’s view not a separate one. <em>Finally, we have a very challenging mind so we decided that we will go for the second option, yes we love mystery.</em></li></ul><h3>Our Solution to the problem</h3><p>After a decent amount of time I finally found the solution to my problem and I texted my mentor after he was home to celebrate with him <strong>wohooo</strong> we have done it, I know you don’t care about those details but I am a talkative person so apologies, let’s head to the solution: <em>Firstly</em> we should think, where is the only place that we will be having control on the list of books related to that Author? You’re right, AuthorSerializer Here is our AuthorSerializer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b6ae2bdc3be0d530caa136d1b6faaa/href">https://medium.com/media/e6b6ae2bdc3be0d530caa136d1b6faaa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf2bb2f1cc6c1c855ecdce6cea0f773/href">https://medium.com/media/daf2bb2f1cc6c1c855ecdce6cea0f773/href</a></iframe><p><strong>Pretty simple!</strong> Cool, then we should write the function that can access the author and its books inside AuthorSerializer, just a normal function that has nothing different:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0745656dd4a07035637b6c32c9f5b076/href">https://medium.com/media/0745656dd4a07035637b6c32c9f5b076/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c08340707d762d81c6e4140f31661aa2/href">https://medium.com/media/c08340707d762d81c6e4140f31661aa2/href</a></iframe><p>Hmmmmm, let’s take this piece of code bit by bit, first the function is expecting <em>2 arguments</em> self and obj. <em>Firstly,</em> we decided that we want the number of books shown per page is 10:</p><pre>page_size = 10</pre><p>Then we used the <strong>Paginator</strong> found in <strong>django.core.paginator</strong> to paginate our desired iterable object, which is books list in our case. So we extract the books from obj and pass it to the <strong>Paginator constructor</strong> along with the page size:</p><pre>paginator = Paginator(obj.books.all(), page_size)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2f9110b84c6caaa5c70fa76ae77212e/href">https://medium.com/media/d2f9110b84c6caaa5c70fa76ae77212e/href</a></iframe><p>Now we have in paginator many pages, each page includes 10 instances of Book, that we can access by number like this:</p><pre>books = paginator.page(1)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76281c308492104acb921e7b54bb05de/href">https://medium.com/media/76281c308492104acb921e7b54bb05de/href</a></iframe><p>After that we serialize the books to make sure they match our BookSerializer restrictions:</p><pre>serializer = BookSerializer(books, many=True)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2b397c4279c89349409c0691e62475/href">https://medium.com/media/5d2b397c4279c89349409c0691e62475/href</a></iframe><p>And at the end we just return the <strong>serialized books</strong> to be used by AuthorSerializer. Seems cool but we have missed something, <em>we should actually tell our </em><em>AuthorSerializer that this function is the one used to serialize books for you</em>, so we have to add one more line to our AuthorSerializer, and we will end up having this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ab8a698fff0feaab224e2ef4f409a7/href">https://medium.com/media/b6ab8a698fff0feaab224e2ef4f409a7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd22fb8451377233492c1d78d049d110/href">https://medium.com/media/fd22fb8451377233492c1d78d049d110/href</a></iframe><p><strong>And we are done, now you can paginate objects inside another object !</strong> Now let’s have a look on some tweaks that we can add to make our code more let’s say dynamic, for now our page_size is fixed to 10 and no way to change but hard coding, so let’s change this a bit, <em>one way that I’ve found suitable to get the page size dynamically is to receive it in the request query params</em>, by doing this we can return a different response in terms of books pagination for each request:</p><pre>page_size = self.context[‘request’].query_params.get(‘size’) or 10</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea06115b433315c3a8de0b3fb0f9a281/href">https://medium.com/media/ea06115b433315c3a8de0b3fb0f9a281/href</a></iframe><p>Also or 10 is used to provide a default value in case size was not passed. We can do the same for requesting which page to access, instead of doing this:</p><pre>books = paginator.page(1)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc4d19c7d8a08934d9ed860323d6ab0e/href">https://medium.com/media/cc4d19c7d8a08934d9ed860323d6ab0e/href</a></iframe><p>we can do this:</p><pre>page_number = self.context[&#39;request&#39;].query_params.get(&#39;page&#39;) or 1<br>books = paginator.page(page_number)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571404dfee8facd2c8d635b651416948/href">https://medium.com/media/571404dfee8facd2c8d635b651416948/href</a></iframe><p>Now the Serializer will be like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72c3614ca73d0403e75baa61781f7fab/href">https://medium.com/media/72c3614ca73d0403e75baa61781f7fab/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf4d1fe62a7150e56fabc54994e6bd2/href">https://medium.com/media/ebf4d1fe62a7150e56fabc54994e6bd2/href</a></iframe><h3>Conclusion</h3><p>Finally, this how we solved the problem we faced, if you’ve faced the same problem and if you’ve found a better solution please let us know and we can update our blog.</p><p>Also if you want another similar example you can checkout my answer to this question <a href="https://stackoverflow.com/questions/40806879/django-rest-framework-paginate-nested-object/49677960#49677960">https://stackoverflow.com/questions/40806879/django-rest-framework-paginate-nested-object/49677960#49677960</a> and maybe hit an up vote if you like it :D .</p><p>Please if you have any questions regarding this topic leave it in the comments below and I’ll be more than happy to answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6414a85b5501" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dreidev/nested-pagination-md-6414a85b5501">Nested Pagination</a> was originally published in <a href="https://medium.com/dreidev">DREIDEV</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>