Marco
Marco

Reputation: 81

Django - request to API in the same project

I have 2 apps in my project. One of them contains the API. The second app sends a request.

class PlayLongView(TemplateView):
    template_name = 'play/homepage.html'

    def get_price_info(self):
        url = reverse('myAPI:play_data')
        return requests.get(url).json()

    def get_context_data(self, **kwargs):
        context = super().get_context_data()

        data = self.get_price_info()
        context['price'] = data[0]['price']
        return context

It gives me a mistake:

Invalid URL '/myAPI/play_data': No schema supplied. Perhaps you meant http:///myAPI/play_data?

Of course I can replace:

url = reverse('myAPI:play_data')

with a:

url = 'http://localhost:8000/myAPI/play_data'

and then it works correctly, but my code is "local".
How should I write it so that the code also works after host on the server?

Upvotes: 0

Views: 1704

Answers (1)

Todor
Todor

Reputation: 16050

You can use HttpRequest.build_absolute_uri to build the absolute url. Something like:

    def get_price_info(self):
        url = self.request.build_absolute_uri(reverse('myAPI:play_data'))
        return requests.get(url).json()

But if you really have two apps in the same project, they should not talk to each other via API's, this is too much overhead for the request. You should have internal methods (services) that execute your business logic and gets reused between apps, views, API's, ... etc.

Upvotes: 2

Related Questions