FastAPI Interview Questions 51-55 (Deployment, Docker, & Logging)

You have built the API, secured it, and even optimized it. The final step is getting it off your laptop and onto the internet.

In this bonus section, we cover the DevOps side of Python engineering: Dockerizing your app, choosing the right server (Uvicorn vs Gunicorn), deploying to the cloud, and setting up logging so you can debug issues in production.

51. How do you mock dependencies in tests?

In Question 48, we used dependency_overrides to replace a database connection. Sometimes, you need to mock standard Python libraries (like requests or boto3) to simulate external services without actually calling them.

The standard tool for this is unittest.mock (or pytest-mock).

from fastapi.testclient import TestClient
from unittest.mock import patch
from main import app

client = TestClient(app)

def test_external_api_call():
    # We want to test an endpoint that calls 'requests.get'
    # But we don't want to actually hit the internet.
    
    mock_response = {"status": "ok", "data": [1, 2, 3]}
    
    # 'patch' temporarily replaces 'requests.get' with our mock
    with patch("requests.get") as mock_get:
        # Configure the mock to return our fake data
        mock_get.return_value.status_code = 200
        mock_get.return_value.json.return_value = mock_response
        
        # Call our API endpoint
        response = client.get("/fetch-data")
        
        assert response.status_code == 200
        assert response.json() == mock_response

52. How do you deploy FastAPI with Uvicorn and Gunicorn?

This is a classic deployment question.
- Uvicorn: An ASGI web server. It is fast but single-process.
- Gunicorn: A WSGI process manager. It is robust and can manage multiple worker processes.

Best Practice: Use Gunicorn as the manager to spawn multiple Uvicorn worker processes. This allows your app to use all CPU cores on the server.

# Command to run in production
# -w 4: Use 4 worker processes
# -k uvicorn.workers.UvicornWorker: Use Uvicorn class
# main:app : The python file and app instance

gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app --bind 0.0.0.0:8000

53. How do you run FastAPI in Docker?

Docker ensures your app runs exactly the same on your laptop and the server. You need a Dockerfile to define the environment.

# Dockerfile

# 1. Base Image (Lightweight Python)
FROM python:3.10-slim

# 2. Set working directory
WORKDIR /app

# 3. Copy requirements and install
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 4. Copy source code
COPY . .

# 5. Run the app
# Using pure Uvicorn inside Docker is fine for simple container setups
# (Or use the Gunicorn command from above)
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

Build & Run:

docker build -t myfastapiapp .
docker run -p 8000:80 myfastapiapp

54. How do you deploy FastAPI on AWS / DigitalOcean / Render?

Deployment strategies vary by platform, but the core concept is always: "Get the code there, install dependencies, run the start command."

PlatformStrategyDifficulty
Render / RailwayConnect GitHub repo. It auto-detects requirements.txt. Set start command.Easy
DigitalOcean App PlatformSimilar to Render, or deploy Docker container.Easy
AWS EC2Manual Linux server setup (SSH, pip install, Systemd service, Nginx).Hard
AWS LambdaUse Mangum adapter to wrap FastAPI as a Lambda handler.Medium

55. How do you configure logging in FastAPI?

In production, print() is not enough. You need structured logging to trace errors. FastAPI uses the standard Python logging module.

import logging
from fastapi import FastAPI

# 1. Configure the logger
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()]
)

logger = logging.getLogger(__name__)
app = FastAPI()

@app.get("/")
def read_root():
    logger.info("Root endpoint accessed")
    try:
        result = 1 / 0
    except ZeroDivisionError:
        logger.error("Math error occurred", exc_info=True)
        return {"error": "oops"}
        
    return {"msg": "ok"}

Sample Output (in app.log):

2023-10-27 10:00:01 [INFO] Root endpoint accessed
2023-10-27 10:00:01 [ERROR] Math error occurred
Traceback (most recent call last):
  File "main.py", line 15, in read_root
    result = 1 / 0
ZeroDivisionError: division by zero
🚀 Deep Dive With AI Scholar