User588233
User588233

Reputation: 491

How to POST unique values to multiple dictionaries using curl

I am writing a REST api with Flask, which should create a Dictionary of Dictionaries, e.g.

Dictionary = {
        dict1 = {},
        dict2 = {}
        }

I would like each dict to be filled with individual values, and I would like to fill both dicts in one request, if possible.

So far I have been testing my code with curl requests, and it seems like it is almost there... except for that both dicts are being filled with the same collection of values.

api.py

dictionary = {}

@app.route('/launch', methods=['POST'])
def launch():
    gw_type = request.json['type']

    for t in gw_type:
        dictionary[t] = {
            'client': request.json['client']
            'band': request.json['band']
            'password': request.json['password']

    return jsonify(**dictionary)

Curl request

curl -H "Content-Type: application/json" -X 
POST -d '{"type":["type1", "type2"], "client":["test1", "test2"], 
"bands":["ABCD", "ABC"], "password":["pass", "pass2"]}' 
http://localhost:5000/launch

Output

{
  "type1": {
    "bands": [
      "ABCD",
      "ABC"
  ],
  "client": [
    "test1",
    "test2"
  ],
  "password": [
    "pass",
    "pass2"
  ]
},
"type2": {
  "bands": [
    "ABCD",
    "ABC"
  ],
  "client": [
    "test1",
    "test2"
  ],
  "password": [
    "pass",
    "pass2"
  ]
 }
}

If it is possible, how would I go about creating the multiple dictionaries ('type'), so that each TYPE has it's own unique values for 'client', 'band' and 'password' in one curl request?

Thanks

Upvotes: 0

Views: 1158

Answers (1)

pech0rin
pech0rin

Reputation: 5016

So you are accessing the entire list of client bands and password everytime. If they are ordered in the curl command the way you want then all you need to do is modify your code to use indexes for the correct values:

@app.route('/launch', methods=['POST'])
def launch():
    gw_type = request.json['type']

    for i in range(len(gw_type)):
        dictionary[gw_type[i]] = {
            'client': request.json['client'][i]
            'band': request.json['band'][i]
            'password': request.json['password'][i]

    return jsonify(**dictionary)

This will get the first client for the first type, the first band for the first type, the second client for the second type, etc.

Upvotes: 1

Related Questions