Using the ButterflyMX API to Create Pin (with Python examples)

by Endgrate Team 2024-09-08 4 min read

ButterflyMX homepage

Introduction to ButterflyMX API

ButterflyMX is a cutting-edge property access solution that simplifies building entry for residents, visitors, and property staff. With its innovative technology, ButterflyMX offers features such as video intercom, virtual keys, and access management, making it a preferred choice for modern residential and commercial buildings.

Integrating with the ButterflyMX API allows developers to enhance property management systems by automating access control processes. For example, you can create and manage tenant PINs programmatically, streamlining the process of granting access to new residents or updating existing credentials.

Setting Up Your ButterflyMX Sandbox Account for API Integration

Before you can start integrating with the ButterflyMX API, it's essential to set up a sandbox account. This environment allows you to test API interactions without affecting live data. Unfortunately, creating a sandbox account isn't as straightforward as signing up online. You'll need to contact ButterflyMX directly to request access to a sandbox environment.

Contacting ButterflyMX for Sandbox Access

To obtain a sandbox account, reach out to ButterflyMX support through their official contact channels. Provide details about your project and request access to their sandbox environment. This step is crucial for ensuring you have a safe space to test your API integrations.

Creating a ButterflyMX App for OAuth2 Authentication

Once you have access to the sandbox, you need to create an app to use OAuth2 authentication. Follow these steps to set up your app:

  1. Log in to your ButterflyMX sandbox account.
  2. Navigate to the app creation section under the developer settings.
  3. Click on "Create New App" and fill in the required details, such as app name and description.
  4. Set the redirect URI to https://usersandbox.butterflymx.com/oauth/callbacks/butterflymx.
  5. Save your app to generate the CLIENT_ID and CLIENT_SECRET.

Obtaining OAuth2 Authorization Code

To begin the OAuth2 flow, construct a URL to obtain an authorization code:

https://accountssandbox.butterflymx.com/oauth/authorize?client_id=$CLIENT_ID&redirect_uri=https://usersandbox.butterflymx.com/oauth/callbacks/butterflymx&response_type=code&client_secret=$CLIENT_SECRET

Open this URL in a browser and follow the prompts to authorize your app. You'll receive an authorization code in the redirect URI.

Exchanging Authorization Code for Access Token

Use the authorization code to obtain an access token by sending a POST request to the token endpoint:

curl --location --request POST 'https://accountssandbox.butterflymx.com/oauth/token' \
--form 'grant_type=authorization_code' \
--form 'code=$code' \
--form 'client_id=$CLIENT_ID' \
--form 'client_secret=$CLIENT_SECRET' \
--form 'redirect_uri=https://usersandbox.butterflymx.com/oauth/callbacks/butterflymx'

Upon success, you'll receive an access_token and refresh_token to authenticate your API requests.

For more detailed information, refer to the ButterflyMX API documentation.

ButterflyMX authentication documentation page.
sbb-itb-96038d7

Making API Calls to ButterflyMX Using Python

To interact with the ButterflyMX API and create tenant PINs, you'll need to use Python. This section will guide you through the process of setting up your environment, making API calls, and handling responses effectively.

Setting Up Your Python Environment for ButterflyMX API Integration

Before making API calls, ensure you have Python 3.11.1 installed on your machine. You will also need the requests library to handle HTTP requests. Install it using the following command:

pip install requests

Creating a PIN for a Tenant Using ButterflyMX API

To create a PIN for a tenant, you'll need to make a POST request to the ButterflyMX API. Below is a Python script example to achieve this:

import requests

# Define the API endpoint and headers
url = "https://apisandbox.butterflymx.com/v3/pins"
headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/vnd.api+json"
}

# Define the payload with tenant ID and PIN code
payload = {
    "data": {
        "type": "pins",
        "attributes": {
            "id": "TENANT_ID",
            "code": "1234"  # Ensure the code is numeric and 4 characters long
        }
    }
}

# Make the POST request to create a PIN
response = requests.post(url, json=payload, headers=headers)

# Check if the request was successful
if response.status_code == 204:
    print("PIN created successfully.")
else:
    print("Failed to create PIN:", response.json())

Replace YOUR_ACCESS_TOKEN with the access token obtained during the OAuth2 authentication process, and TENANT_ID with the actual tenant ID.

Verifying API Call Success and Handling Errors

After running the script, verify the success of the API call by checking the response status code. A status code of 204 indicates success. If the request fails, the response will contain error details. Common error codes include:

  • 400 Bad Request: The request was malformed. Check the payload for errors.
  • 401 Unauthorized: The access token is invalid or expired. Obtain a new token.

For more error codes and their meanings, refer to the ButterflyMX API documentation.

Conclusion and Best Practices for Using ButterflyMX API with Python

Integrating with the ButterflyMX API to manage tenant PINs can significantly enhance the efficiency of property management systems. By automating access control, you can streamline operations and improve the resident experience.

Best Practices for Securely Storing User Credentials

When handling sensitive information such as access tokens and client secrets, it's crucial to store them securely. Consider using environment variables or secure vault services to keep these credentials safe from unauthorized access.

Handling Rate Limiting and Optimizing API Requests

To ensure smooth API interactions, be mindful of rate limits imposed by ButterflyMX. Optimize your requests by batching operations where possible and implementing exponential backoff strategies for retries. For specific rate limit details, refer to the ButterflyMX API documentation.

Data Transformation and Standardization

When working with API data, ensure that you transform and standardize data fields to match your application's requirements. This practice helps maintain consistency and improves data integrity across systems.

Leverage Endgrate for Simplified Integration Management

For developers looking to streamline the integration process further, consider using Endgrate. With Endgrate, you can save time and resources by outsourcing integrations, allowing you to focus on your core product. Endgrate provides a unified API endpoint that connects to multiple platforms, including ButterflyMX, offering an intuitive integration experience for your customers.

Explore more about how Endgrate can enhance your integration strategy by visiting Endgrate.

Read More

Ready to get started?

Book a demo now

Book Demo