2

I'm implementing an API using Django Rest framework. I wonder Python can send POST params as an array like Ruby does?

For example:

POST /api/end_point/
params = { 'user_id': [1,2,3] }

# In controller, we get an array of user_id:
user_ids = params[:user_id] # [1,2,3]

1 Answer 1

5

There are a number of ways to deal with this in django-rest-framework, depending on what you are actually trying to do.

If you are planning on passing this data through POST data then you should use a Serializer. Using a serializer and django-rest-frameworks Serializer you can provide the POST data through json or through a form.

Serializer documentation: http://www.django-rest-framework.org/api-guide/serializers/ Serializer Field documentation: http://www.django-rest-framework.org/api-guide/fields/

Specifically you will want to look at the ListField.

It's not tested, but you will want something along the lines of:

from rest_framework import serializers
from rest_framework.decorators import api_view

class ItemSerializer(serializers.Serializer):
    """Your Custom Serializer"""
    # Gets a list of Integers
    user_ids = serializers.ListField(child=serializers.IntegerField())

@api_view(['POST'])
def item_list(request):
    item_serializer = ItemSerializer(data=request.data)
    item_serializer.is_valid(raise_exception=True)
    user_ids = item_serializer.data['user_ids']
    # etc ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.