# Quick Start Guide
source: https://developer.mastercard.com/bin-lookup/documentation/quick-start-guide/index.md

###### Time to complete: \*10 minutes\*

## Introduction {#introduction}

The BIN Lookup service provides a set of APIs that let you consume Mastercard account range (BIN) data in a variety of ways, opening up the possibility for novel solutions in the card and issuer identification space.

In this quick start guide, you create a project for the service, learn about Mastercard's approach to authentication, and download a full set of data from the sandbox environment using Python.

### Prerequisites {#prerequisites}

For this tutorial you must ensure you have `Python` and `pip` installed on your system. If you don't already have Python installed, check out the [Getting Python guide](https://wiki.python.org/moin/BeginnersGuide).

## 1. Generate Your Credentials {#1-generate-your-credentials}

As a first step, create a new Mastercard Developers project and Sandbox API credentials. These will give you access to our Sandbox which has mocked, rich, data, that will help you understand the data points the API provides, along with their structure.

1. Log in and click the **Create Project** button on the top right of this page.
2. Complete the **Project details** page. Ensure you select **BIN Lookup** from the **APIs** field.
3. On the **Project credentials** page, enter a name and password for a PKCS#12 keystore that Mastercard Developers generates for signing requests. Keep note of these values. Alternatively, if you have a a custom CSR, click **Skip this step**.
4. Download, and keep safe, your PKCS#12 (.p12) keystore file.
5. Once you complete this flow you will land on the project page. From this page, take note of your consumer key.

## 2. Authentication {#2-authentication}

Mastercard uses OAuth 1.0a for authenticating your application. You can manage your authentication keys from your [Developer Dashboard](https://developer.mastercard.com/dashboard) after you created a project using BIN Lookup service. Mastercard provides [client authentication libraries](https://github.com/Mastercard?q=oauth) in several languages you can integrate to your project or use as reference OAuth 1.0a implementations:

|                      |                                                     ![Java](https://static.developer.mastercard.com/content/bin-lookup/img/java.svg) **Java**                                                      |                                                    ![C#](https://static.developer.mastercard.com/content/bin-lookup/img/csharp.svg) **C#**                                                     |                            ![Python](https://static.developer.mastercard.com/content/bin-lookup/img/python.svg) **Python**                             |                             ![NodeJS](https://static.developer.mastercard.com/content/bin-lookup/img/nodejs.svg) **NodeJS**                             |                                      ![Go](https://static.developer.mastercard.com/content/bin-lookup/img/go.svg) **Go**                                      |
|----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Download/install** | [![](https://img.shields.io/maven-central/v/com.mastercard.developer/oauth1-signer.svg?style=flat&color=f99f1c&label=)](https://search.maven.org/artifact/com.mastercard.developer/oauth1-signer/) | [![](https://img.shields.io/nuget/v/Mastercard.Developer.OAuth1Signer.Core.svg?style=flat&color=f99f1c&label=)](https://www.nuget.org/packages/Mastercard.Developer.OAuth1Signer.RestSharpV2/) | [![](https://img.shields.io/pypi/v/mastercard-oauth1-signer.svg?style=flat&color=f99f1c&label=)](https://pypi.org/project/mastercard-oauth1-signer/)   | [![](https://img.shields.io/npm/v/mastercard-oauth1-signer.svg?style=flat&color=f99f1c&label=)](https://www.npmjs.com/package/mastercard-oauth1-signer) | [![](https://img.shields.io/github/v/release/mastercard/oauth1-signer-go.svg?style=flat&color=f99f1c&label=)](https://github.com/Mastercard/oauth1-signer-go) |
| **View on GitHub**   | [![](https://img.shields.io/github/stars/mastercard/oauth1-signer-java.svg?label=&style=social)](https://github.com/Mastercard/oauth1-signer-java)                                                 | [![](https://img.shields.io/github/stars/mastercard/oauth1-signer-csharp.svg?label=&style=social)](https://github.com/Mastercard/oauth1-signer-csharp)                                         | [![](https://img.shields.io/github/stars/mastercard/oauth1-signer-python.svg?label=&style=social)](https://github.com/Mastercard/oauth1-signer-python) | [![](https://img.shields.io/github/stars/mastercard/oauth1-signer-nodejs.svg?label=&style=social)](https://github.com/Mastercard/oauth1-signer-nodejs)  | [![](https://img.shields.io/github/stars/mastercard/oauth1-signer-go.svg?label=&style=social)](https://github.com/Mastercard/oauth1-signer-go)                |

In this quick start guide we are going to demonstrate using *Python* to get set up with the provided authentication library. For other languages you can follow the README files on Github.

Start by installing the `oauth signer` and the Python `requests` library using `pip`, via your command terminal:

```cli
pip install mastercard-oauth1-signer requests
```

Next, create a *Python* file, lets call it `binlookup.py`. Once the file is created add the following imports at the top:

```python
import requests
from requests.auth import AuthBase

import oauth1.authenticationutils as authenticationutils
from oauth1.signer import OAuthSigner
```

Next, we are going to create a helper class using AuthBase from the Requests library that will automatically sign all of the HTTP requests we send:

```python
# MCSigner
# Helper class for signing request objects
class MCSigner(AuthBase):
    def __init__(self, consumer_key, signing_key):
        self.signer = OAuthSigner(consumer_key, signing_key)

    def __call__(self, request):
        self.signer.sign_request(request.url, request)
        return request
```

Next, use the `load_signing_key` function to create a signing key from the .p12 file and your keystore password. Here is the code:

```python
signing_key = authenticationutils.load_signing_key('./path/to/projectname-sandbox.p12', 'keystorepassword')
```

Then, use the `MCSigner` helper class to create our HTTP request signer:

```python
base_url = 'Add Sandbox BASE URL here'
consumer_key = 'enter your consumer key here'
signer = MCSigner(consumer_key, signing_key)
```

At this stage we have everything we need to authenticate a request. In the next step we will demonstrate creating and calling a method to download all data from the paginated full download endpoint.

For a detailed overview of the OAuth 1.0a approach Mastercard uses, refer to [Using OAuth 1.0a to Access Mastercard APIs](https://developer.mastercard.com/platform/documentation/authentication/using-oauth-1a-to-access-mastercard-apis/).

## 3. Fetching All Account Ranges {#3-fetching-all-account-ranges}

We are now going to write the method that allows us to call the full download endpoint in a paginated manner to download the full set of account ranges and store them in an array. The code for this is as follows:

```python
def fetch_data_from_api(base_url, initial_page=1, post_payload={}, signer=None, data=None):
    all_items = []
    current_page = initial_page
    total_items_downloaded = 0
    total_items = None

    while True:

        # Update the payload to include the current page number for pagination
        post_payload.update({"page": current_page, 'size': '10000'})

        # Perform a POST request to the API
        response = requests.post(base_url, params=post_payload, auth=signer, json=data)
        response_data = response.json()
        
        # Extract metadata
        current_page_number = response_data['currentPageNumber']
        total_pages = response_data['totalPages']
        total_items = response_data['totalItems']
        
        # Extract the actual items
        items = response_data.get('items', [])
        
        # Add the items from the current page to the master list
        all_items.extend(items)
        
        # Update the total number of items downloaded
        total_items_downloaded += len(items)
        
        # Print the current progress for reference
        print(f"Downloaded {len(items)} items from page {current_page_number}/{total_pages}.")
        
        # Check if we have reached the last page
        if current_page_number >= total_pages:
            break
        
        # Move to the next page
        current_page += 1

    # After the loop, verify that the number of downloaded items matches the totalItems value
    if total_items_downloaded == total_items:
        print(f"Successfully downloaded all {total_items_downloaded} items.")
    else:
        print(f"Warning: Downloaded {total_items_downloaded} items, but expected {total_items} items.")
    
    return all_items
```

And to call this method we use the following code, once the download is complete you can then store the results in your persistent database:

```python
all_records = fetch_data_from_api(base_url=f'{BASE_URL}/bin-ranges', initial_page=1, post_payload={}, signer=signer)
```

Now you can run this file with the following command:

```cli
python binlookup.py
```

And that's all there is to it. You have now successfully called the BIN Lookup service.

Here is the whole file:

```python
import requests
from requests.auth import AuthBase

import oauth1.authenticationutils as authenticationutils
from oauth1.signer import OAuthSigner

# MCSigner
# Helper class for signing request objects
class MCSigner(AuthBase):
    def __init__(self, consumer_key, signing_key):
        self.signer = OAuthSigner(consumer_key, signing_key)

    def __call__(self, request):
        self.signer.sign_request(request.url, request)
        return request

signing_key = authenticationutils.load_signing_key('./path/to/projectname-sandbox.p12', 'keystorepassword')

base_url = 'Add Sandbox BASE URL here'
consumer_key = 'enter your consumer key here'
signer = MCSigner(CONSUMER_KEY, signing_key)

def fetch_data_from_api(base_url, initial_page=1, post_payload={}, signer=None, data=None):
    all_items = []
    current_page = initial_page
    total_items_downloaded = 0
    total_items = None

    while True:

        # Update the payload to include the current page number for pagination
        post_payload.update({"page": current_page, 'size': '10000'})

        # Perform a POST request to the API
        response = requests.post(base_url, params=post_payload, auth=signer, json=data)
        response_data = response.json()
        
        # Extract metadata
        current_page_number = response_data['currentPageNumber']
        total_pages = response_data['totalPages']
        total_items = response_data['totalItems']
        
        # Extract the actual items
        items = response_data.get('items', [])
        
        # Add the items from the current page to the master list
        all_items.extend(items)
        
        # Update the total number of items downloaded
        total_items_downloaded += len(items)
        
        # Print the current progress for reference
        print(f"Downloaded {len(items)} items from page {current_page_number}/{total_pages}.")
        
        # Check if we have reached the last page
        if current_page_number >= total_pages:
            break
        
        # Move to the next page
        current_page += 1

    # After the loop, verify that the number of downloaded items matches the totalItems value
    if total_items_downloaded == total_items:
        print(f"Successfully downloaded all {total_items_downloaded} items.")
    else:
        print(f"Warning: Downloaded {total_items_downloaded} items, but expected {total_items} items.")
    
    return all_items

all_records = fetch_data_from_api(base_url=f'{BASE_URL}/bin-ranges', initial_page=1, post_payload={}, signer=signer)
```

## 4. Next Steps {#4-next-steps}

To learn how to check a single BIN at a time, see the [single lookup documentation](https://developer.mastercard.com/bin-lookup/documentation/tutorials-and-guides/single-lookup/index.md). You might also like to review the [API specification](https://developer.mastercard.com/bin-lookup/documentation/api-section/api-reference/index.md) or review [data elements](https://developer.mastercard.com/bin-lookup/documentation/api-section/data-explanations/index.md) to understand what is available in our different tiers.
