Table of contents
- Create Your First API with Python: Flask, FastAPI, and Django Explained
- Introduction
- Building a Simple API
- Flask
- FastAPI
- Django
- Setting up the Environment
- Creating a Django Project and App
- Defining a Model (File: myapp/models.py)
- Creating a Serializer (File: myapp/serializers.py)
- Creating a View (File: myapp/views.py)
- Defining URL Routing (File: myapp/urls.py)
- Including App URL Configuration (File: myproject/urls.py)
- Adding App to Installed Apps (File: myproject/settings.py)
- Migrating the Database
- Running the Server
- Comparison Between Frameworks
- Conclusion
- References and Further Reading plus Github Repo for these APIs
Create Your First API with Python: Flask, FastAPI, and Django Explained
Introduction
Welcome to the thrilling and dynamic realm of APIs! In this comprehensive, beginner-friendly guide, we will embark on a journey to discover how to construct a fundamental API utilizing three renowned Python frameworks: Flask, FastAPI, and Django. Regardless of whether you are a programming novice or simply intrigued by these powerful frameworks, this guide is designed to cater to all levels of expertise. So, without further ado, let's dive headfirst into the fascinating world of API building!
What Are APIs?
Understanding APIs: The Building Blocks of Connectivity
APIs, which stand for Application Programming Interfaces, can be best described as the enchanting bridges that seamlessly connect disparate software applications. These indispensable tools facilitate communication and information exchange between various services, ultimately making our digital lives more interconnected and efficient. By acting as intermediaries, APIs enable software developers to integrate diverse functionalities and features into their applications, thus fostering innovation and enhancing user experiences.
Overview of Flask, FastAPI, and Django
Flask: A lightweight and flexible framework that provides the essentials to get started quickly.
FastAPI: A modern, high-performance framework designed specifically for building APIs with automatic documentation.
Django: A feature-rich framework that offers many built-in tools, suitable for building complex web applications.
Building a Simple API
Flask
Setting up the Environment
Windows
Open Visual Studio Code (VS Code).
Install Python from the official website.
Create a virtual environment:
python -m venv myenv
.Activate the virtual environment:
myenv\Scripts\activate
.Install Flask:
pip install flask
.
Mac/Linux
Open VS Code.
Install Python using a package manager like Homebrew or from the official website.
Create a virtual environment:
python3 -m venv myenv
.Activate the virtual environment:
source myenv/bin/activate
.Install Flask:
pip install flask
.
Creating a Simple CRUD API
Create a file named app.py
with the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/items', methods=['GET'])
def get_items():
return {'items': ['item1', 'item2']}
if __name__ == '__main__':
app.run()
To run the server:
python app.py
once the server opens go to 127.0.0.1:5000/items
and you should see the following on Firefox
Or for example Brave without advanced tools:
To stop the server go to the terminal and click ctrl+c
FastAPI
Setting up the Environment
Windows
Open VS Code.
Install Python from the official website.
Create a virtual environment:
python -m venv myenv
.Activate the virtual environment:
myenv\Scripts\activate
.Install FastAPI and uvicorn:
pip install fastapi uvicorn
.
Mac/Linux
Open VS Code.
Install Python using a package manager like Homebrew or from the official website.
Create a virtual environment:
python3 -m venv myenv
.Activate the virtual environment:
source myenv/bin/activate
.Install FastAPI and uvicorn:
pip install fastapi uvicorn
.
Creating a Simple CRUD API
Create a file named main.py
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def read_items():
return {"items": ["item3", "item4"]}
To run the server:
uvicorn main:app --reload
Open the browserlink and add items again in the url like this
http://127.0.0.1:8000/items and you should see one or the following
Firefox
Chrome
To stop the server go to the terminal and click ctrl+c
Django
Setting up the Environment
Windows
Open VS Code.
Install Python from the official website.
Create a virtual environment:
python -m venv myenv
.Activate the virtual environment:
myenv\Scripts\activate
.Install Django:
pip install django
.Install Django Rest Framework:
pip install djangorestframework
.
Mac/Linux
Open VS Code.
Install Python using a package manager like Homebrew or from the official website.
Create a virtual environment:
python3 -m venv myenv
.Activate the virtual environment:
source myenv/bin/activate
.Install Django:
pip install django
.Install Django Rest Framework:
pip install djangorestframework
.
Creating a Django Project and App
Create a new Django project:
django-admin startproject myproject
.Navigate to the project directory:
cd myproject
.Create a new app:
python
manage.py
startapp myapp
.
Defining a Model (File: myapp/models.py
)
Create a model for the items by adding the following code in the models.py
file of your app:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
Creating a Serializer (File: myapp/serializers.py
)
Create a new file named serializers.py
in your app's directory, and add the following code to define a serializer:
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ['name']
Creating a View (File: myapp/views.py
)
Open the views.py
file in your app's directory and add the following code to define a view:
from django.http import JsonResponse
from .models import Item
from .serializers import ItemSerializer
def get_items(request):
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
return JsonResponse({'items': serializer.data})
Defining URL Routing (File: myapp/urls.py
)
Create a new file named urls.py
in your app's directory and add the following code to define URL routing:
from django.urls import path
from .views import get_items
urlpatterns = [
path('items/', get_items),
]
Including App URL Configuration (File: myproject/urls.py
)
Open the urls.py
file in your main project directory and modify it to include your app's URL configuration:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Include the app's URL configuration
]
Adding App to Installed Apps (File: myproject/settings.py
)
Open the settings.py
file in your main project directory and add your app to the INSTALLED_APPS
list:
INSTALLED_APPS = [
...
'myapp', # Add this line
...
]
Migrating the Database
Create the corresponding database table by running the following commands:
python manage.py makemigrations
python manage.py migrate
Running the Server
Start the server with:
python manage.py runserver
To access the API, open your browser and go to:
http://127.0.0.1:8000/items/
You should see an empty list so now you need to add something in there so stop the server go to the terminal and click ctrl+c.
To add specific items (e.g., "item5" and "item6") to the database so that they show up in the API response, you can use Django's shell. Here's a step-by-step guide:
- Open Django's Shell: Run the following command in your terminal (make sure you are in your project directory):
python manage.py shell
Import the Item Model: In the shell, import the
Item
model you defined earlier:from myapp.models import Item
Create New Items: Create new items with the names "item5" and "item6":
item5 = Item(name='item5') item5.save() item6 = Item(name='item6') item6.save()
Exit the Shell: You can exit the shell by typing:
exit()
Verify the Items: If you now access the API by going to
http://127.0.0.1:8000/items/
, you should see the added items in the JSON response.
If you prefer using Django's admin interface to manage items, you'll need to first stop the server again and register the Item
model with the admin site. Add the following code to your app's admin.py
file:
from django.contrib import admin
from .models import Item
admin.site.register(Item)
Create a Superuser Account: In your terminal, while in your project directory, run the following command:
python manage.py createsuperuser
Enter the Required Information: You'll be prompted to enter a username, email address, and password for the superuser account. Make sure to remember these credentials, as you'll need them to log in to the admin interface.
Access the Admin Interface: Once the superuser account is created, you can start the server (if it's not already running):
python manage.py runserver
Then, navigate to the admin site at
http://127.0.0.1:8000/admin/
and log in with the superuser credentials you've just created.Manage Items: From the admin interface, you can manage the items (and other database objects) using a user-friendly graphical interface.
These detailed instructions should have provided a clear and comprehensive guide to building a simple API with Django, including the necessary steps to set up the environment, define the model, serializer, view, and URL routing, and run the server, add items with Django shell and guidance how to create a superuser and use the admin panel for CRUD actions.
Comparison Between Frameworks
Ease of Use: Flask offers simplicity, FastAPI emphasizes speed and documentation, and Django provides comprehensive features.
Performance: FastAPI generally performs better in terms of speed.
When to Use Which: Choose Flask for flexibility, FastAPI for modern APIs with performance, and Django for
Conclusion
Building an API is an exciting and valuable skill. Whether you choose Flask for its simplicity, FastAPI for its modern features, or Django for its robust capabilities, you're on the path to becoming a proficient web developer. Happy coding, and may your code be bug-free!
References and Further Reading plus Github Repo for these APIs
Thank you for reading
If you have any requests for future topics or comments on these please let me know. I am more than happy to write about things of interest.