Home > Enterprise >  Flask Curl POST - 500 Internal Secer Error - Pyrest API
Flask Curl POST - 500 Internal Secer Error - Pyrest API

Time:07-20

500 Internal Server Error when trying to set up a pyrest.

I am using a guide from https://linuxhint.com/rest_api_python/ to try and set up a rest API within my python 3 server, i am using the code below in api.py and using terminal, both the first GET requests i have put in work and display the data fine, when it comes to the POST request which is what i am trying to get working on the Virtual Machine with Ubuntu on i get a 500 internal error...

from flask import Flask, jsonify

app = Flask(__name__)

accounts = [
    {'name': "Billy", 'balance': 450.0},
    {'name': "Kelly", 'balance': 250.0}
     ]


@app.route("/accounts", methods=["GET"])
def getAccounts():
    return jsonify(accounts)
    
    
@app.route("/account/<id>", methods=["GET"])
def getAccount(id):
    id = int(id) - 1
    return jsonify(accounts[id])
    
@app.route("/account", methods=["POST"])
def addAccount():
    name = request.json['name']
    balance = request.json['balance']
    data = {'name': name, 'balance': balance}
    accounts.append(data)
    
    return jsonify(data)    
    
    
if __name__ == '__main__':
    app.run(port=8080)
    

I am guessing the code is correct and it is more of a server issue, problem is i am trying to install this service onto my server to get the POST method to work, not sure if i am missing any steps.

I am using

curl -X POST -H "Content-Type: application/json" -d '{"name": "Shovon", "balance": 100}' http://127.0.0.1:8080/account

To "Add" the data to the list of accounts which are within the api.py file.

Any help is appreciated, this is the first time i have used FLASK & APP.Route so please forgive me if its a newbie mistake.

CodePudding user response:

You forgot to import request from Flask, so the first two lines within your addAccount() function throw the 500 error. To fix the problem all you have to do is change the import line at the top to:

from flask import Flask, jsonify, request

Additionally one other thing to note is that it's encouraged to write function names following the PEP8 standard with an underscore between words and not camel case. Here's a fixed version of your file:

from flask import Flask, jsonify, request

app = Flask(__name__)

accounts = [
    {'name': "Billy", 'balance': 450.0},
    {'name': "Kelly", 'balance': 250.0}
     ]


@app.route("/accounts", methods=["GET"])
def get_accounts():
    return jsonify(accounts)
    
    
@app.route("/account/<id>", methods=["GET"])
def get_account(id):
    id = int(id) - 1
    return jsonify(accounts[id])
    
@app.route("/account", methods=["POST"])
def add_account():
    name = request.json['name']
    balance = request.json['balance']
    data = {'name': name, 'balance': balance}
    accounts.append(data)
    
    return jsonify(data)    
    
    
if __name__ == '__main__':
    app.run(port=8080)

  • Related