Skip to content

Instantly share code, notes, and snippets.

@diegofcornejo
Last active January 12, 2022 03:18
Show Gist options
  • Save diegofcornejo/e88e0af77a9144ce3110166c2adbfc2c to your computer and use it in GitHub Desktop.
Save diegofcornejo/e88e0af77a9144ce3110166c2adbfc2c to your computer and use it in GitHub Desktop.
Python: generate csv file from json, fetch json example.
"""*********************************************************
Service: Generate csv from json request
------- Use example ---------------
from helpers.request import Request
params = {
'page':1,
'size':100,
'month':12,
'year':2021
}
Request.toCSV(params)
**********************************************************"""
import requests
import csv
class Request:
def toCSV(params):
page = params['page'] or 0
size = params['size'] or 1
month = params['month'] or 0
year = params['year']
try:
url = 'https://api.diegocornejo.com'
headers = {
'content-type': 'application/json',
'accept': 'application/json'
}
payload = {
"page": page,
"pageSize": size,
"sort": "invoiceid",
"ascending": True,
"month": month,
"year": year,
"org": "AllOrganizations",
"soldby": "All",
"orgviewoption": 1,
"userviewoption": 1
}
response = requests.post(url, headers=headers, json=payload)
items = response.json()['result']['item']
data_file = open(f'{year}_{month}_{page}_{size}.csv', 'w')
csv_writer = csv.writer(data_file)
count = 0
for item in items:
if count == 0:
header = item.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(item.values())
data_file.close()
except Exception as e:
print("Error:", e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment