To create a post with a cover image in a single request, you need to send both text and a file through multipart/form-data. FastAPI handles it by declaring text fields with Form() and the file with File() in the same function signature — the framework splits the two parts automatically and returns 422 when data is missing. This works for any endpoint that receives a form with a file: posting with an image, updating a profile with an avatar, or importing a CSV with a note.
The Problem
An endpoint that creates a post with an image is often written like this — a Pydantic model for the text and an UploadFile for the image:
from fastapi import FastAPI, File, UploadFilefrom pydantic import BaseModelapp = FastAPI()class PostCreate(BaseModel): title: str caption: str | None = None@app.post("/posts/")async def create_post(post: PostCreate, image: UploadFile = File(...)): return {"title": post.title}
It looks reasonable, but this endpoint will never receive a valid request. FastAPI collapses the whole model into a single nested form field named post, while clients usually send title and caption as separate fields plus the image file — so every request returns 422 Field required for the post body. The app still runs normally, so the error only shows up when you test it for real. Sending JSON with a file is useless too — an endpoint with File() must receive multipart/form-data.
The Solution
Drop the model from the function signature, declare each text field with Form(), and keep UploadFile for the file:
from fastapi import FastAPI, File, Form, HTTPException, UploadFileapp = FastAPI()ALLOWED_TYPES = {"image/jpeg", "image/png", "image/webp"}MAX_SIZE = 5 * 1024 * 1024 # 5MB@app.post("/posts/")async def create_post( title: str = Form(min_length=3, max_length=100), caption: str | None = Form(default=None, max_length=500), image: UploadFile = File(...),): if image.content_type not in ALLOWED_TYPES: raise HTTPException(status_code=400, detail="chi nhan anh jpeg/png/webp") data = await image.read() if len(data) > MAX_SIZE: raise HTTPException(status_code=413, detail="file qua 5MB") return { "title": title, "caption": caption, "filename": image.filename, "size": len(data), }
Now title and caption are separate form fields, and each one is still validated as usual — a title shorter than 3 characters or a missing image file is rejected with 422 before the function runs. You can also type the file as bytes = File(...), but UploadFile is better for large files because FastAPI spools the file to a temporary disk file instead of holding it all in RAM. Remember to install python-multipart — without it, FastAPI errors at startup because it cannot read form data. On the client side: curl uses -F for each field, requests uses data= and files=, and an HTML form needs enctype="multipart/form-data".
Apply It to Your Project
Use it right away for a post-creation form with a cover image, a profile-update form with an avatar, or a data-import form with a CSV file and a note. One rule to remember: whenever File() is in the signature, everything else must be Form() — never mix a JSON model in. If the form has many text fields, group them into a dependency class: its __init__ takes the Form() fields, and the endpoint just Depends on that class.
Related Posts
- FastAPI: Receive Form Data with Form() — a Standard OAuth2 Login Endpoint in 5 Minutes
- FastAPI: Receive File Uploads with UploadFile — Block Oversized and Wrong-Format Files Before Saving in 5 Minutes
- FastAPI: Bundle a Dozen Query Params into One Pydantic Model — Centralized Validation in 5 Minutes
Frequently Asked Questions
Can I use a Pydantic model for the form text?
No — each form field must be declared separately with Form(). If the form has many fields, group them into a dependency class: the class’s __init__ takes the Form() fields, and the endpoint only needs Depends on that class. This has been verified to work on FastAPI 0.143.
For large files, should I use bytes or UploadFile?
Use UploadFile. With bytes, FastAPI reads the whole file into RAM; with UploadFile, the file is spooled to a temporary disk file and you read it in chunks with await file.read(size). A file of several dozen MB or more using bytes can easily exhaust the server’s RAM.
What happens if the client sends JSON with a file?
It gets a 422. An endpoint with File() must use multipart/form-data: curl uses the -F flag for each field, requests uses data= for text and files= for the file, and an HTML form must have enctype="multipart/form-data". A JSON body only works when the endpoint has no File() or Form().
What error appears without python-multipart?
FastAPI errors right at startup because it cannot read form data. Install it with pip install python-multipart and declare it in the project’s requirements — missing this package at deploy time is the most common mistake.
💬 Have you tried this in your own project? If you hit an error or have a cleaner way to do it, leave a comment below — I read every comment and will add the best ideas to the post.
References
- FastAPI docs — Request Forms and Files: https://fastapi.tiangolo.com/tutorial/request-forms-and-files/
- FastAPI docs — Request Files: https://fastapi.tiangolo.com/tutorial/request-files/
- FastAPI docs — Form Data: https://fastapi.tiangolo.com/tutorial/request-forms/
