Upgrade Your Projects with Fast API
Fast API is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. The key features of Fast API are its speed and ease of use, making it an excellent choice for building robust APIs. Fast API has quickly become a go-to framework for setting up Python APIs and services.
Prerequisites
Before diving into Fast API, 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. Fast API requires Python 3.7 or higher.
Setting Up Your Environment
Install an IDE: Visual Studio Code (VS Code) is recommended for its support for Python and FastAPI.
Check for Python: Open your command prompt and type
python
to open the Python editor. Test it by typingprint('hello')
.Create a Virtual Environment: For Python projects, using a virtual environment (venv) is best practice. It keeps dependencies required by different projects separate.
python -m venv vnv
Activate Virtual Environment
./venv/scripts/activate
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 uvicorn
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.
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.