> 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/readme/using-the-2050-materials-api/sdks/code-examples.md).

# Code Examples

Below are some examples of queries in Javascipt and Python. For more code samples, please look at the [SDKs](/readme/using-the-2050-materials-api/sdks.md)

## Get API token from Developer token

### Javascript

{% code overflow="wrap" %}

```javascript
const axios = require('axios');
async function fetchData() {
    try {
      const response = await axios.get('https://app.2050-materials.come/developer/api/getapitoken', {
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_TOKEN',
        },
        mode: 'no-cors'
      });
      console.log(response.data);
    } catch (error) {
      console.error('Error fetching data: ', error);
    }
  }
  
  fetchData();
```

{% endcode %}

### Python

{% code overflow="wrap" %}

```python
import requests

url = "https://app.2050-materials.com/developer/api/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

### Step 1: Render filters and create dictionaries for filtering

{% code 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['name']] = i['id']

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

{% endcode %}

## Limited data: /get\_products\_open\_api

{% code 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_type['Building boards (Multiple functions)']

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

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

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

print(response.text)

```

{% endcode %}

## Expanded data: /get\_products

{% code 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 from Canada (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&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

{% code 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

{% code 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.

#### Step 1: Obtain Bearer Token

{% code overflow="wrap" %}

```python
import requests

url = "https://app.2050-materials.com/developer/api/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['api_token']
```

{% endcode %}

#### Step 2: Get Filters and Create Dictionaries for Product Types, Material Types, and Certificate Types

{% code overflow="wrap" %}

```python
codebase_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['name']: i['id'] for i in filters['product_type']['filter_options']}
    material_types = {i['name']: i['id'] for i in filters['material_types']['filter_options']}
    certificate_type = {i['name']: 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

{% code overflow="wrap" %}

```python
codeimport pandas as pd

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

# Constructing the URL with query parameters
products_url = f"{base_api_url}developer/api/get_products?group_by=company_name&certificate_type={selected_certificate_type}&product_type={selected_product_type}&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)
except requests.RequestException as e:
    raise Exception(f"Failed to retrieve products data: {e}")

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

{% endcode %}

#### Notes:

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.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.2050-materials.com/readme/using-the-2050-materials-api/sdks/code-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
