0

If I wanted to push a csv file to an endpoint in Python, what is the correct way to do this?

with open("foo.csv") as f:
  endpoint = 'some-url'
  headers = {}
  r = requests.post(endpoint, ...., headers = headers)

What would be the next steps?

khelwood
  • 55,782
  • 14
  • 81
  • 108
OctaveParango
  • 113
  • 1
  • 14
  • 1
    Does this answer your question? [Send file using POST from a Python script](https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script) – luk2302 Mar 13 '23 at 09:37

2 Answers2

0

it probably depends on the receiving end but a list of lists is a json object, so directly reading the file using csv module could work.

import csv
with open("foo.csv") as f:
  endpoint = 'some-url'
  cr = csv.reader(f)  # delimiter="," by default
  r = requests.post(endpoint, json = list(cr))

or if the csv file has a title, pass a list of dicts

import csv
with open("foo.csv") as f:
  endpoint = 'some-url'
  cr = csv.DictReader(f)  # delimiter="," by default
  r = requests.post(endpoint, json = list(cr))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

you can directly push your CSV file since requests makes it simple to upload multipart encoded files

with open("foo.csv", "rb") as f:
    file_data = {"file": f}
    endpoint = "some-url"
    response = requests.post(endpoint, files=file_data)