File uploads and handling form data are a big deal when it comes to building web apps. FastAPI makes this whole process super easy and efficient. Let’s break down how you can use FastAPI to tame file uploads and manage form data like a pro.
Getting Started with FastAPI
First things first, ensure FastAPI is ready to roll in your environment. If it isn’t, setting it up is a breeze.
Fire up your terminal and navigate to your project folder. Then, create a virtual environment and install the goods.
cd path/to/your/project/directory
python -m venv venv_name
source venv_name/bin/activate # For macOS or Linux
venv_name\Scripts\activate # For Windows
pip install fastapi uvicorn python-multipart
File Uploads: The Basics
FastAPI has got your back when it comes to file uploads, thanks to its File
and UploadFile
types. These nifty features let you handle file data with ease.
Using File
Type
The File
type is perfect when you need to munch on the file contents directly as bytes. Check this out:
from fastapi import FastAPI, File
app = FastAPI()
@app.post("/files/")
async def create_files(files: list[bytes] = File()):
return {"file_sizes": [len(file) for file in files]}
Here, the create_files
endpoint takes in multiple files and spits out their sizes.
Using UploadFile
Type
The UploadFile
type is a bit snazzier, providing you with more details about the uploaded file, such as its name and type.
from fastapi import FastAPI, UploadFile
app = FastAPI()
@app.post("/uploadfiles/")
async def create_upload_files(files: list[UploadFile]):
return {"filenames": [file.filename for file in files]}
In this example, the create_upload_files
endpoint takes in multiple files and returns their filenames.
Juggling Form Data and File Uploads Together
At times, you need to handle both form data and file uploads in one go. FastAPI lets you pull this off by combining Form
and File
or UploadFile
parameters.
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files-and-form/")
async def create_files_and_form(
file: bytes = File(...),
token: str = Form(...),
size: int = Form(...),
):
return {
"file_size": len(file),
"token": token,
"size": size,
}
This example shows the create_files_and_form
endpoint taking a file, a token, and a size all in one swoop.
Combining File Uploads with JSON Payload
There are instances when you need to upload files alongside JSON data. It sounds tricky, but don’t sweat it. Instead of sending both JSON and file data in the same request body, you can convert the file to a base64 encoded string and ship it as part of the JSON payload.
Here’s how to do it:
import base64
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class UpdateProfileSchema(BaseModel):
email: str
picture: str # Base64 encoded string
@app.post("/upload-with-json/")
async def update_profile(payload: UpdateProfileSchema):
data_split = payload.picture.split('base64,')[1]
data = base64.b64decode(data_split)
with open("uploaded_image.png", "wb") as writer:
writer.write(data)
return {"detail": "Profile update successful"}
The update_profile
endpoint is digging for a JSON payload with an email and a base64 encoded image. It decodes that image and stashes it in your file system.
Crafting HTML Forms for File Uploads
To give your file upload endpoints a spin, you can whip up simple HTML forms. Check this snippet out:
from fastapi.responses import HTMLResponse
@app.get("/")
async def main():
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>
"""
return HTMLResponse(content=content)
This will generate two forms: one for uploading with the File
type and another for the UploadFile
type.
Pro Tips and Best Practices
- Grab the
python-multipart
package: It simplifies handling those HTTP multipart requests, which are the bread and butter of file uploads. - Use the right tool for the job:
File
for byte-based uploads,UploadFile
for more intricate file details. - Error handling is key: Always be on the lookout for potential hiccups, like invalid file types or sizes.
- Security first: Be sure to validate and sanitize file uploads to keep security threats at bay.
Armed with these tips and examples, managing file uploads and form data in your FastAPI projects will be a walk in the park. Whether you’re dealing with simple file uploads or the intricate dance of JSON payloads, FastAPI has got you covered, making your development process nothing short of seamless and efficient.