I have a Django app that lets a user upload a file and does some processing on it, and I need to write an API for this app. The requirements are:
- The API must accept file uploads (this is really the only thing the API will be responsible for)
- User authentication must be supported, meaning each file uploaded must be associated with an existing Django user
I wrote the first part quite easily by just telling Django to listen for POST’ed data on a specific URL (which I hit by passing a file to curl), but that obviously won’t give me user auth.
How can I add that in? Should I try something like tastypie since it’s for building API’s and has support for user auth, even though I will only barely scratch the surface of its functionality with this basic API? Or could I just get away with telling Django to accept a username and password in the POST along with the file? Is there a best practice for authenticating a user through an API built on top of Django?
My take on this would be to simply use the
django.contrib.authapplication and before handling the actual file data in the POST request just verify that the POST request also contains valid authentication info. You can do that by calling theauthenticatefunction, see https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticateThe above applies in case you want the whole process to happen in a single request. That, however, means that the whole file will be uploaded before checking the authentication info. If you can afford to split this into one auth request followed by a file upload, you can just create a view that will take care of the authentication and then protect your file upload view by the
login_requireddecorator. This will require sessions…