Below is the sample of the CSV file(sample.csv) i am using
ID Name Address Ph.no Category
1 Person 1 Address 1 1234568789 Category1
2 Person 2 Address 2 1234568790 Category2
3 Person 3 Address 3 1234568791 Category3
4 Person 4 Address 4 1234568792 Category4
5 Person 5 Address 5 1234568793 Category1
6 Person 6 Address 6 1234568794 Category2
7 Person 7 Address 7 1234568795 Category3
8 Person 8 Address 8 1234568796 Category2
9 Person 9 Address 9 1234568797 Category1
Using Bottle Framework i want to build a restful webservice to query this CSV file. The Request will be “/getDetails?category=x”.Response should be table of records (tuples) of ID,Name,Address, Ph.no belong to the category
This is one of the ways to do it:
from bottle import route, run, template, response
from json import dumps
import csv
output = []
# API Endpoint
@get('/getDetails')
def get_details():
category = request.forms.get('category')
response.content_type = 'application/json'
# read csv file
csv_file = open("file-question", "r")
reader = csv.reader(csv_file)
#Traversing the CSV file
for row in reader:
if row[4] == category:
output.append(row)
# Return Output
return dumps(output)
run(host='localhost', port=8080)