Using the Looker API to generate PDFs

Update: This article is now out of date. For the latest info on how to render and download a dashboard’s PDF using the Looker API, please see our Looker SDK Examples repo on Github.


Downloading a PDF version of your dashboard is great and is very easy to do 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 looker

base_url = 'https://learn.looker.com:19999/api/3.0'
client_id = ''
client_secret = ''

# instantiate Auth API
unauthenticated_client = looker.ApiClient(base_url)
unauthenticated_authApi = looker.ApiAuthApi(unauthenticated=_client)

# authenticate client
token = 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 the dashboard_filters, which is a string and expects the filters in query URL format. e.g.: "My Filter=New York&My Other Filter=Brooklyn".

# instantiate render task API
renderTask = looker.RenderTaskApi(api_client=client)

height = 842
width = 595
output_format  = 'pdf'
dashboard_id = 241
body = {
         "dashboard_style": "tiled",
         "dashboard_filters": {
            "Created Date=12 months ago for 12 months"
         }
       }

# fire a render task and get its ID
task_response = renderTask.create_dashboard_render_task(dashboard_id, output_format, body, width, height)
task_id = task_response.id

###Step 3:
Use the render_task(id) endpoint to confirm the the render task has finished. Consequently, we can get the produced document using the render_task_results endpoint as follows:

# get the produced results
results = renderTask.render_task_results(task_id, _preload_content = False)
data = results.data

# write it to PDF
with open('output.pdf', 'wb+') as f:
    f.write(data)

PS: the _preload_content = false parameter is used to tell Python not to parse the body of the response as text.

10 13 5,720