How to use FastAPI UploadFile with Pydantic model

This is a short tutorial to guide you on how to use Pydantic models and UploadFile together in FastAPI.

I had to figure out a way to achieve this after all sorts of validation errors I had. And since there were no guides online on how best to do this, I decided to write one myself, and I hope it helps someone.

I was trying to build an API endpoint that can handle profile picture uploads, and user information updates at the same time. So I will just go straight to the point. I broke down my models in the classes below so my users can have an idea of what to expect for each route.

Pydantic User models

To use the model with UploadFile I am using the UserUpdate model so I can update it when no file has been uploaded.

Here is the FastAPI route handling the update with None as default values of user fields.

This would give you this view in your openapi interface

You can do whatever you like with the user variable up there. Here is what I did with mine. I excluded all unset fields and all fields with a None value. So when none of the fields is updated, I return an exception

Handle user password field

If everything works fine, we can now save the details to whatever database we intend to work with and return a response with the empty exception

or a successful response which would be up to you how you intend to respond.

Successful response

And Voila!! we have an API endpoint that works. Good luck

--

--

Pronoun: He/Him. Backend Engineer. Passionate about building data-driven and interactive products.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Oluwatosin Olubiyi

Pronoun: He/Him. Backend Engineer. Passionate about building data-driven and interactive products.