Mark
Mark

Reputation: 169

Can't POST because I'm missing arguments

I'm very new to Python and even newer to Flask RESTful. I'm trying to get my routes down and I'm having trouble POSTing. I get an error with using Postman saying "TypeError: post() missing 3 required positional arguments: 'username', 'avatar', and 'friend_code'" but I do have those arguments in the body of my POST request.

Below is my code. I want to only be able to POST from the root only.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

users = []


class User(Resource):
    def get(self, username):
        # /<username>
        for user in users:
            if user['username'] == username:
                return user

    def post(self, username, avatar, friend_code):
        # / root
        user = {'username': username, 'avatar': avatar,
                'friend_code': friend_code}
        users.append(user)
        return user


api.add_resource(User, '/', '/<string:username>')


app.run(debug=True)

Upvotes: 0

Views: 950

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Your post method needs 3 arguments username, avatar, friend_code.

When you do api.add_resource(User, '/', '/<string:username>'), you are passing just one argument(username). So, what about the other two(avatar & friend_code)?

Either you hardcode them to some constant values that your post method can always pick or use a reqparse to parse them from the payload's body.

Roughly like this:

from flask_restful import Resource, Api, reqparse
parser = reqparse.RequestParser()

def post(self):
        parser.add_argument('avatar', type=str)
        parser.add_argument('friend_code', type=str)
        args = parser.parse_args()

        user = {'username': username, 'avatar': avatar,
                'friend_code': friend_code}
        users.append(user)
        return user

Below is a nice link to get you started Building Basic RESTful API with Flask-RESTful.

Upvotes: 2

Related Questions