Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fedora - Use FastAPI to build web services in Python

#1
Use FastAPI to build web services in Python

FastAPI 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.

Getting Started


The development environment can be set up using the Fedora container image. The following Dockerfile prepares the container image with FastAPI, Uvicorn and aiofiles.

FROM fedora:32
RUN dnf install -y python-pip \ && dnf clean all \ && pip install fastapi uvicorn aiofiles
WORKDIR /srv
CMD ["uvicorn", "main:app", "--reload"]

After saving this Dockerfile in your working directory, build the container image using podman.

$ podman build -t fastapi .
$ podman images
REPOSITORY TAG IMAGE ID CREATED SIZE
localhost/fastapi latest 01e974cabe8b 18 seconds ago 326 MB

Now let’s create a basic FastAPI program and run it using that container image.

from fastapi import FastAPI app = FastAPI() @app.get("/")
async def root(): return {"message": "Hello Fedora Magazine!"}

Save that source code in a main.py file and then run the following command to execute it:

$ 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!"

You now have a running web service using FastAPI. Any changes to main.py will be automatically reloaded. For example, try changing the “Hello Fedora Magazine!” message.

To stop the application, run the following command.

$ podman stop fastapi

Building a small web service


To really see the benefits of FastAPI and the performance improvement it brings (see comparison with other Python web frameworks), let’s build an application that manipulates some I/O. You can use the output of the dnf history command as data for that application.

First, save the output of that command in a file.

$ dnf history | tail --lines=+3 > history.txt

The command is using tail to remove the headers of dnf history which are not needed by the application. Each dnf transaction can be represented with the following information:

  • id : number of the transaction (increments every time a new transaction is run)
  • command : the dnf command run during the transaction
  • date: the date and time the transaction happened

Next, modify the main.py file to add that data structure to the application.

from fastapi import FastAPI
from pydantic import BaseModel app = FastAPI() class DnfTransaction(BaseModel): id: int command: str date: str

FastAPI comes with the pydantic library which allow you to easily build data classes and benefit from type annotation to validate your data.

Now, continue building the application by adding a function that will read the data from the history.txt file.

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

This function makes use of the aiofiles 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.

Finally, change the root function to return the data stored in the transactions list.

@app.get("/")
async def read_root(): return await read_history()

To see the output of the application, run the following command

$ 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"
},
....
]

Conclusion


FastAPI 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 FastAPI in the documentation.

The code of this article is available in this GitHub repository.


Photo by Jan Kubita on Unsplash.



https://www.sickgaming.net/blog/2020/06/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  Fedora - Docker and Fedora 32 xSicKxBot 0 10 06-27-2020, 09:28 AM
Last Post: xSicKxBot
  Fedora - Getting Started with Haskell on Fedora xSicKxBot 0 11 06-25-2020, 11:13 AM
Last Post: xSicKxBot
  Fedora - Contribute at the Fedora Test Week for Kernel 5.7 xSicKxBot 0 24 06-20-2020, 09:22 AM
Last Post: xSicKxBot
  Fedora - Fedora 32: Simple Local File-Sharing with Samba xSicKxBot 0 30 06-13-2020, 05:44 AM
Last Post: xSicKxBot
  Fedora - Contribute at the Fedora CoreOS Test Day xSicKxBot 0 39 06-06-2020, 07:29 PM
Last Post: xSicKxBot
  Fedora - How to generate an EPUB file on Fedora xSicKxBot 0 37 06-06-2020, 11:40 AM
Last Post: xSicKxBot
  Fedora - Use FastAPI to build web services in Python xSicKxBot 0 30 06-06-2020, 05:32 AM
Last Post: xSicKxBot
  Fedora - Fedora Silverblue, an introduction for developers xSicKxBot 0 36 06-05-2020, 11:22 PM
Last Post: xSicKxBot
  Fedora - Using Fedora to implement REST API in JavaScript: part 2 xSicKxBot 0 33 06-05-2020, 05:00 PM
Last Post: xSicKxBot
  Fedora - The pieces of Fedora Silverblue xSicKxBot 0 29 06-05-2020, 09:57 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Upcoming Events

[-]
Discord

[-]
Latest Threads
[Tut] Python Tuple to Integer
Last Post: xSicKxBot
Today 12:13 PM
» Replies: 0
» Views: 0
(Indie Deal) Crazy Sausage Bundle & Metr...
Last Post: xSicKxBot
Today 12:13 PM
» Replies: 0
» Views: 0
News - NBA 2K21’s Legend Edition Will Pa...
Last Post: xSicKxBot
Today 12:12 PM
» Replies: 0
» Views: 1
News - Hyper Scape Impressions: Is Ubiso...
Last Post: xSicKxBot
Today 12:12 PM
» Replies: 0
» Views: 0
News - This Week At Bungie – 7/2/2020
Last Post: xSicKxBot
Today 06:51 AM
» Replies: 0
» Views: 2
Steam - Weekend Deal – The Elder Scrolls...
Last Post: xSicKxBot
Today 06:49 AM
» Replies: 0
» Views: 3
Xbox Wire - Xbox Insider Release Notes –...
Last Post: xSicKxBot
Today 06:49 AM
» Replies: 0
» Views: 1
Substance Alchemist Hands-On
Last Post: xSicKxBot
Today 05:40 AM
» Replies: 0
» Views: 2
Fedora - Customizing Bash
Last Post: xSicKxBot
Today 05:38 AM
» Replies: 0
» Views: 2
News - Get a job: Join Ziggurat Interact...
Last Post: xSicKxBot
Today 05:37 AM
» Replies: 0
» Views: 2

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2019