3

i wanna get my data from an external API (https://example.com/consumers). Can I build my urls.py like this?

url(r'^(?P<test.com/consumers)>[0-9]+)$/', views.get, name="get"),

Or do you have any other(s) good idea(s) ?

Thanks.

2 Answers 2

14

I think it would be better to create your own url endpoint that maps to a view which makes a request to the external API.

# urls.py
url(r'^external-api/$', external_api_view)

# views.py
import requests
import time
from rest_framework import status
from rest_framework.response import Response

MAX_RETRIES = 5  # Arbitrary number of times we want to try

def external_api_view(request):
    if request.method == "GET":
        attempt_num = 0  # keep track of how many times we've retried
        while attempt_num < MAX_RETRIES:
            r = requests.get("https://example.com/consumers", timeout=10)
            if r.status_code == 200:
                data = r.json()
                return Response(data, status=status.HTTP_200_OK)
            else:
                attempt_num += 1
                # You can probably use a logger to log the error here
                time.sleep(5)  # Wait for 5 seconds before re-trying
        return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

Just an example. You can do it as a class-based view as well.

Sign up to request clarification or add additional context in comments.

3 Comments

You should set timeout limit for external API call, or your view may block the other incoming requests for minutes.
Thanks @ToanNguyen for pointing that out, I added a timeout and included maximum number of retries
Thanks @ThomasJiang , i will try it like that, and after i'll implement the class-based view. Thanks all
0

Whatever you are trying to achieve, this code will not work.

Firstly, ?P<name> construct is just a way to give a symbolic name to a group. And it does not accept characters '.', '/' and ')'. So correct name would be something like ?P<consumer_id>.

Secondly, even after you correct mistakes in the regular expression (like this, for example r'^(?P<consumer_id>[0-9]+$)/'), it will just match any URL like YOURDOMAIN.COM/<integer_number>/.

I suggest you learn how regular expressions work in Python first.

1 Comment

where to give username and password to connect with the external API?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.