FastAPI — Really Fast and Modern

Merwan Chinta
CodeNx
Published in
4 min readFeb 15, 2024

Efficiency and performance are pivotal in the web development design. FastAPI, a modern web framework for building APIs with Python 3.7+, stands out for its speed and ease of use.

This article will walk you through setting up FastAPI, explaining its core features and how to utilize them to build a robust API for managing products.

Routes we are going to define in this article
Routes we are going to define in this article — Image source: By Author

Prerequisites

Before diving into FastAPI, ensure you have Python installed on your system.

You can verify this by running in your command prompt.

python --version

If Python isn't installed, head to www.python.org, navigate to the downloads section, and install the latest version. FastAPI requires Python 3.7 or higher.

Setting Up Your Environment

  1. Install an IDE: Visual Studio Code (VS Code) is recommended for its support for Python and FastAPI.
  2. Check for Python: Open your command prompt and type python to open the Python editor. Test it by typing print('hello').
  3. Create a Virtual Environment: For Python projects, using a virtual environment (venv) is best practice. It keeps dependencies required by different projects separate.

Here’s how to set it up from command prompt:

mkdir SampleFastApi
cd SampleFastApi

python -m venv samplefastapienv

Activating the venv is crucial. You can deactivate it later if necessary.

> samplefastapienv\Scripts\activate.bat

4. Install FastAPI and Uvicorn: Uvicorn is an ASGI server that runs your FastAPI app, run the below commands under your newly created venv.

pip install fastapi
pip install "uvicorn[standard]"

Building Your First FastAPI Application

With your environment set up, it’s time to start building. FastAPI simplifies the creation of web APIs, supporting both synchronous and asynchronous requests.

Open IDE, and open the folder SampleFastApi (not inside the venv), create a file named products.py.

Write your first FastAPI App:

from fastapi import FastAPI

app = FastAPI()

PRODUCTS = [
{'name': 'Laptop', 'price': 1000, 'category': 'Electronics'},
{'name': 'Chair', 'price': 100, 'category': 'Furniture'},
{'name': 'Book', 'price': 20, 'category': 'Education'},
]

@app.get('/')
async def welcome():
return {'message': 'Welcome to our product catalog'}

@app.get('/products')
async def get_all_products():
return PRODUCTS

This simple app can list products.

The @app.get('/') decorator defines a GET route that the app will respond to with a welcome message.

The @app.get('/products') decorator defines a GET route that the app will respond with list of products.

Run Your App

Use Uvicorn to serve your application. Navigate to your project directory in the command prompt and run.

uvicorn products:app --reload

This command tells Uvicorn to look for an instance of FastAPI called app in the products.py file and reload the server automatically on code changes.

You would also notice, localhost URL after running above command.

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [75200] using WatchFiles
INFO: Started server process [107248]
INFO: Waiting for application startup.
INFO: Application startup complete.

The localhost URL is where we can run/test our FastAPI app.

Swagger, a documentation tool that is inbuilt and comes by default with FastAPI is readily available for us to use, by appending /doc to the URL.

http://127.0.0.1:8000/doc

This interactive documentation allows you to test your API's endpoints directly from the browser.

Swagger documentation for FastAPI
Swagger documentation for FastAPI — Image source: By Author

Expanding Your API

FastAPI makes it easy to add functionality. Let’s expand our API to handle product management with CRUD operations.

Adding a Product

from fastapi import Body

@app.post('/products')
async def add_product(product: dict = Body()):
PRODUCTS.append(product)
return {'message': 'Product added successfully'}

This endpoint allows clients to add new products by sending a POST request with product data.

Updating a Product

To update a product, you can use a PUT request. Match the product by name and replace its details.

@app.put('/products/{product_name}')
async def update_product(product_name: str, product: dict = Body()):
for idx, existing_product in enumerate(PRODUCTS):
if existing_product['name'] == product_name:
PRODUCTS[idx] = product
return {'message': 'Product updated successfully'}

Deleting a Product

Similarly, to delete a product, use a DELETE request.

@app.delete('/products/{product_name}')
async def delete_product(product_name: str):
for idx, product in enumerate(PRODUCTS):
if product['name'] == product_name:
PRODUCTS.pop(idx)
return {'message': 'Product deleted successfully'}

FastAPI provides a powerful yet easy-to-use framework for building APIs. The framework’s speed, ease of use, and automatic documentation make it an excellent choice for modern web development projects.

I trust this information has been valuable to you. 🌟 Wishing you an enjoyable and enriching learning journey!

📚 For more insights like these, feel free to follow 👉 Merwan Chinta

--

--

Merwan Chinta
CodeNx

🚧 Roadblock Eliminator & Learning Advocate 🖥️ Software Architect 🚀 Efficiency & Performance Guide 🌐 Cloud Tech Specialist