FastAPI File upload and store in MySQL.

In this article, we will explore how to upload a file using FastAPI and store it in a MySQL database. This tutorial will cover the following steps:

  1. Set up the database

  2. Install dependencies

  3. Create a FastAPI app

  4. Define the file upload endpoint

  5. Store the file in the MySQL database

Step 1:

Set up the Database

First, we need to set up the MySQL database. You will need to have MySQL installed on your system and create a database and table to work with. For this tutorial, we will create a table called "files" with the following schema:

CREATE TABLE files (
    id INT(11) NOT NULL AUTO_INCREMENT,
    filename VARCHAR(100) NOT NULL,
    content BLOB NOT NULL,
    PRIMARY KEY (id)
);

Step 2:

Install Dependencies

Next, install the necessary dependencies. You will need to install the following libraries:

pip install fastapi
pip install uvicorn
pip install mysql-connector-python

Step 3:

Create a FastAPI app

Once you have installed the dependencies, create a new file called "main.py" and import the necessary libraries:

from fastapi import FastAPI, File, UploadFile
import mysql.connector

Next, create a FastAPI app instance:

app = FastAPI()

Step 4:

Define the file upload endpoint

Now that the app is set up, define the file upload endpoint:

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

This endpoint takes in a file of type UploadFile and returns the filename of the uploaded file.

Step 5:

Store the file in the MySQL database

To store the file in the MySQL database, we need to modify the endpoint to read the contents of the file and insert it into the database. Here is the modified endpoint:

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    mydb = mysql.connector.connect(
      host="localhost",
      user="yourusername",
      password="yourpassword",
      database="mydatabase"
    )
    cursor = mydb.cursor()
    contents = await file.read()
    sql = "INSERT INTO files (filename, content) VALUES (%s, %s)"
    val = (file.filename, contents)
    cursor.execute(sql, val)
    mydb.commit()
    return {"filename": file.filename}

This endpoint reads the contents of the uploaded file using the read() method and stores it in a variable called contents. It then creates a connection to the MySQL database and inserts the filename and contents of the file into the "files" table using a prepared statement.

Step 6:

Start the server

Finally, start the server using the "uvicorn" library:

uvicorn main:app --reload

This will start the server on localhost:8000. You can now test the file upload endpoint using a tool like Postman.

Conclusion

In this article, we have explored how to upload a file encoded in base64 string format using FastAPI and store it in a MySQL database. With its easy-to-use syntax and powerful features, FastAPI makes it simple to create a robust REST API in Python.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!