0

I am using Django-Rest-Framework for my API. And I am documenting that API w/ swagger using drf_yasg. One of my views returns a Django FileResponse.

When I access the view directly at "http://localhost:8000/api/my_documents/1" it successfully displays the (PDF) file. But when I access it via swagger it successfully returns a 200 but gives the following message:

Unrecognized response type; displaying content as text.

This is b/c of this issue in swagger itself. As suggested in that ticket, the problem goes away if I change the "Content-Disposition" response header from "inline" to "attachment". However, I don't want to always download the file.

My question is: Can I determine whether the request was made by swagger in the view and conditionally change the headers? Something like:

class MyDocumentView(GenericAPIVIew):

  def get(self, request, pk):
    my_document = MyDocument.objects.get(pk=pk)
    response = FileResponse(my_document.file)  # (file is a FileField)

    # WHAT DO I PUT HERE ?!?
    if request.is_from_swagger:
      response.headers["Content-Disposition"] = response.headers["Content-Disposition"].replace("inline", "attachment")

    return response

Thanks.

trubliphone
  • 4,132
  • 3
  • 42
  • 66

1 Answers1

1

You can do this by checking the request.headers.get('referer'). There should be your swagger url in there.

Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13