Reputation: 119
I am writing an API for shortening URL and I have to return the following response.
request:
GET /:shorten_url
Content-Type: "application/json"
Expected Response:
302 response with the location header pointing to the shortened URL
HTTP/1.1 302 Found
Location: http://www.example.com # original url
I tried:
# shortcode is the shorten url of original url
def get(self, request, shortcode):
if shortcode:
try:
shortUrl = UrlShort.objects.get(shortcode=shortcode)
originalUrl = shortUrl.url
response = HttpResponse(status=status.HTTP_302_FOUND)
response['Location'] = shortUrl.url
return response
except UrlShort.DoesNotExist:
raise Http404()
Rather than getting 302 status code with location header, I'm redirected to the url
with status code 200. What is wrong in my code?
Upvotes: 0
Views: 360
Reputation: 4432
There is special class for "found" redirect you can use - HttpResponseRedirect redirect instead:
...
return HttpResponseRedirect(shortUrl.url)
Upvotes: 2