In this article, I'll show you how to build a Number Classification API using FastAPI, Docker, and Render. The API classifies numbers based on mathematical properties (prime, perfect, Armstrong, odd/even) and fetches fun facts from the Numbers API.
GIF by Augustus
Tools Used
- FastAPI β for building the API.
- Docker β for containerization.
- Render β for deployment.
Step 1: Setting Up the Project
Clone the project and install dependencies:
git clone https://github.com/Fola-Git/number-classification-api.git
cd number-classification-api
pip install -r requirements.txt
Step 2: Building the API with FastApi
Create the API Endpoint
The core of our API is a single route /api/classify-number?number=<num>
that checks whether a number is prime, perfect, Armstrong, or odd/even. Additionally, it fetches a fun fact about the number from the Numbers API.
Hereβs the core logic in app.py
:
from fastapi import FastAPI
import requests
app = FastAPI()
@app.get("/classify-number")
def classify_number(number: int):
result = {"number": number, "classification": classify(number)}
result['fact'] = fetch_number_fact(number)
return result
def classify(number):
"""Determine if a number is prime, perfect, Armstrong, and odd/even."""
return {
"is_prime": is_prime(number),
"is_perfect": is_perfect(number),
"is_armstrong": is_armstrong(number),
"is_even": number % 2 == 0
}
def fetch_number_fact(number):
response = requests.get(f"http://numbersapi.com/{number}")
return response.text if response.status_code == 200 else "No fact found."
# Helper functions (is_prime, is_perfect, is_armstrong) defined in the repo
Step 3: Dockerizing the Application
Creating a Dockerfile
We will containerize the application to ensure it runs in a consistent environment.
FROM python:3.10
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
π Creating docker-compose.yml
To manage the container easily, we use Docker Compose:
version: '3'
services:
web:
build: .
ports:
- "8000:8000"
To build and run the container, use:
docker-compose up --build
π Step 4: Deploying with Render
π Push Your Code to GitHub
Run the following commands to commit and push your project:
git add .
git commit -m "Initial commit"
git push origin main
π Deploy on Render
- Sign in to Render.
- Create a New Web Service.
- Connect your GitHub repository.
- Select FastAPI as the framework.
- Set the start command:
uvicorn app:app --host 0.0.0.0 --port 8000
Click Deploy and Your API will be live!.
π― Conclusion
In this guide, we built a FastAPI Number Classification API, containerized it with Docker, and deployed it on Render.
Feel free to explore and enhance the project with additional features. Check out my repository for the full structure: Fola-Git.
You can also modify online templates to improve the design and functionality. Happy coding!
Top comments (0)