In this post I’m going to cover how to handle file uploads using FastAPI. You can send the form any way you like, but for ease of use I’ll provide a cURL command you can use to test it. This is something I did on my stream and thought might be useful to others. The code is available on my GitHub repo.

I’m starting with an existing API written in FastAPI, so won’t be covering setting that up in this post.

File uploads are done in FastAPI by accepting a parameter of type UploadFile - this lets us access files that have been uploaded as form data.

To use UploadFile, we first need to install an additional dependency:

pip install python-multipart

Then the first thing to do is to add an endpoint to our API to accept the files, so I’m adding a post endpoint:

@router.post("/")
async def receive_file(file: UploadFile = File(...)):

Once you have the file, you can read the contents and do whatever you want with it. For this example I’m simply writing the content to a new file (using a timestamp to make sure it’s almost a unique name) - just to show that it’s working as expected.

    dir_path = os.path.dirname(os.path.realpath(__file__))
    filename = f'{dir_path}/uploads/{time.time()}-{file.filename}'
    f = open(f'{filename}', 'wb')
    content = await file.read()
    f.write(content)

Once you run the API you can test this using whatever method you like, if you have cURL available you can run:

curl --request POST -F "file=@./python.png" localhost:8000

Alternatively you can send the same kind of command through Postman or whatever tool you choose, or through code. For example, if you were using Axios on the frontend you could use the following code:

let formData = new FormData();
formData.append('file', file);
await axios.post('http://localhost:8000/',
        formData,
        {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });

Just a short post, but hopefully this post was useful to someone.