Guide: Building and Deploying a FastAPI App for Number Classification

This guide walks through the steps to build a simple FastAPI application that classifies a number based on various mathematical properties (e.g., prime, perfect, Armstrong) and provides a fun fact from an external API. The application is then deployed and kept running persistently on an Ubuntu EC2 instance. 1. Setting Up the FastAPI App FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is built on top of Starlette for the web parts and Pydantic for data validation. Steps to Build the App: Create a Virtual Environment: Use venv to isolate project dependencies. python3 -m venv venv source venv/bin/activate Install Dependencies: Install FastAPI, Uvicorn, and any other required libraries (requests for fetching fun facts). pip install fastapi uvicorn requests Create Your FastAPI Application: Create an app.py file where you define the endpoints and the number classification logic (prime check, perfect number check, Armstrong check, etc.). Use the Numbers API to fetch fun facts about the number. Run the Application: Use Uvicorn to run your app locally. uvicorn app:app --host 0.0.0.0 --port 8000 Visit http://localhost:8000 to access the app and http://localhost:8000/docs to view the automatic interactive Swagger API documentation. 2. Configuring CORS for Web Access If your app will be accessed from different origins (like a frontend app), Cross-Origin Resource Sharing (CORS) needs to be configured to avoid restrictions. Add the following middleware to your FastAPI app: from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows all origins allow_credentials=True, allow_methods=["*"], # Allows all methods allow_headers=["*"], # Allows all headers ) 3. Handling Asynchronous Requests FastAPI supports asynchronous programming, which helps in optimizing the performance of I/O-bound tasks, such as fetching data from an external API. Use async and await to fetch fun facts asynchronously from the Numbers API: async def get_fun_fact(n: int) -> str: try: response = requests.get(f"http://numbersapi.com/{n}/math") return response.text except: return f"{n} is a number" 4. Running the App in the Background on Ubuntu EC2 Once the app is running locally, you’ll want to keep it running persistently on a cloud server. Using Ubuntu EC2, you can ensure the app keeps running even after you disconnect by using tools like nohup or systemd. Using nohup: nohup uvicorn app:app --host 0.0.0.0 --port 8000 & This command runs the FastAPI app in the background and saves logs to nohup.out. You can monitor logs by running: tail -f nohup.out Alternatively, Using systemd: For more advanced management, you can create a systemd service to manage the app as a background service, ensuring it starts on boot and restarts on failure. 5. Testing the API With your app running, you can test the endpoints using tools like Postman, cURL, or directly from the browser. Example cURL Request: curl -X GET "http://:8000/api/classify-number?number=42" 6. Documenting the API with Swagger FastAPI automatically generates Swagger UI documentation at http://localhost:8000/docs. This documentation lets users interact with your API directly, making it easier for others to understand and use your endpoints. 7. Best Practices for Deployment Running in the Background: Use tools like nohup or systemd to keep your app running persistently. Monitoring Logs: Use tail or other log monitoring tools to ensure the app is functioning correctly and to catch any errors. Scaling: Consider scaling your app with tools like Docker and Kubernetes for larger projects that require high availability. Conclusion By following these steps, you can build and deploy a FastAPI app that classifies numbers and provides fun facts, while also learning key concepts like asynchronous programming, API documentation, and cloud deployment. Keep the app running using nohup or systemd for persistence, and utilize CORS to allow your app to handle requests from different origins. For detailed instructions and the full code, visit the GitHub Repository.

Feb 5, 2025 - 14:51
 0
Guide: Building and Deploying a FastAPI App for Number Classification

This guide walks through the steps to build a simple FastAPI application that classifies a number based on various mathematical properties (e.g., prime, perfect, Armstrong) and provides a fun fact from an external API. The application is then deployed and kept running persistently on an Ubuntu EC2 instance.

1. Setting Up the FastAPI App

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is built on top of Starlette for the web parts and Pydantic for data validation.

Steps to Build the App:

  1. Create a Virtual Environment: Use venv to isolate project dependencies.
   python3 -m venv venv
   source venv/bin/activate
  1. Install Dependencies: Install FastAPI, Uvicorn, and any other required libraries (requests for fetching fun facts).
   pip install fastapi uvicorn requests
  1. Create Your FastAPI Application:
    Create an app.py file where you define the endpoints and the number classification logic (prime check, perfect number check, Armstrong check, etc.). Use the Numbers API to fetch fun facts about the number.

  2. Run the Application:
    Use Uvicorn to run your app locally.

   uvicorn app:app --host 0.0.0.0 --port 8000

Visit http://localhost:8000 to access the app and http://localhost:8000/docs to view the automatic interactive Swagger API documentation.

2. Configuring CORS for Web Access

If your app will be accessed from different origins (like a frontend app), Cross-Origin Resource Sharing (CORS) needs to be configured to avoid restrictions.

Add the following middleware to your FastAPI app:

from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

3. Handling Asynchronous Requests

FastAPI supports asynchronous programming, which helps in optimizing the performance of I/O-bound tasks, such as fetching data from an external API.

Use async and await to fetch fun facts asynchronously from the Numbers API:

async def get_fun_fact(n: int) -> str:
    try:
        response = requests.get(f"http://numbersapi.com/{n}/math")
        return response.text
    except:
        return f"{n} is a number"

4. Running the App in the Background on Ubuntu EC2

Once the app is running locally, you’ll want to keep it running persistently on a cloud server. Using Ubuntu EC2, you can ensure the app keeps running even after you disconnect by using tools like nohup or systemd.

Using nohup:

nohup uvicorn app:app --host 0.0.0.0 --port 8000 &

This command runs the FastAPI app in the background and saves logs to nohup.out. You can monitor logs by running:

tail -f nohup.out

Alternatively, Using systemd:

For more advanced management, you can create a systemd service to manage the app as a background service, ensuring it starts on boot and restarts on failure.

5. Testing the API

With your app running, you can test the endpoints using tools like Postman, cURL, or directly from the browser.

Example cURL Request:

curl -X GET "http://:8000/api/classify-number?number=42"

6. Documenting the API with Swagger

FastAPI automatically generates Swagger UI documentation at http://localhost:8000/docs. This documentation lets users interact with your API directly, making it easier for others to understand and use your endpoints.

7. Best Practices for Deployment

  • Running in the Background: Use tools like nohup or systemd to keep your app running persistently.
  • Monitoring Logs: Use tail or other log monitoring tools to ensure the app is functioning correctly and to catch any errors.
  • Scaling: Consider scaling your app with tools like Docker and Kubernetes for larger projects that require high availability.

Conclusion

By following these steps, you can build and deploy a FastAPI app that classifies numbers and provides fun facts, while also learning key concepts like asynchronous programming, API documentation, and cloud deployment. Keep the app running using nohup or systemd for persistence, and utilize CORS to allow your app to handle requests from different origins.

For detailed instructions and the full code, visit the GitHub Repository.