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 and runs one process by default, but its --workers flag can start several.
- Gunicorn: A WSGI process manager. It is robust and can manage multiple worker processes.

Best Practice: Run multiple Uvicorn worker processes so your app can use all CPU cores on the server. FastAPI's docs now simply use Uvicorn's own --workers flag; the classic alternative is Gunicorn as the manager, with the worker class from the uvicorn-worker package (the old uvicorn.workers module is deprecated).

# Command to run in production (4 worker processes)
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

# Classic alternative: Gunicorn as the process manager
# pip install gunicorn uvicorn-worker
# -w 4: Use 4 worker processes
# -k uvicorn_worker.UvicornWorker: Use the Uvicorn worker class
# main:app : The python file and app instance
gunicorn -w 4 -k uvicorn_worker.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.13-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,123 [INFO] Root endpoint accessed
2023-10-27 10:00:01,124 [ERROR] Math error occurred
Traceback (most recent call last):
  File "/app/main.py", line 18, in read_root
    result = 1 / 0
             ~~^~~
ZeroDivisionError: division by zero

Check your understanding

3 questions · no sign-up · misses join your review queue, on this device only

0/3 answered
Question 1

1.What is the usual relationship between Uvicorn and Gunicorn?

Question 2

2.Why copy requirements and install dependencies before copying application code in a Dockerfile?

Question 3

3.What is the main benefit of structured (JSON) logging in production?

0 / 74 ranges

Progress is stored in this browser only - no sign-up, nothing sent anywhere.

Go deeper

The same topic at architecture level, in the system design curriculum.