FileResponse is an optimized response class for serving files. It automatically handles content type detection, content length, caching headers, and range requests.
Import
Class Signature
Constructor Parameters
str | PathLike
required
The file path to serve. Can be absolute or relative.
int
default:"200"
The HTTP status code for the response.
dict | None
default:"None"
Additional HTTP headers to include in the response.
str | None
default:"None"
The media type for the file. If not provided, it’s automatically detected from the file extension.
BackgroundTask | None
default:"None"
Background task to run after the file is sent.
str | None
default:"None"
The filename to use in the
Content-Disposition header for downloads.os.stat_result | None
default:"None"
Pre-computed file stats to avoid redundant filesystem calls.
str | None
default:"None"
The HTTP method (usually set automatically by FastAPI).
str
default:"attachment"
The Content-Disposition type:
attachment (download) or inline (display in browser).Usage
Basic File Response
Serve a file directly:Using response_class
Return just the file path when usingresponse_class:
Force Download with Custom Filename
Set a download filename using thefilename parameter:
Display in Browser (Inline)
Useinline content disposition to display files in the browser:
Custom Headers
Add custom headers to the file response:Dynamic File Path
Serve files based on path parameters:Automatic Features
Content Type Detection
The media type is automatically detected based on file extension:.pdf→application/pdf.jpg,.jpeg→image/jpeg.png→image/png.mp4→video/mp4.txt→text/plain- etc.
Range Requests
FileResponse automatically supports HTTP range requests, enabling:
- Video/audio seeking in browsers
- Resume interrupted downloads
- Efficient bandwidth usage
Caching Headers
Automatically includes:Content-Length- File sizeLast-Modified- File modification timeETag- Entity tag for caching
Content-Disposition
TheContent-Disposition header controls how browsers handle the file:
attachment (default)
Forces download with optional custom filename:inline
Displays in browser (for images, PDFs, videos):Properties
chunk_size
The size of chunks when streaming the file (default: 64KB):Notes
FileResponseis more efficient than manually streaming files withStreamingResponse- Files are streamed in chunks, not loaded entirely into memory
- Supports serving files of any size
- Automatically handles HEAD requests
- Works with both synchronous and asynchronous path operations
- Media type detection requires proper file extensions
Security Considerations
- Always validate file paths to prevent directory traversal attacks
- Don’t expose sensitive file paths in error messages
- Consider using absolute paths or validating against allowed directories
- Be cautious with user-provided filenames
Related
- StreamingResponse - For streaming data
- StaticFiles - Serving static file directories
- Response - Base response class