Bird
0
0

You want to create a FastAPI endpoint that lets users download a CSV file named data.csv stored in static/files/. The file path may not exist sometimes. Which is the best way to handle this safely?

hard🚀 Application Q15 of 15
FastAPI - File Handling
You want to create a FastAPI endpoint that lets users download a CSV file named data.csv stored in static/files/. The file path may not exist sometimes. Which is the best way to handle this safely?
AUse <code>FileResponse</code> with a try-except block to catch file not found errors and return 404
BReturn <code>FileResponse</code> directly without checking; client will get an error if file missing
CUse <code>StreamingResponse</code> without checking file existence
DSend the file content as a plain string response
Step-by-Step Solution
Solution:
  1. Step 1: Understand file existence risk

    Since the file may not exist, directly returning FileResponse risks server errors or confusing client errors.
  2. Step 2: Implement error handling

    Using a try-except block to catch FileNotFoundError and returning a 404 response is best practice for user-friendly error handling.
  3. Final Answer:

    Use FileResponse with a try-except block to catch file not found errors and return 404 -> Option A
  4. Quick Check:

    Check file existence and handle errors gracefully [OK]
Quick Trick: Always check file exists before FileResponse to avoid errors [OK]
Common Mistakes:
MISTAKES
  • Not handling missing files causing server errors
  • Using StreamingResponse without reason
  • Sending raw file content as string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes