display csv data into flask api
- Import necessary modules:
from flask import Flask, jsonify
import csv
- Create a Flask application:
app = Flask(__name__)
- Define a route to handle CSV data:
@app.route('/api/csv_data', methods=['GET'])
- Create a function to read CSV data:
def get_csv_data():
data = []
with open('your_csv_file.csv', 'r') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
data.append(row)
return data
- Define the route function to return CSV data as JSON:
def csv_to_json():
csv_data = get_csv_data()
return jsonify(csv_data)
- Run the Flask application:
if __name__ == '__main__':
app.run(debug=True)
Make sure to replace 'your_csv_file.csv' with the actual path or filename of your CSV file.