Creating sales reports in python

I want to create a sales report in python such that I can retrieve sales automatically with my app.

I have the following code:

import requests

Set up the necessary headers and authentication

api_key = “my_key”
api_password = “my_access_token”
shop_url = “https://client_account.myshopify.com
headers = {
“Content-Type”: “application/json”,
“X-Shopify-Access-Token”: api_password,
}

report_name = “Sales report”
report_query = “SHOW total_sales BY order_id FROM sales SINCE -1m UNTIL today ORDER BY total_sales”

Construct the request payload

payload = {
“report”: {
“name”: report_name,
“shopify_ql”: report_query
}
}

Send the API request to create the report

create_report_url = f"{shop_url}/admin/api/2023-04/reports.json"
response = requests.post(create_report_url, json=payload, headers=headers)

Check the response status, I am getting an error

if response.status_code == 201:
report_data = response.json()
report_id = report_data[‘report’][‘id’]
print(f"Successfully created report with ID: {report_id}")
else:
print(“Failed to create the report. Error:”, response.text)

When checking the response status, I get “Failed to create the report. Error:” printed. So also the response.text seems to be empty. How can I successfully create a sales report?

Hi Wrkt,

How are you pulling the sales data that your app will use to generate the sales report? The report resource will let you create a report, but you can’t access any other reports or data that isn’t created by your app via this resource: “Reports are scoped to the app that created them. When an app creates a report, other apps can’t view, modify, or delete that report. Also, apps can’t access reports that were created from the Shopify admin.”

I believe the issue here could be related to how you’re getting the sales data - you likely will want to access the orders.json endpoint to gather the required data by fetching Orders, Refunds, Transactions, etc via the API and then calculate the sales figures in your Python application.

Hope this helps!

Hi Liam,

Thanks a lot for your reply. I did this, I used initially the orders.json endpoint and calculated sales from this. However this isn’t ideal as orders get refunded for example. Ideally, I want the sales numbers being reported in Shopify.

I understand that you can only get reports from your app that created them. So that’s what I am trying to do: create a sales report with my app and then subsequently get the reports in the future using my app.

Hopefully you can help, appreciate it!

Best,

Wrkt