0

I'm new to django, i'm currently working with API using Django Ninja Rest Framework.
in this example, users will have a unique APIKey each time i create new APIKey from this model and attach it to selected user.

this is my APIKey model :

### NOTE - This is just for testing, Not a real model, see the link below

class APIKey(models.Model):
    key         = models.CharField(max_length=64) # i know this should be unique, just for demo :)
    user        = models.ForeignKey(get_user_model(), related_name='free_key', on_delete=models.CASCADE)
    label       = models.CharField(max_length=40)
    revoked     = models.BooleanField(default=False)
    created_at  = models.DateTimeField(auto_now_add=True)
    expires_at  = models.DateTimeField(null=True, blank=True)

This model is just for testing purposes, I actually use this for my project and modify it.

So, My API endpoints need an API key for authentication (the API key that i have created that correspond to a specific user),
then i implement and follow the steps here and it works normally

My questions are :

  1. Each user has a unique API key. How to count and store the total request from a user each time user makes a request to an endpoint ? Should i add request_total field to my APIKey model or create a new Model ? Should i use custom middleware? or should i use Redis or something? if so, how to implement it ?

  2. What's the best way for this scenario to implement a daily limit by the total request from a user ? for example, the user daily limit request is 100 requests, and reset every 00:01AM

  3. According to question number 1, what's the recommended way to filter the total request and show it to the corresponding user? for example, in Django Views, showing the total request each day from the last 7 days

As a piece of additional information, my API endpoints are mostly GET method and perform a function call, do some calculation or something, and return some data, not querying the database(Model.objects.get(id=id), etc...),

I apologize if my question doesn't make any sense, Thankyou ...

metersk
  • 11,803
  • 21
  • 63
  • 100
fhmisml
  • 71
  • 2
  • 3

1 Answers1

0

I would do the following

  1. inside authentication - create new object in database:

class ApiRequest(models.Model): key = models.ForeignKey(APIKey) timestamp = models.DateTimeField(auto_now_add=True, db_index=True)

  1. After saving - you can count how many requests was during the day (or 24 hours) - and if more than 100 - return 403 forbidden
Djangonaut
  • 5,511
  • 7
  • 40
  • 53