python – I keep getting ; trouble connecting django to plaid api

I’m trying to connect my Django backend to Plaid’s API but I’ve been stuck on how to only return the body from the Object.

This is the traceback I’m getting:

Request Method: GET
Request URL: http://127.0.0.1:8000/create-link-token

Django Version: 4.0.6
Python Version: 3.9.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:Python39libsite-packagesdjangocorehandlersexception.py", line 55, in inner
    response = get_response(request)
  File "C:Python39libsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersDaniel TshibanguDesktopmukadiplaid-integrationpythonbackendappviews.py", line 82, in create_link_token
    response = client.link_token_create(request)
  File "C:Python39libsite-packagesplaidapi_client.py", line 769, in __call__
    return self.callable(self, *args, **kwargs)
  File "C:Python39libsite-packagesplaidapiplaid_api.py", line 7404, in __link_token_create
    return self.call_with_http_info(**kwargs)
  File "C:Python39libsite-packagesplaidapi_client.py", line 831, in call_with_http_info
    return self.api_client.call_api(
  File "C:Python39libsite-packagesplaidapi_client.py", line 406, in call_api
    return self.__call_api(resource_path, method,
  File "C:Python39libsite-packagesplaidapi_client.py", line 193, in __call_api
    response_data = self.request(
  File "C:Python39libsite-packagesplaidapi_client.py", line 452, in request
    return self.rest_client.POST(url,
  File "C:Python39libsite-packagesplaidrest.py", line 264, in POST
    return self.request("POST", url,
  File "C:Python39libsite-packagesplaidrest.py", line 150, in request
    r = self.pool_manager.request(
  File "C:Python39libsite-packagesurllib3request.py", line 78, in request
    return self.request_encode_body(
  File "C:Python39libsite-packagesurllib3request.py", line 170, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "C:Python39libsite-packagesurllib3poolmanager.py", line 376, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "C:Python39libsite-packagesurllib3connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "C:Python39libsite-packagesurllib3connectionpool.py", line 398, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:Python39libsite-packagesurllib3connection.py", line 239, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "C:Python39libhttpclient.py", line 1255, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:Python39libhttpclient.py", line 1296, in _send_request
    self.putheader(hdr, value)
  File "C:Python39libsite-packagesurllib3connection.py", line 224, in putheader
    _HTTPConnection.putheader(self, header, *values)
  File "C:Python39libhttpclient.py", line 1232, in putheader
    if _is_illegal_header_value(values[i]):

Exception Type: TypeError at /create-link-token
Exception Value: expected string or bytes-like object

From what I can tell, after checking my configuration, it’s attempting to request the link token and other info from plaid servers, but it’s failing to do so.

callback            <function create_link_token at 0x000002283648B5E0>
callback_args       ()
callback_kwargs     {}
middleware_method   <bound method CsrfViewMiddleware.process_view of 
                    <CsrfViewMiddleware get_response=convert_exception_to_response. 
                    <locals>.inner>>

request             <WSGIRequest: GET '/create-link-token'>
response            None
self                <django.core.handlers.wsgi.WSGIHandler object at 
                    0x0000022834FF1040>
wrapped_callback    <function create_link_token at 0x000002283648B5E0>

So far, I’ve looked through the documentation and google searches to figure out if others had gone through similar issues too. Found nothing helpful towards my situation at least. Since this error is coming from django’s core exceptions, I tried finding ways to override that exception.

After focusing in on my problem, my question is now, “How can I return body to the request field when I can’t access requests?” Might be wrong, but I’m under the impression that I don’t have a way to tamper with requests, that’ll that me manipulate the data it receives.

This is my code:

views.py

PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
PLAID_PUBLIC_KEY = os.getenv('PLAID_PUBLIC_KEY') 
PLAID_SECRET = os.getenv('PLAID_SECRET')
PLAID_ENVIRONMENT = os.getenv('PLAID_ENV', 'development')


configuration = plaid.Configuration(
    host=plaid.Environment.Development,
    api_key = {
        'clientId': PLAID_CLIENT_ID, 
        'secret': PLAID_SECRET,
        'plaidVersion': '2020-09-14',
    }
)

api_client = plaid.ApiClient(configuration)
client = plaid_api.PlaidApi(api_client)

# We store the access_token in memory - in production, store it in a secure
# persistent data store.
access_token = None
# The payment_id is only relevant for the UK Payment Initiation product.
# We store the payment_id in memory - in production, store it in a secure
# persistent data store.
payment_id = None
# The transfer_id is only relevant for Transfer ACH product.
# We store the transfer_id in memomory - in produciton, store it in a secure
# persistent data store
transfer_id = None

item_id = None

def index(request):
    if request.method == 'GET': 
        return True


def create_link_token(request):
    try:
        # Get the client_user_id by searching for the current user
        # Create a link_token for the given user
        request = LinkTokenCreateRequest(
            products=[Products("auth")],
            client_name="Plaid Test App",
            country_codes=[CountryCode('US')],
            language="en",
            user=LinkTokenCreateRequestUser(
                client_user_id=str(time.time())
            )
        )

        response = client.link_token_create(request)
        link_token = response['link_token']
        # Send the data to the client
        return JsonResponse(link_token)
    except plaid.ApiException as e:
        return json.dumps(e.body)

and urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('create-link-token', views.create_link_token, name="create-link-token"),
]

If there’s anything more I can provide, please let me know.

Leave a Comment