Python FastAPI Tutorial #34: How to Read and Write With CSV Files in Python FastAPI
In this tutorial, we will cover how to read and write data from CSV files using Python FastAPI. CSV (Comma Separated Values) files are a popular file format for storing tabular data, such as spreadsheets or databases. FastAPI is a modern, fast web framework for building APIs with Python.
To start, make sure you have Python and FastAPI installed on your machine. You can install FastAPI using pip:
pip install fastapi
In addition, we will be using the csv
module which is a built-in Python module for working with CSV files. There is no need to install any additional packages for this.
Now, let’s create a new Python file, for example csv_api.py
, and import FastAPI and the necessary modules:
from fastapi import FastAPI
import csv
Next, we will instantiate our FastAPI application:
app = FastAPI()
Now, let’s create routes for reading and writing data to a CSV file. To read data from a CSV file, we can create a GET endpoint that will return the CSV data. To do this, we first need to create a CSV file with some data.
Create a file named data.csv
and add some sample data:
Name, Age, Gender
Alice, 25, Female
Bob, 30, Male
Charlie, 35, Male
Now, let’s create a route to read data from the CSV file and return it as a JSON response:
@app.get("/read_csv")
async def read_csv():
with open('data.csv', mode='r') as file:
csv_reader = csv.DictReader(file)
data = [row for row in csv_reader]
return data
In this endpoint, we open the file in read mode (‘r’) using the open
function, then use csv.DictReader
to read each row of the CSV file as a dictionary. We then return the list of dictionaries as JSON data.
To write data to a CSV file, we can create a POST endpoint that takes data in the request body and appends it to the CSV file. Let’s create a route for this:
@app.post("/write_csv")
async def write_csv(data: dict):
with open('data.csv', mode='a', newline='') as file:
fieldnames = ['Name', 'Age', 'Gender']
writer = csv.DictWriter(file, fieldnames=fieldnames)
if file.tell() == 0:
writer.writeheader()
writer.writerow(data)
return {"message": "Data written successfully"}
In this endpoint, we open the file in append mode (‘a’) using the open
function and create a csv.DictWriter
instance to write data to the CSV file. We check if the file is empty (using file.tell()
) and if so, write the header row. We then write the data provided in the request body to the CSV file.
To test our API, run the FastAPI development server using the following command:
uvicorn csv_api:app --reload
You can now make requests to your endpoints using tools like cURL or Postman. To read the data from the CSV file, make a GET request to localhost:<port>/read_csv
. To write data to the CSV file, make a POST request to localhost:<port>/write_csv
with the data to be written in the request body.
That’s it! You now know how to read and write data to CSV files using Python FastAPI. Happy coding!