Chapter 15. Files
Preview
Besides fielding API requests and traditional content like HTML,
web servers are expected to handle file transfers in both directions.
Very large files may need to be transferred in chunks
that don’t use too much of the system’s memory. You can also provide access to a directory of files
(and subdirectories, to any depth)
with StaticFiles
.
Multipart Support
To handle large files, FastAPI’s uploading and downloading features need these extra modules:
- Python-Multipart
-
pip install python-multipart
- aio-files
-
pip install aiofiles
Uploading Files
FastAPI targets API development, and most of the examples in this book have used JSON requests and responses. But in the next chapter you’ll see forms, which are handled differently. This chapter covers files, which are treated like forms in some ways.
FastAPI offers two techniques for file uploads:
File()
and UploadFile
.
File()
File()
is used as the type for a direct file upload.
Your path function may be synchronous (def
)
or asynchronous (async def
),
but the asynchronous version is better because it won’t
tie up your web server while the file is uploading.
FastAPI will pull up the file in chunks and reassemble it
in memory, so File()
should be used for only
relatively small files.
Instead of assuming that the input is JSON,
FastAPI encodes a file as a form element.
Let’s write the code to request a file and test it. You can grab any file on your machine to test with, or download one from a site like ...
Get FastAPI now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.