Created
July 8, 2022 05:55
-
-
Save Olgoetz/8a7f3acfb647d345558ce50f9f8a277e to your computer and use it in GitHub Desktop.
Example with Terraform Enterprise API how to use json pagination with python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Envs | |
TFE_TOKEN = os.environ['TFE_TOKEN'] | |
TFE_API_ENDPOINT_BASE = os.environ['TFE_API_ENDPOINT_BASE'] | |
# Set request header for authentication | |
HEADERS = { 'Authorization' : 'Bearer ' + TFE_TOKEN } | |
# Switch for ssl | |
VERIFY = False | |
def get_workspaces_from_orga(org_name): | |
""" | |
This function returns workspaces from a specific organization | |
Args: | |
organization name | |
Returns: | |
(list(dict)) containing dicts with the workspace id and workspace name | |
""" | |
# Set the page size | |
page_size = 50 | |
## 1. Init call to the endpoint to get the next_page | |
response = requests.get(f'{TFE_API_ENDPOINT_BASE}/organizations/{org_name}/workspaces', headers=HEADERS,verify=VERIFY, params={"page[size]": page_size}).json() | |
data= response["data"] | |
# Get the next_page | |
next_page = response["meta"]["pagination"]["next-page"] | |
## 2. Paginate until no next page is available | |
while next_page: | |
response = requests.get(f'{TFE_API_ENDPOINT_BASE}/organizations/{org_name}/workspaces', headers=HEADERS,verify=VERIFY, params={"page[size]": page_size,"page[number]": next_page}).json() | |
data = data + response["data"] | |
next_page = response["meta"]["pagination"]["next-page"] | |
print(f"Next page is: {next_page}") | |
return data | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment