Using the Looker API to Generate PDFs
Downloading a PDF version of your dashboard is great and also possible via the Looker UI. In this article, we make use of the Looker API (and the Python SDK client) to do this.
Step 1
Authenticate into the Looker API.
import lookerbase_url = 'https://docsexamples.dev.looker.com:19999/api/3.1'client_id = ''client_secret = ''# instantiate Auth APIunauthenticated_client = looker.ApiClient(base_url)unauthenticated_authApi = looker.ApiAuthApi(unauthenticated_client)# authenticate clienttoken = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret)client = looker.ApiClient(base_url, 'Authorization', 'token ' + token.access_token)
Step 2
Create a new task to render the desired dashboard to a PDF, using the create_dashboard_render_task
endpoint. Please take note of the format of dashboard_filters
, which is a string and expects the filters in query URL format. For example: "My Filter=New York&My Other Filter=Brooklyn."
# instantiate render task APIrenderTask = looker.RenderTaskApi(api_client=client)height = 842width = 595result_format = 'pdf'dashboard_id = 241body = {"dashboard_style": "tiled","dashboard_filters": {"Created Date=12 months ago for 12 months"}}# fire a render task and get its IDtask_response = renderTask.create_dashboard_render_task(dashboard_id, result_format, body, width, height)task_id = task_response.id
Step 3
Use the render_task(id)
endpoint to confirm that the render task has finished:
task = renderTask.render_task(task_id, fields='status')task.status
Once the task status returns "success", we can get the produced document using the render_task_results
endpoint as follows:
# get the produced resultsresults = renderTask.render_task_results(task_id, _preload_content = False)data = results.data# write it to PDFwith open('output.pdf', 'wb+') as f:f.write(data)
Note: The _preload_content = false
parameter is used to tell Python not to parse the body of the response as text.