Search code examples
pythonpython-3.xapiflaskflask-restful

Getting Array keys in POST method using POSTMAN in Python 3 Flask-Restful API


How to get the value of array in postman using parser = reqparse.RequestParser() in flask api?

enter image description here

Im getting an error says: NoneType' object is not subscriptable

And here is my code:

class CreateUser(Resource):

    def post(self):
        try: 
          conn = None
          parser = reqparse.RequestParser()
          parser.add_argument('username', type = str)

          args = parser.parse_args()
          name = args['username'][0]

          return name
        except Exception as e:
            x = str(e)
            x.replace('\n', '')
            return {'status' : 'failed', 'message' : str(x)}
        finally:
            if conn is not None:
                conn.close()

im getting error with this name = args['username'][0] and i also try to make this too name = args[0]['username'] and still error appears and when i just make this like name = args['username'] the postman replies null. please help me.


Solution

  • Use this

    def post(self):
    try: 
      conn = None
      parser = reqparse.RequestParser()
      parser.add_argument('username[0]', type = str)
      parser.add_argument('username[1]', type = str)
    
      args = parser.parse_args()
      name = args['username[0]']
    
      return name
    except Exception as e:
        x = str(e)
        x.replace('\n', '')
        return {'status' : 'failed', 'message' : str(x)}
    finally:
        if conn is not None:
            conn.close()
    

    Editing for multiple params form data should be like this

    username: "user1"
    username: "user2"
    username: "user3"
    

    Yes you can pass multiple values with same key

    def post(self):
    try: 
      conn = None
      parser = reqparse.RequestParser()
      parser.add_argument('username', type = str, action='append')
      args = parser.parse_args()
      name = args['username']
      print(name) # ['user1', 'user2','user3'] you can traverse over this list