Fouten afhandelen

Introductie tot FastAPI

Matt Eckerle

Software and Data Leader

Twee hoofdredenen om fouten af te handelen

Gebruikersfout

  • Ongeldige of verouderde URI
  • Missende of onjuiste 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 {}

Serverfout

  • Er ging iets anders mis
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # Return an error
    return {}
Introductie tot FastAPI

HTTP-statuscodes: "niveaus van roepen"

  • Laat API status in response geven
    • Succes, mislukking, fout, enz.
  • Specifieke codes gedefinieerd in HTTP-protocol
  • Bereik: 100 - 599
  • Categorie op eerste cijfer (1 -5)
  1. Informatieve responses (100 - 199)
  2. Succesvolle responses (200 - 299)
  3. Redirects (300 - 399)
  4. Clientfouten (400 - 499)
  5. Serverfouten (500 - 599)
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Introductie tot FastAPI

Veelvoorkomende HTTP-statuscodes

Succes (200 - 299)

  • 200 OK
    • Standaard succesresponse
  • 201 Created
    • Specifiek voor POST
  • 202 Accepted
    • Niet-bindend. "We werken eraan"
  • 204 No Content
    • Succes! Niets meer te melden

Overige responses

  • 301 Moved Permantently
    • URI permanent veranderd
  • 400 Bad Request
    • Clientfout
  • 404 Not Found
    • Server kan de gevraagde resource niet vinden
  • 500 Internal Server Error
    • Server weet niet hoe deze situatie af te handelen
Introductie tot FastAPI

Fouten afhandelen met statuscodes

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 {}
Introductie tot FastAPI

Laten we oefenen!

Introductie tot FastAPI

Preparing Video For Download...