Handle errors and responses appropriately based on the network protocol being used. Different protocols have different mechanisms for error reporting and communication patterns.
For HTTP endpoints:
# When allow_credentials is True, avoid wildcards
app.add_middleware(
CORSMiddleware,
allow_origins=["https://specific-origin.com"], # Not ['*']
allow_methods=["GET", "POST"], # Not ['*']
allow_headers=["X-Custom-Header"], # Not ['*']
allow_credentials=True
)
For WebSockets:
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
# Process data
if error_condition:
# Don't use HTTPException here
await websocket.close(code=1008) # Policy violation
return
except Exception:
await websocket.close(code=1011) # Internal error
For custom headers:
expose_headers
parameterEnter the URL of a public GitHub repository