# Filtering Tutorial
source: https://developer.mastercard.com/bin-lookup/documentation/tutorials-and-guides/filtering-tutorial/index.md

## Overview {#overview}

This tutorial walks through how to *filter* the results from the paginated endpoint. This is useful when you have specific needs from the data and don't require the full data set. For example, you may only want records that include a specific country, issuer, or product code. At the end of this tutorial you will have a Python script that will demonstrate basic filtering.

### 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 [Python documentation](https://www.python.org/doc/).
Tip: If you have followed any of the other BIN Lookup tutorials in this section, you can skip steps 1 and 2 because they are the same for every tutorial. If you want to get straight to the code, all example files are available on [Github](https://github.com/Mastercard-Samples/bin-lookup-sample-code)

## 1. Create the File \& Download Dependencies {#1-create-the-file--download-dependencies}

First, we need to ensure to have the dependencies needed for our code. We install the `mastercard-oauth1-signer` and `requests` packages via the following command line:

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

Next, create a file called `filtering-example.py` and add the following imports at the top of the file:

```python
import requests
from requests.auth import AuthBase
import oauth1.authenticationutils as authenticationutils
from oauth1.signer import OAuthSigner
import csv
```

## 2. Configuring Authentication {#2-configuring-authentication}

Next, create some variables to hold the base URL, which is the url for the API we will be calling, and for your consumer key. You can get your consumer key from your project in the projects dashboard.

```python
BASE_URL = 'Add Sandbox or Production BASE URL here'
CONSUMER_KEY = 'Add your project consumer key here' 
```

Following that, use the this code to create a simple class that will sign all HTTP requests we send using the Python requests library:

```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
```

Finally, use the Mastercard OAuth library to create a signing key using the .p12 cert that you downloaded when you created your project, and the keystore password that you set:

```python
# Generate a signing key and use it, and consumer key, with the signer class
signing_key = authenticationutils.load_signing_key('./certs/sandbox.p12', 'keystorepassword')
signer = MCSigner(CONSUMER_KEY, signing_key)
```

## 3. Filtering {#3-filtering}

Tip: This example shows how you can use fuzzy matching on the customerName key to match on values that aren't exact. For example, using 'CITI' as the value to filter on will return any customer names that contain 'CITI'. It is important to know that this only works for the customerName filter, and filtering on all other values must be **exact** matches.

To filter on the paginated endpoint we create an array of key/value pairs and store it in a variable called `filters`:

```python
filters = [
    {
        "key": "customerName",
        "value": "CITIBANK"
    },
    {
        "key": "productCode",
        "value": "MCO"
    }
]
```

Then, all we have to do is pass the `filter` variable to our requests POST. The printed line will tell you how many matching items were found, if you want to see the full returned response you can instead print `resp.json()`.

```python
resp = requests.post(
        f'{BASE_URL}/bin-ranges',
        auth=signer,
        json = filters
    )

print (f"There are {resp.json()['totalItems']} items that match")
```

This endpoint uses pagination, so check the `totalItems` and `currentPageSize` values in the response metadata to ensure you receive all results for your filtered search:

```json
{
    "currentPageNumber": 1,
    "currentPageSize": 25,
    "totalPages": 1,
    "totalItems": 210,
    "items": [
        {
            "lowAccountRange": 5082460000000000000,
            "highAccountRange": 5082469999999999999,
            "binNum": "508246",
            "binLength": 6,
            "acceptanceBrand": "MSI",
            "ica": "00000017551",
            "customerName": "CITIBANK N.A.",
            "country": {
                "code": 360,
                "alpha3": "IDN",
                "name": "Indonesia"
            },
            "localUse": false,
            "authorizationOnly": false,
            "productCode": "MSI",
            "productDescription": "MAESTRO",
            "governmentRange": false,
            "nonReloadableIndicator": false,
            "anonymousPrepaidIndicator": "N",
            "programName": null,
            "vertical": null,
            "fundingSource": "DEBIT",
            "consumerType": "CONSUMER",
            "smartDataEnabled": true,
            "affiliate": "North Community Credit Union"
        }
        ...
    ]
}
```

To better understand how pagination works, check out the [pagination tutorial](https://developer.mastercard.com/bin-lookup/documentation/tutorials-and-guides/pagination-tutorial/index.md).

## Code {#code}

Here is the full Python source code:

```python
import requests
from requests.auth import AuthBase
import oauth1.authenticationutils as authenticationutils
from oauth1.signer import OAuthSigner
import csv

BASE_URL = 'Add Sandbox or Production BASE URL here'
CONSUMER_KEY = 'Add you project consumer key here' 

# 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

# Generate a signing key and use it, and consumer key, with the signer class
signing_key = authenticationutils.load_signing_key('./certs/sandbox.p12', 'keystorepassword')
signer = MCSigner(CONSUMER_KEY, signing_key)

filters = [
    {
        "key": "customerName",
        "value": "CITIBANK"
    },
    {
        "key": "productCode",
        "value": "MCO"
    }
]

resp = requests.post(
        f'{BASE_URL}/bin-ranges',
        auth=signer,
        json = filters
    )

print (f"There are {resp.json()['totalItems']} items that match")
```

