1

So im trying to POST to my python rest server but i cant get this right. The goal is to send a list from the client to server and when received check if objcects of that list already exist in another, and if not, to append them to the existing list. Heres my code:

Server:

from flask import Flask, request jsonify
import requests, json

app = Flask(__name__)
url = "http://0.0.0.0:5000"
list = ["1","2","3","4"]
IPs2 = []

@app.route('/')
def index():
     return "Hello"
@app.route('/list/', methods=['GET','POST'])
def get_tasks():
    if request.method == 'GET':
        return jsonify(list)
    if request.method == 'POST':
        IPs2 = request.json(IPs)
        for i in IPs2:
            if i not in list
                list.append(i)
if __name__ == '__main__':
app.run(host="0.0.0.0", port = 5000,debug=True)

client:

import json 
import requests

IPs = ["4", "5"]
api_url = 'http://0.0.0.0:5000/list/'
r = requests.post(url = api_url, json=IPs)
jakkis
  • 73
  • 1
  • 9

2 Answers2

1

Your code is missing comma and indents, therefore can't be pasted in order to reproduce the problem. Additionally, you did not describe, what exactly is wrong, so apart from missing comma and indent, you should:

server.py

from flask import Flask, request, jsonify
import requests, json

app = Flask(__name__)
url = "http://0.0.0.0:5000"
main_list = ["1","2","3","4"]

@app.route('/')
def index():
     return "Hello"
@app.route('/list/', methods=['GET','POST'])
def get_tasks():
    if request.method == 'GET':
        return jsonify(main_list)
    if request.method == 'POST':
        print(request.json)
        IPs2 = request.json
        for i in IPs2:
            if i not in main_list:
                main_list.append(i)
    return 'OK', 201
if __name__ == '__main__':
    app.run(host="0.0.0.0", port = 5000,debug=True)

Regards Pawel

Pawel Stradowski
  • 807
  • 7
  • 13
0

Json format needs {key: value} data to be properly parsed, you can add a content key at the root:

from flask import Flask, request, jsonify

app = Flask(__name__)
mylist = []
body = {"content": mylist}

@app.route('/list/', methods=['GET', 'POST'])
def get_tasks():
    if request.method == 'GET':
        return jsonify(body)
    if request.method == 'POST':
        print(request.data)
        received = request.get_json()
        for ip in received["content"]:
            if ip not in mylist:
                mylist.append(ip)
        print(mylist)
        return request.data


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)
Marsu
  • 786
  • 6
  • 9