0
0
FastAPIframework~30 mins

Logging errors in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Logging errors in FastAPI
📖 Scenario: You are building a simple web API using FastAPI. You want to keep track of errors that happen when users call your API. Logging errors helps you find and fix problems quickly.
🎯 Goal: Create a FastAPI app that logs error messages when an exception happens in an endpoint.
📋 What You'll Learn
Create a FastAPI app instance called app
Set up a logger named logger using Python's logging module
Add a configuration to log error messages to the console
Create an endpoint /divide that divides two query parameters a and b
Catch division errors and log the error message using logger.error
Return a JSON response with the error message when division by zero occurs
💡 Why This Matters
🌍 Real World
Logging errors in web APIs helps developers quickly find and fix bugs, improving app reliability.
💼 Career
Understanding error logging is essential for backend developers and DevOps engineers to maintain healthy production systems.
Progress0 / 4 steps
1
Create FastAPI app and import logging
Import FastAPI from fastapi and logging. Create a FastAPI app instance called app.
FastAPI
Need a hint?

Use app = FastAPI() to create the app instance.

2
Set up logger to log errors to console
Create a logger named logger using logging.getLogger(__name__). Set the logger level to logging.ERROR. Add a StreamHandler to output logs to the console.
FastAPI
Need a hint?

Use logging.getLogger(__name__) to create the logger and logger.setLevel(logging.ERROR) to set the level.

3
Create /divide endpoint with error logging
Create a GET endpoint /divide that accepts query parameters a and b as floats. Inside the function, try to divide a by b. If a ZeroDivisionError occurs, log the error message using logger.error and return a JSON response with key error and a message "Cannot divide by zero".
FastAPI
Need a hint?

Use try and except ZeroDivisionError as e to catch the error and log it.

4
Print a test log message
Add a line to log an error message "Test error log" using logger.error.
FastAPI
Need a hint?

Use logger.error("Test error log") to print the test message.