erick.chali
erick.chali

Reputation: 686

Django middleware for consuming an external api

Here's the deal, I need to consume an API and every time I perform a request a header needs to be appended, I've checked the middleware documentation but this is only working for incoming requests, is there anything that can be used in this situation.

Upvotes: 0

Views: 605

Answers (1)

user4691348
user4691348

Reputation:

As discussed in comments:

class ServiceAPIClient(object):

    def __init__(self):
        self.base_url = "http://example.com/api"
        self.custom_header = "custom: header example"

    def consume_endpoint(self, endpoint):
        return requests.get(self.base_url+endpoint, headers=self.custom_header)

And then use it inside your views/models like:

response = ServiceAPIClient().consume_endpoint("/endpoint")

Take in mind that this is a silly example...

Upvotes: 2

Related Questions