> For the complete documentation index, see [llms.txt](https://docs.2050-materials.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.2050-materials.com/using-the-2050-materials-api/sdks/code-examples.md).

# Code Examples

Examples of requests using our API endpoints

Below are some examples of queries in JavaScript and Python.

## Get API token from Developer token <a href="#get-api-token-from-developer-token" id="get-api-token-from-developer-token"></a>

### Javascript <a href="#javascript" id="javascript"></a>

{% code title="Get an API token (JavaScript)" overflow="wrap" %}

```javascript
const axios = require('axios');
async function fetchData() {
    try {
      const response = await axios.get('https://app.2050-materials.com/developer/api/token/getapitoken/', {
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_DEVELOPER_TOKEN',
        },
      });
      console.log(response.data);
    } catch (error) {
      console.error('Error fetching data: ', error);
    }
  }
  
  fetchData();
```

{% endcode %}

### Python <a href="#python" id="python"></a>

{% code title="Get an API token (Python)" overflow="wrap" %}

```python
import requests

url = "https://app.2050-materials.com/developer/api/token/getapitoken/"

payload = {}
headers = {
  'Authorization': 'Bearer {{Developer Token from https://app.2050-materials.com/accounts/edit-account/}}'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
```

{% endcode %}

## Get building board products with an EPD <a href="#get-building-board-products-with-an-epd" id="get-building-board-products-with-an-epd"></a>

### Step 1: Render filters and create dictionaries for filtering <a href="#step-1-render-filters-and-create-dictionaries-for-filtering" id="step-1-render-filters-and-create-dictionaries-for-filtering"></a>

{% code title="Step 1: get filters and build lookup dictionaries" overflow="wrap" %}

```python
# This code filters for product types and material types 

import requests

base_api_url = 'https://app.2050-materials.com/'
get_filters_url = f'{base_api_url}developer/api/get_product_filters/'

headers = {
    'Authorization': f'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json',
}

try:
    response = requests.get(get_filters_url, headers=headers)
    response.raise_for_status()
    filters = response.json()
except requests.RequestException as e:
    raise Exception(f"Failed call to get_products API: {e}")
    
product_types = {}
for i in filters['product_type']['filter_options']:
    product_types[i['value']] = i['id']

material_types = {}
for i in filters['material_type']['filter_options']:
    material_types[i['value']] = i['id']
    
certificate_type = {}
for i in filters['certificate_type']['filter_options']:
    certificate_type[i['value']] = i['id']
```

{% endcode %}

{% hint style="info" %}
Each entry in a section's `filter_options` has `value`, the option's name, and `id`. The examples map each `value` to its `id` and filter by `id`. The `epd_operator`, `compliances`, `lca_database`, `lca_tool` and `verification_type` sections have `value` only, with no `id`. With `include_counts=true`, each entry also has `count`.
{% endhint %}

## Limited data: /get\_products\_open\_api <a href="#limited-data-get_products_open_api" id="limited-data-get_products_open_api"></a>

{% code title="get\_products\_open\_api: building boards with an EPD" overflow="wrap" %}

```python
# This code gets building boards (product_type.id = 5), with an EPD (certificate_type.id=1) and groups then by company_name
import requests

url = "https://app.2050-materials.com/developer/api/get_products_open_api?group_by=company_name&certificate_type=1&product_type=5"

#The above code could also replace the filters in this way:
#certificate_type_selected = certificate_type['EPD']
#product_type_selected = product_types['Building boards (Multiple functions)']

#url = f"https://app.2050-materials.com/developer/api/get_products_open_api?group_by=company_name&certificate_type={certificate_type_selected}&product_type={product_type_selected}"

payload = {}
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

```

{% endcode %}

## Expanded data: /get\_products <a href="#expanded-data-get_products" id="expanded-data-get_products"></a>

{% code title="get\_products: building boards with an EPD, made in Canada" overflow="wrap" %}

```python
# This code gets building boards (product_type.id = 5), with an EPD (certificate_type.id=1) and groups then by company_name
# Additionally, this filters to products manufactured in Canada (manufacturing_country=Canada) only.

import requests

url = "https://app.2050-materials.com/developer/api/get_products?group_by=company_name&certificate_type=1&product_type=5&manufacturing_country=Canada"


payload = {}
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
```

{% endcode %}

### Generic Data: /get\_generic\_materials <a href="#generic-data-get_generic_materials" id="generic-data-get_generic_materials"></a>

{% code title="get\_generic\_materials: building boards" overflow="wrap" %}

```python
# This code gets building boards from the generic data (product_type.id = 5)

import requests

url = "https://app.2050-materials.com/developer/api/get_generic_materials?product_types=5"

payload = {}
files={}
headers = {'Authorization': 'Bearer YOUR_API_TOKEN'}

response = requests.request("GET", url, headers=headers, data=payload, files=files)

print(response.text)

```

{% endcode %}

## Retrieve Warming Potential and EC for a High-Rise Residential building /get\_co2\_warming\_potential <a href="#retrieve-warming-potential-and-ec-for-a-high-rise-residential-building-get_co2_warming_potential" id="retrieve-warming-potential-and-ec-for-a-high-rise-residential-building-get_co2_warming_potential"></a>

{% code title="get\_co2\_warming\_potential: high-rise residential building" overflow="wrap" %}

```python
import requests

url = "https://app.2050-materials.com/developer/api/get_co2_warming_potential?building_type=Residential, High-rise&gross_internal_floor_area=1000&glazing_percentage=30&materials_type=High-carbon (Metal, Concrete)&stories=3"

payload = {}
headers = {
  'Authorization': 'Bearer YOUR_API_TOKEN'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
```

{% endcode %}

## Flow to retrieve tokens, get filters, and render building boards with EPDs in Canada. <a href="#flow-to-retrieve-tokens-get-filters-and-render-building-boards-with-epds-in-canada" id="flow-to-retrieve-tokens-get-filters-and-render-building-boards-with-epds-in-canada"></a>

#### Step 1: Obtain Bearer Token <a href="#step-1-obtain-bearer-token" id="step-1-obtain-bearer-token"></a>

{% code title="Step 1: get an API token" overflow="wrap" %}

```python
import requests

url = "https://app.2050-materials.com/developer/api/token/getapitoken/"

payload = {}
headers = {
  'Authorization': 'Bearer {{Developer Token from https://app.2050-materials.com/accounts/edit-account/}}'
}

response = requests.request("GET", url, headers=headers, data=payload)
bearer_token = response.json()['api_token']
```

{% endcode %}

#### Step 2: Get Filters and Create Dictionaries for Product Types, Material Types, and Certificate Types <a href="#step-2-get-filters-and-create-dictionaries-for-product-types-material-types-and-certificate-types" id="step-2-get-filters-and-create-dictionaries-for-product-types-material-types-and-certificate-types"></a>

{% code title="Step 2: get filters and build lookup dictionaries" overflow="wrap" %}

```python
base_api_url = 'https://app.2050-materials.com/'
get_filters_url = f'{base_api_url}developer/api/get_product_filters/'

# Update headers with the obtained bearer token
headers = {
    'Authorization': f'Bearer {bearer_token}',
    'Content-Type': 'application/json',
}

try:
    # Request to get product filters
    filters_response = requests.get(get_filters_url, headers=headers)
    filters_response.raise_for_status()
    filters = filters_response.json()

    # Parsing and storing filters in dictionaries
    product_types = {i['value']: i['id'] for i in filters['product_type']['filter_options']}
    material_types = {i['value']: i['id'] for i in filters['material_type']['filter_options']}
    certificate_type = {i['value']: i['id'] for i in filters['certificate_type']['filter_options']}
except requests.RequestException as e:
    raise Exception(f"Failed to retrieve product filters: {e}")
```

{% endcode %}

#### Step 3: Use Filters to Call `get_products` API and Create DataFrame <a href="#step-3-use-filters-to-call-get_products-api-and-create-dataframe" id="step-3-use-filters-to-call-get_products-api-and-create-dataframe"></a>

{% code title="Step 3: call get\_products and build a DataFrame" overflow="wrap" %}

```python
import pandas as pd

# Define your filters here
certificate_type_selected = certificate_type['EPD']
product_type_selected = product_types['Building boards (Multiple functions)']
selected_country = 'Canada'

# Constructing the URL with query parameters
products_url = f"{base_api_url}developer/api/get_products?certificate_type={certificate_type_selected}&product_type={product_type_selected}&manufacturing_country={selected_country}"

try:
    # Request to get products data
    products_response = requests.get(products_url, headers=headers)
    products_response.raise_for_status()
    products_data = products_response.json()

    # Creating a DataFrame from the response
    products_df = pd.DataFrame(products_data['results'])
except requests.RequestException as e:
    raise Exception(f"Failed to retrieve products data: {e}")

# Optional: Display the DataFrame
print(products_df.head())
```

{% endcode %}

#### Notes: <a href="#notes" id="notes"></a>

1. **Error Handling:** The code includes try-except blocks to handle potential request errors.
2. **Bearer Token**: Ensure to replace `{{Developer Token}}` with your actual developer token.
3. **Filters**: The code dynamically creates dictionaries for different filter types based on the response from the `get_product_filters` endpoint.
4. **DataFrame Creation**: The final step converts the product data into a pandas DataFrame for easy manipulation and analysis.
