Skip to main content

Django REST Params

Function decorator to specify and validate parameters for API calls. Invalid params will automatically return a useful error message; validated params are passed to the wrapped function as kwargs.

pip install django-rest-params==1.0.2

A Few Examples

Specify the types of parameters, and check that they are within acceptable ranges:

from django_rest_params.decorators import params

@api_view(['GET'])
@params(latitude=float, latitude__gte=-90.0, latitude__lte=90.0,
        longitude=float, longitude__gte=-180.0, longitude__lte=180.0)
def get_something(request, latitude, longitude):
    # If latitude/longitude are missing or out of range, user will get an error message.
    # If we get here, we know they're valid
    pass

Create optional params with default values. Django REST Params supports POST params as well:

@api_view(['POST'])
@params(offset=int, offset__default=0)
def paged_api_call(request, offset):
    # if offset isn't specified, default value is used
    pass

Django REST Params works with ViewSets as well as request functions.

class ShirtsViewSet(viewsets.GenericViewSet):

    @params(colors=('red','blue','green','yellow'), colors__many=True,
            colors__optional=True, colors__name='color_filter')
    def get_shirts(self, request, colors):
        # Handle API calls like these:
        # /shirts?color_filter=red          __name lets you use a function param name different from the API param name
        # /shirts?color_filter=yellow,blue  __many lets you pass multiple values
        # /shirts                           __optional will set colors to None if it isn't specified
        # /shirts?color_filter=black        ERROR! This will return an error stating black is invalid, and listing the valid options
        pass

Options

TYPE

Specify the type of a param:

latitude=float
valid options are:
  • int

  • float

  • bool (1/true are considered True, and 0/false False; this is not case-sensitive)

  • str/unicode

  • tuple/list/set/frozenset (which will be treated as a list of valid options)

  • a django Model subclass (in which case the param will be treated as a PK to that Model)

GT/LT/GTE/LTE

Automatically check that a param falls within a certain range. Valid for float, int, or Model PK, which all do numerical comparisons.

latitude__gte=-90.0
latitude__lte=90.0

LENGTH__LT/GT/LTE/GTE/EQ

Only valid for str params. Check the length of the str

description__length__lt=256
country_code__length__eq=2

OPTIONAL

latitude__optional=True # same as latitude__default=None

Default is False; if set to True, this param will be checked for validity (it will still return a 400 if it doesn’t pass gte checks, for example), but will be passed to the wrapped function as None if it wasn’t specified.

DEFAULT

sort_by=('messages_count', 'most_recent')
sort_by__default='messages_count'

Implies that this param is optional. Specify a default value for this param if it isn’t specified.

NAME

By default, we’ll look for a param with the same name as the kwargs, e.g.

user_id=User # User is a Django model. Look for user_id param, fetch corresponding User, pass to wrapped fn as user_id

But sometimes it makes more sense to call such a param ‘user’ locally, so you can do:

user=User, user__name='user_id' # look for user_id, assign to user

MANY

users=int # param 'users=1' is ok, 'users=1,2' is not
users__many=True # param 'users=1,2' will return tuple of (1, 2), 'users=1' will return (1)

Allow User to (optionally) specify params as CSV (GET) or Array (JSON POST) If many==True, the params will be returned as a tuple regardless of whether or not there was only one param

DEFERRED

user__deferred=True

By default, Django REST Params will retrieve an object like this:

User.objects.only('id').get(id=user_id) # all fields except for 'id' are deferred

Usually, this is preferrable, since we usually don’t need to fetch the entire object from the DB, and it is significantly faster than doing so. By setting __deferred to False, Django REST Params will change the object retrieval call to this:

User.objects.get(id=user_id)  # All fields are fetched

FIELD

category = Category # by default, do Category.get(id=category)
category__field='name' # instead, do Category.get(name=category)

Applies to Django models only. By default, we treat the param as an ID; instead, you can treat it as something else, e.g. ‘name’

METHOD

Valid methods for passing this param. Default is ‘POST’ for POST/PUT requests and GET for all others

user__method='GET' # GET only
user__method=('GET', 'POST') # allow either source

Extra Customization

You can tweak some behavior by setting adding a ‘DJANGO_REST_PARAMS’ dict to your Django settings module:

DJANGO_REST_PARAMS: {
    'TRUE_VALUES': ('1', 'true'),    # tuple of case-insensitive string values we'll accept as True for a param of type bool.
    'FALSE_VALUES': ('0', 'false'),  # string values that are considered false
}

Tests

Run the (fairly extensive) unit tests:

make test

Mock classes are used to simulate Django models / managers / Django REST Framework requests, so these tests don’t actually need to run inside a Django app.

Metadata

Release files for django-rest-params 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-rest-params 1.0.2
File Size Uploaded Provenance Actions
django-rest-params-1.0.2.tar.gz 6.9 kB Without provenance Details for django-rest-params-1.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-rest-params 1.0.2
File Interpreter ABI Platform Actions
django_rest_params-1.0.2-py2.py3-none-any.whl Python 2, Python 3 none any Details for django_rest_params-1.0.2-py2.py3-none-any.whl

Total release size: 19.3 kB

Release files / django-rest-params-1.0.2.tar.gz

Download URL django-rest-params-1.0.2.tar.gz
Size 6.9 kB
Tags Source
SHA-256 checksum
How to use checksums
1e911192d6bd3008719875d8c7e82dc93eafd434502afe52b1561944e3aa5536
BLAKE2b-256 checksum
How to use checksums
6220ba2983442c6bc1088b1ee87b38d1abd5e7a62546b02e980962f32eb86446
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / django_rest_params-1.0.2-py2.py3-none-any.whl

Download URL django_rest_params-1.0.2-py2.py3-none-any.whl
Size 12.4 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
248fe5fcf2e8d24f958d738b33a469b2cbe1f1b0db20082e014abda214f693b8
BLAKE2b-256 checksum
How to use checksums
ca36ef394c571436b209d3c1994920df6baf1cfac75d3a562e25526a8e809782
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for django-rest-params 1.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page