Let's imagine you're starting a FastAPI project and someone hands you a boilerplate code to kickstart your development. You may wonder why you should consider using it instead of starting from scratch. Well, here are 7 benefits that make it worth your consideration:
-
⚡ Unmatched Speed: This FastAPI implementation is blazingly fast, thanks to its use of the latest PyPy interpreter instead of traditional Python. The code is optimized for maximum performance, and you can hardly make it any faster. At best with a few hours of tweaking, you can achieve the same lightning-fast results, which you can avail instantly.
-
🐳 Simplified Dockerization: While setting up a basic Dockerfile for a Python and FastAPI project is straightforward, things can get messy and error-prone when incorporating PyPy. Fortunately, we've already prepared a well-structured Dockerfile that perfectly integrates PyPy. By leveraging our Dockerfile, you don't have to spend time reinventing the wheel.
-
🚀 Production-Ready Foundation: Building a production-ready codebase often requires countless hours of effort. By forking or using this boilerplate code as a foundation, you save an immense amount of time. The code is already optimized, follows best practices, and is ready to be deployed to a production environment with minimal modifications.
-
💻 Real-Time Development and Testing: Imagine writing your code and instantly seeing the results. With this boilerplate, it's possible. When you save your code in VSCode, the entire application is automatically Dockerized, pushed to a local Kind Kubernetes cluster, and made accessible through port-forwarding. You can view your application in real-time on your laptop, exactly as your customers would see it from server. Handling with poetry is not needed. You see what your customers or peer developers will see without time-consuming deployment testing. If it works in a machine, it will wor everywhere.
-
☁️ Kubernetes-First Approach: If you want to develop with a focus on Kubernetes deployment, this boilerplate is tailored for you. It allows you to write your code and immediately observe how it behaves in a production Kubernetes cluster. Whether you fork the code or download it, you can start development right away with Kubernetes in mind, except juggling with random yaml k8 files. Because, we wrote a production ready helm chart for you.
-
🌟 Industry Best Practices: Rest assured that the codebase you'll be working with is the same one used in production environments. We've followed industry best practices throughout its microservices oriented development, ensuring code quality, scalability, and maintainability.
-
⏱️ Fast Development: By adopting this approach, you can save countless hours lost in debugging. We've learned these lessons the hard way, and now you can benefit from our experience. Speed up your development process and avoid unnecessary debugging efforts.
By considering these benefits, you can leverage this fastest FastAPI boilerplate to accelerate your development process and deliver high-quality, performant applications.
To create you developer environment to start this project you will need to have this in your operation system. Install these developer tools first.
Here are the installation links for the required tools to run this project:
- Helm:
- Official Helm installation: https://helm.sh/docs/intro/install/
- Skaffold:
- Official Skaffold installation: https://skaffold.dev/docs/install/
- Kind:
- Official Kind installation: https://kind.sigs.k8s.io/docs/user/quick-start/
- Docker:
- Docker installation: https://www.docker.com/get-started
- kubectl:
- Kubernetes official installation: https://kubernetes.io/docs/tasks/tools/
Please refer to these links for detailed instructions on installing each tool based on your operating system.
Once you have installed all the necessary tools, follow these steps to proceed:
- 🐳 Open Docker Desktop.
- 🖥️ Open a terminal.
- 📂 Navigate to the directory where the project is located.
- ⚙️ Create a
kind
cluster for the first time. After creating it, you won't need to do it again. To create akind
cluster, run the following command in the terminal:kind create cluster --name faster-fastapi
▶️ From the terminal, start the app by running the command:skaffold dev
- 🌐 Visit
localhost:8080
in your web browser to see the changes.
Now, open the fastapi/app/main.py
file:
# Start developing from here. When you save a line of code, see the changes automatically in `localhost:8080`.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def hello_world():
return {"Hello": "World"}
You can begin developing your FastAPI application from the specified file. Whenever you save a line of code, you will see the changes automatically reflected in localhost:8080
. Happy coding!
Add your python library to the requirements.txt
file. Rest assured, no local installation is needed. 🐍
Of course, you need environment variables. We follow the best practices. Considering the CI/CD pipeline scenario, we store the environment variables for both development and production environments in the following files. Please edit both files. 🌐
fastapi/development.env.yaml
for development environments (For local development.)fastapi/production.env.yaml
for production environments (For production kubernetes cluster.)
secrets:
ENVVARIABLE1: "envvalue1"
ENVVARIABLE2: "envvalue2"
Here you can add your environment variables. Later, you will find these environment variables in your FastAPI application. All variables are stored using Kubernetes secrets with the help of Helm. ⚓️
In a more serious production environment, where you don't want to store environment variables in the codebase, you can set more secret environment variables on the fly from your CI/CD pipeline. 💻
helm upgrade --install --set-json='secret={"envkey1":"envvalue1","envkey2":"envvalue2"}' -f ./fastapi/production.env.yaml fastapi ./fastapi/helm-chart
It's easy. You just have to update the fastapi/production.env.yaml
file. 🚀
resources:
limits:
cpu: 250m # 25% of 1 CPU core
memory: 256Mi
requests:
cpu: 250m # 25% of 1 CPU core
memory: 256Mi
autoscaling:
enabled: true
minReplicas: 1
maxReplicas: 100 # Edit the max replica you want
targetCPUUtilizationPercentage: 80
# targetMemoryUtilizationPercentage: 80
First, create a Kubernetes YAML file in the raw-k8-yaml
directory. Then update the skaffold.yaml
file like this. 🔧
manifests:
rawYaml:
- ./raw-k8-yaml/namespace.yaml # For creating namespaces
- ./raw-k8-yaml/dockerconfigjson.yaml # For creating image pull secrets
- ./raw-k8-yaml/ingress-nginx.yaml # For creating ingress-nginx
Update the production.env.yaml
file with the following entry. 🔒
imagePullSecrets: [{ name: dockerconfigjson-github-com }]
Refer to the above section to add the dockerconfigjson
YAML.
With Helm, it's easy. Just set the variables.
helm upgrade --install --set image.repository=fastapi --set image.tag=latest -f ./fastapi/production.env.yaml fastapi ./fastapi/helm-chart
The default port is 8080
. If you want to change it to 9090
, you need to perform three tasks. 🔄
- Change the
Dockerfile
toEXPOSE 9090/tcp
. - Add the following to your
production.env.yaml
and development.env.yaml
files:
service:
type: ClusterIP
port: 9090
- In your
skaffold.yaml
file, add the following section.
portForward:
- resourceType: deployment
resourceName: fastapi
port: 9090
address: 0.0.0.0
localPort: 9090
By default, the replicaCount
is 1. To increase it, add the following line to your production.env.yaml
file.
replicaCount: 3
Go to fastapi/helm-chart/values.yaml
and tweak it according to your needs. 🛠️
Contributions are welcome as well. We are also open to discussion.
The following steps outline what your CI/CD pipeline will look like in the production environment:
-
🔨 Build Docker Image: Use the
docker build
command to build the Docker image for your FastAPI application. Provide the path to the Dockerfile (fastapi/Dockerfile
) and tag the image with the specified$IMAGE_NAME:$IMAGE_TAG
from the CI/CD environment variable.docker build fastapi/ --file fastapi/Dockerfile --tag $IMAGE_NAME:$IMAGE_TAG
-
🔑 Login to Container Registry: Authenticate with your container registry using the
docker login
command. This step ensures you have the necessary credentials to push the Docker image to the registry. -
🚀 Push Image to Container Registry: Use the
docker push
command to upload the built Docker image ($IMAGE_NAME:$IMAGE_TAG
) to the container registry. This step makes the image accessible for deployment in your production environment.docker push $IMAGE_NAME:$IMAGE_TAG
-
⚙️ Set Kubernetes Context: Configure the Kubernetes context to match your production environment. This ensures that subsequent commands interact with the correct Kubernetes cluster.
-
📄 Apply Raw Kubernetes YAML: Apply any necessary raw Kubernetes YAML files as part of your deployment. Store those in the
raw-k8-yaml
folder. This step typically involves creating namespaces, configuring image pull secrets, or setting up other required Kubernetes resources.kubectl apply -f /raw-k8-yaml
-
🎩 Install Helm: Ensure that Helm is installed in your CI/CD environment. Helm enables you to deploy and manage your FastAPI application using Helm charts.
-
🚢 Run Helm Command: Execute the
helm upgrade --install
command to deploy your FastAPI application using Helm. This command essentially upgrades the installation if it exists or performs a fresh installation. Specify the image repository and tag using the--set
flag (--set image.repository=$IMAGE_NAME --set image.tag=$IMAGE_TAG
). Additionally, provide the path to theproduction.env.yaml
file (-f ./fastapi/production.env.yaml
) to override any Helm values specific to the production environment. Lastly, add the local chart path (./fastapi/helm-chart
) for deploying the Helm chart. Don't forget to include the image pull secrets in theproduction.env.yaml
file.helm upgrade --install --set image.repository=$IMAGE_NAME --set image.tag=$IMAGE_TAG -f ./fastapi/production.env.yaml fastapi ./fastapi/helm-chart
Please note that you may need to adapt these steps based on your specific CI/CD setup, container registry configuration, Kubernetes cluster, and deployment requirements in the production environment.
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.