I'm currently using simple-salesforce to return some rows and write to a csv file with column headers. However, if the row count is 0 e.g. 'select Id from Lead limit 0' I just get the following response
OrderedDict([('totalSize', 0), ('done', True), ('records', [])])
Is there a way of still getting the column headers even if there are zero rows returned in the query.
Basically I need to create the csv with headers even if there are 0 rows
Unfortunately, there's not. A query doesn't really return headers as such at all (unless you use the Bulk API); in just returns a list of records composed of key-value pairs.
The usual pattern is that you generate a query from a list of fields, and that list of fields becomes your column headers. For example,
fields = ["Id", "Name"]
results = sf.query(f"SELECT {', '.join(fields)} FROM Lead")
writer = csv.writer(some_file)
writer.writerow(fields)
# etc., or use a DictWriter if desired.