Reputation: 141
I am trying to interact with the SWAPI API.
I want a view that fetches all the movies(films/
) and one that fetches one (film/id
).
When I hit http://127.0.0.1:8000/api/films/?id=4
it enters the get_films
function.
I am using Django==1.11 and Django Rest Framework==3.9.0 .
my urs.py:
urlpatterns = [
url(r'films/',views.get_films,name="get-films"),
url(r'films/(?P<id>[0-9])/',views.get_film,name="get-film"),
]
my views.py:
MAX_RETRIES = 5
API_URL= "https://swapi.co/api/"
@api_view(['GET', 'POST'])
def get_films(request):
request_url = API_URL + "films"
print(request_url)
if request.method == "GET":
attempt_num = 0 # keep track of how many times we've retried
while attempt_num < MAX_RETRIES:
r = requests.get(request_url, 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)
@api_view(['GET', 'POST'])
def get_film(self, request):
print('entered')
request_url = API_URL + "films/" + request.query_params.get('id')
if request.method == "GET":
attempt_num = 0 # keep track of how many times we've retried
while attempt_num < MAX_RETRIES:
r = requests.get(request_url, 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)
Upvotes: 1
Views: 747
Reputation: 51938
There are 2 things wrong with your implementation. First, get_film
. the arguments are wrong in this method. you need to define it like this:
@api_view(['GET', 'POST'])
def get_film(request, id): # <-- First argument is request which is for `HttpRequest` object. Second is `id` which is for mapping it with the url's id.
print('entered')
request_url = API_URL + "films/" + str(id)
# rest of the code
Second, when calling this api, you need to do it like this: http://127.0.0.1:8000/api/films/4/
Upvotes: 2
Reputation: 4189
The order in urlpatterns
matter. Try changing the order of your urls. It probably matches the first one and doesn't reach the second one.
Upvotes: 0