Sick Gaming
Fedora - Use FastAPI to build web services in Python - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Computers (https://www.sickgaming.net/forum-86.html)
+--- Forum: Linux, FreeBSD, and Unix types (https://www.sickgaming.net/forum-88.html)
+--- Thread: Fedora - Use FastAPI to build web services in Python (/thread-95348.html)



Fedora - Use FastAPI to build web services in Python - xSicKxBot - 06-02-2020

Use FastAPI to build web services in Python

<div><p><em><a href="https://fastapi.tiangolo.com/">FastAPI</a></em> is a modern Python web framework that leverage the latest Python improvement in asyncio. In this article you will see how to set up a container based development environment and implement a small web service with FastAPI.</p>
<p> <span id="more-31024"></span> </p>
<h2>Getting Started</h2>
<p>The development environment can be set up using the Fedora container image. The following Dockerfile prepares the container image with FastAPI, <a href="https://www.uvicorn.org/">Uvicorn</a> and <a href="https://github.com/Tinche/aiofiles">aiofiles</a>.</p>
<pre class="wp-block-preformatted">FROM fedora:32
RUN dnf install -y python-pip \ &amp;&amp; dnf clean all \ &amp;&amp; pip install fastapi uvicorn aiofiles
WORKDIR /srv
CMD ["uvicorn", "main:app", "--reload"]</pre>
<p>After saving this Dockerfile in your working directory, build the container image using podman.</p>
<pre class="wp-block-preformatted">$ podman build -t fastapi .
$ podman images
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB</pre>
<p>Now let’s create a basic FastAPI program and run it using that container image.</p>
<pre class="wp-block-preformatted">from fastapi import FastAPI app = FastAPI() @app.get("/")
async def root(): return {"message": "Hello Fedora Magazine!"}</pre>
<p>Save that source code in a <em>main.py</em> file and then run the following command to execute it:</p>
<pre class="wp-block-preformatted">$ podman run --rm -v $PWD:/srv:z -p 8000:8000 --name fastapi -d fastapi
$ curl http://127.0.0.1:8000
{"message":"Hello Fedora Magazine!"</pre>
<p>You now have a running web service using FastAPI. Any changes to <em>main.py</em> will be automatically reloaded. For example, try changing the “Hello Fedora Magazine!” message.</p>
<p>To stop the application, run the following command. </p>
<pre class="wp-block-preformatted">$ podman stop fastapi</pre>
<h2>Building a small web service</h2>
<p>To really see the benefits of FastAPI and the performance improvement it brings (<a href="https://www.techempower.com/benchmarks/#section=test&amp;runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&amp;hw=ph&amp;test=composite&amp;l=z8kflr-v&amp;a=2&amp;f=jz8cg-0-3s-0-3k-6bo-0-0-18y74-8s5c-0">see comparison</a> with other Python web frameworks), let’s build an application that manipulates some I/O. You can use the output of the <em>dnf history</em> command as data for that application.</p>
<p>First, save the output of that command in a file.</p>
<pre class="wp-block-preformatted">$ dnf history | tail --lines=+3 &gt; history.txt</pre>
<p>The command is using <em>tail</em> to remove the headers of <em>dnf history</em> which are not needed by the application. Each dnf transaction can be represented with the following information: </p>
<ul>
<li>id : number of the transaction (increments every time a new transaction is run)</li>
<li>command : the dnf command run during the transaction</li>
<li>date: the date and time the transaction happened</li>
</ul>
<p>Next, modify the <em>main.py</em> file to add that data structure to the application.</p>
<pre class="wp-block-preformatted">from fastapi import FastAPI
from pydantic import BaseModel app = FastAPI() class DnfTransaction(BaseModel): id: int command: str date: str</pre>
<p>FastAPI comes with the <a href="https://pydantic-docs.helpmanual.io/">pydantic</a> library which allow you to easily build data classes and benefit from type annotation to validate your data.</p>
<p>Now, continue building the application by adding a function that will read the data from the <em>history.txt </em> file.</p>
<pre class="wp-block-preformatted">import aiofiles from fastapi import FastAPI
from pydantic import BaseModel app = FastAPI() class DnfTransaction(BaseModel): id: int command: str date: str async def read_history(): transactions = [] async with aiofiles.open("history.txt") as f: async for line in f: transactions.append(DnfTransaction( id=line.split("|")[0].strip(" "), command=line.split("|")[1].strip(" "), date=line.split("|")[2].strip(" "))) return transactions</pre>
<p>This function makes use of the <em><a href="https://github.com/Tinche/aiofiles">aiofiles</a></em> library which provides an asyncio API to manipulate files in Python. This means that opening and reading the file will not block other requests made to the server.</p>
<p>Finally, change the root function to return the data stored in the transactions list.</p>
<pre class="wp-block-preformatted">@app.get("/")
async def read_root(): return await read_history()</pre>
<p>To see the output of the application, run the following command</p>
<pre class="wp-block-preformatted">$ curl http://127.0.0.1:8000 | python -m json.tool
[
{ "id": 103, "command": "update", "date": "2020-05-25 08:35"
},
{ "id": 102, "command": "update", "date": "2020-05-23 15:46"
},
{ "id": 101, "command": "update", "date": "2020-05-22 11:32"
},
....
]</pre>
<h2>Conclusion</h2>
<p><em>FastAPI</em> is gaining a lot a popularity in the Python web framework ecosystem because it offers a simple way to build web services using asyncio. You can find more information about <em>FastAPI</em> in the <a href="https://fastapi.tiangolo.com/">documentation</a>.</p>
<p>The code of this article is available in <a href="https://github.com/cverna/fastapi_app">this GitHub repository</a>.</p>
<hr class="wp-block-separator" />
<p><em>Photo by&nbsp;<a href="https://unsplash.com/@jankubita?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Kubita</a>&nbsp;on&nbsp;<a href="https://unsplash.com/s/photos/fast-snake?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</em></p>
</div>


https://www.sickgaming.net/blog/2020/06/01/use-fastapi-to-build-web-services-in-python/