Handling errors

Introduction to FastAPI

Matt Eckerle

Software and Data Leader

Two Main Reasons To Handle Errors

User error

  • Invalid or outdated URI
  • Missing or incorrect input
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Return an error
    else:
        crud.delete_item(item)
        return {}

Server error

  • Something else happened
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
Introduction to FastAPI

HTTP Status Codes: "Levels of Yelling"

  • Enables API to provide status in response
    • Success, failure, error, etc.
  • Specific codes defined in HTTP protocol
  • Range: 100 - 599
  • Categorize by first number (1 -5)
  1. Informational responses (100 - 199)
  2. Successful responses (200 - 299)
  3. Redirection messages (300 - 399)
  4. Client error responses (400 - 499)
  5. Server error responses (500 - 599)
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Introduction to FastAPI

Common HTTP Status Codes

Success (200 - 299)

  • 200 OK
    • Default success response
  • 201 Created
    • Specific to POST operation
  • 202 Accepted
    • Noncommittal. "Working on it"
  • 204 No Content
    • Success! Nothing more to say

Other responses

  • 301 Moved Permantently
    • URI changed permanently
  • 400 Bad Request
    • Client error
  • 404 Not Found
    • Server cannot find the requested resource
  • 500 Internal Server Error
    • Server has encountered a situation it does not know how to handle
Introduction to FastAPI

Handling Errors With Status Codes

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # Send response with status 404 and specific error message
        raise HTTPException(status_code=404, detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}
Introduction to FastAPI

Let's practice!

Introduction to FastAPI

Preparing Video For Download...