Home > database >  How do I send a list of items from my UI to my Django Rest Framework API?
How do I send a list of items from my UI to my Django Rest Framework API?

Time:02-04

my project uses multithreading to work on several tasks simultaneously. I'd like my UI (I'm using Vue.js) to send a list/array of items to my API to work on each individual item task. ex.

[{ 
"1": "item1",
"2": "item2",
"3": "item3",
...}]

(API searches the items to find what commands to use, that's why I used multithreading so I can work on several tasks at once instead of sending each individual item which takes too long)

How do I send a list or array of objects to the API?

CodePudding user response:

The answer is by using JavaScript to send data via request to your endpoint. How to do it depends on what you want to use, for example, one popular choice is axios.

Although, here is a simple example using fetch API:

template

<script>
    const url = '/your/endpoint/url/';
    data = [
        {'my': 'list', "of": "key", "pair": "values"}, 
        {'can': 'be', "multiple": "objects"}
    ]
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data) 
    })
    .then((response) => response.json())
    .then((data) => console.log(data.message));
</script>

views.py

class Endpoint(APIView):

    def post(self, request):
        print(request.data)
        # print output: [{'my': 'list', 'of': 'key', 'pair': 'values'}, {'can': 'be', 'multiple': 'objects'}]
        ...
        return Response({'message': 'data received'})
  • Related