Request Files¶
You can define files to be uploaded by the client usingFile.
Info
To receive uploaded files, first installpython-multipart.
Make sure you create avirtual environment, activate it, and then install it, for example:
$pipinstallpython-multipartThis is because uploaded files are sent as "form data".
ImportFile¶
ImportFile andUploadFile fromfastapi:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes,File()]):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:bytes=File()):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}DefineFile Parameters¶
Create file parameters the same way you would forBody orForm:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes,File()]):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:bytes=File()):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}Info
File is a class that inherits directly fromForm.
But remember that when you importQuery,Path,File and others fromfastapi, those are actually functions that return special classes.
Tip
To declare File bodies, you need to useFile, because otherwise the parameters would be interpreted as query parameters or body (JSON) parameters.
The files will be uploaded as "form data".
If you declare the type of yourpath operation function parameter asbytes,FastAPI will read the file for you and you will receive the contents asbytes.
Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files.
But there are several cases in which you might benefit from usingUploadFile.
File Parameters withUploadFile¶
Define a file parameter with a type ofUploadFile:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes,File()]):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:bytes=File()):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile):return{"filename":file.filename}UsingUploadFile has several advantages overbytes:
- You don't have to use
File()in the default value of the parameter. - It uses a "spooled" file:
- A file stored in memory up to a maximum size limit, and after passing this limit it will be stored in disk.
- This means that it will work well for large files like images, videos, large binaries, etc. without consuming all the memory.
- You can get metadata from the uploaded file.
- It has afile-like
asyncinterface. - It exposes an actual Python
SpooledTemporaryFileobject that you can pass directly to other libraries that expect a file-like object.
UploadFile¶
UploadFile has the following attributes:
filename: Astrwith the original file name that was uploaded (e.g.myimage.jpg).content_type: Astrwith the content type (MIME type / media type) (e.g.image/jpeg).file: ASpooledTemporaryFile(afile-like object). This is the actual Python file object that you can pass directly to other functions or libraries that expect a "file-like" object.
UploadFile has the followingasync methods. They all call the corresponding file methods underneath (using the internalSpooledTemporaryFile).
write(data): Writesdata(strorbytes) to the file.read(size): Readssize(int) bytes/characters of the file.seek(offset): Goes to the byte positionoffset(int) in the file.- E.g.,
await myfile.seek(0)would go to the start of the file. - This is especially useful if you run
await myfile.read()once and then need to read the contents again.
- E.g.,
close(): Closes the file.
As all these methods areasync methods, you need to "await" them.
For example, inside of anasyncpath operation function you can get the contents with:
contents=awaitmyfile.read()If you are inside of a normaldefpath operation function, you can access theUploadFile.file directly, for example:
contents=myfile.file.read()async Technical Details
When you use theasync methods,FastAPI runs the file methods in a threadpool and awaits for them.
Starlette Technical Details
FastAPI'sUploadFile inherits directly fromStarlette'sUploadFile, but adds some necessary parts to make it compatible withPydantic and the other parts of FastAPI.
What is "Form Data"¶
The way HTML forms (<form></form>) sends the data to the server normally uses a "special" encoding for that data, it's different from JSON.
FastAPI will make sure to read that data from the right place instead of JSON.
Technical Details
Data from forms is normally encoded using the "media type"application/x-www-form-urlencoded when it doesn't include files.
But when the form includes files, it is encoded asmultipart/form-data. If you useFile,FastAPI will know it has to get the files from the correct part of the body.
If you want to read more about these encodings and form fields, head to theMDN web docs forPOST.
Warning
You can declare multipleFile andForm parameters in apath operation, but you can't also declareBody fields that you expect to receive as JSON, as the request will have the body encoded usingmultipart/form-data instead ofapplication/json.
This is not a limitation ofFastAPI, it's part of the HTTP protocol.
Optional File Upload¶
You can make a file optional by using standard type annotations and setting a default value ofNone:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes|None,File()]=None):ifnotfile:return{"message":"No file sent"}else:return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile|None=None):ifnotfile:return{"message":"No upload file sent"}else:return{"filename":file.filename}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"No file sent"}else:return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile|None=None):ifnotfile:return{"message":"No upload file sent"}else:return{"filename":file.filename}UploadFile with Additional Metadata¶
You can also useFile() withUploadFile, for example, to set additional metadata:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:Annotated[bytes,File(description="A file read as bytes")]):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:Annotated[UploadFile,File(description="A file read as UploadFile")],):return{"filename":file.filename}🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFileapp=FastAPI()@app.post("/files/")asyncdefcreate_file(file:bytes=File(description="A file read as bytes")):return{"file_size":len(file)}@app.post("/uploadfile/")asyncdefcreate_upload_file(file:UploadFile=File(description="A file read as UploadFile"),):return{"filename":file.filename}Multiple File Uploads¶
It's possible to upload several files at the same time.
They would be associated to the same "form field" sent using "form data".
To use that, declare a list ofbytes orUploadFile:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportHTMLResponseapp=FastAPI()@app.post("/files/")asyncdefcreate_files(files:Annotated[list[bytes],File()]):return{"file_sizes":[len(file)forfileinfiles]}@app.post("/uploadfiles/")asyncdefcreate_upload_files(files:list[UploadFile]):return{"filenames":[file.filenameforfileinfiles]}@app.get("/")asyncdefmain():content="""<body><form action="/files/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form><form action="/uploadfiles/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form></body> """returnHTMLResponse(content=content)🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportHTMLResponseapp=FastAPI()@app.post("/files/")asyncdefcreate_files(files:list[bytes]=File()):return{"file_sizes":[len(file)forfileinfiles]}@app.post("/uploadfiles/")asyncdefcreate_upload_files(files:list[UploadFile]):return{"filenames":[file.filenameforfileinfiles]}@app.get("/")asyncdefmain():content="""<body><form action="/files/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form><form action="/uploadfiles/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form></body> """returnHTMLResponse(content=content)You will receive, as declared, alist ofbytes orUploadFiles.
Technical Details
You could also usefrom starlette.responses import HTMLResponse.
FastAPI provides the samestarlette.responses asfastapi.responses just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
Multiple File Uploads with Additional Metadata¶
And the same way as before, you can useFile() to set additional parameters, even forUploadFile:
fromtypingimportAnnotatedfromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportHTMLResponseapp=FastAPI()@app.post("/files/")asyncdefcreate_files(files:Annotated[list[bytes],File(description="Multiple files as bytes")],):return{"file_sizes":[len(file)forfileinfiles]}@app.post("/uploadfiles/")asyncdefcreate_upload_files(files:Annotated[list[UploadFile],File(description="Multiple files as UploadFile")],):return{"filenames":[file.filenameforfileinfiles]}@app.get("/")asyncdefmain():content="""<body><form action="/files/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form><form action="/uploadfiles/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form></body> """returnHTMLResponse(content=content)🤓 Other versions and variants
Tip
Prefer to use theAnnotated version if possible.
fromfastapiimportFastAPI,File,UploadFilefromfastapi.responsesimportHTMLResponseapp=FastAPI()@app.post("/files/")asyncdefcreate_files(files:list[bytes]=File(description="Multiple files as bytes"),):return{"file_sizes":[len(file)forfileinfiles]}@app.post("/uploadfiles/")asyncdefcreate_upload_files(files:list[UploadFile]=File(description="Multiple files as UploadFile"),):return{"filenames":[file.filenameforfileinfiles]}@app.get("/")asyncdefmain():content="""<body><form action="/files/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form><form action="/uploadfiles/" enctype="multipart/form-data" method="post"><input name="files" type="file" multiple><input type="submit"></form></body> """returnHTMLResponse(content=content)Recap¶
UseFile,bytes, andUploadFile to declare files to be uploaded in the request, sent as form data.







