Search code examples
pythonpython-requestskeyword-argument

TypeError: 'data' is an invalid keyword argument for this function


I'm trying to modify the function request to take different arguments depending on the api call. For example: in post_categories, I need it to send a third parameter data that includes the body that I want to post, but the get_categories function doesn't need a third parameter. I added **kwargs to the request function but this is the error that I'm getting: TypeError: 'data' is an invalid keyword argument for this function

class ApiGateway():
    base_url = 'https://api.com/v3/'

    def request(self, method, endpoint, **kwargs):
        url = f'{self.base_url}{endpoint}'
        kwargs.setdefault('headers', {})
        kwargs['headers'].update({
            'Authorization': f'Bearer ${self.token}',
            'Accept': 'application/json',
        })
        response = requests.request(method, url, **kwargs)
        return response.json()

    def get_categories(self, merchant_id):
        endpoint = f'merchants/{merchant_id}/categories'
        return self.request('GET', endpoint)

    def post_categories(self, merchant_id):
        update = {
            'payment_method': {
                'token': 1234,
                'data': '123556'
            }
        }    
        endpoint = f'merchants/{merchant_id}/categories'
        return self.request('POST', endpoint, data=json.dumps(update)) 

Solution

  • i found the solution. i had to specify the type of data i wanted to pass to the request function instead of passing the data as a kwargs parameter. i just updated this part of the post_categories function return self.request('POST', endpoint, data=json.dumps(update)) so now the function looks like this

       def post_categories(self, merchant_id):
            update = {
                'payment_method': {
                    'token': 1234,
                    'data': '123556'
                }
            }    
            endpoint = f'merchants/{merchant_id}/categories'
       
            return self.request('POST', endpoint, json=update) # <-- updated third parameter