The post and get functions for my Flask server look as follows:
from flask import Flask, request
import json
app = Flask(__name__)
tasks=[]
#Create a new task
@app.route('/v1/tasks', methods=['POST'])
def post():
data=request.get_json()
if "title" not in data:
return bulkadd(data)
title=data["title"]
tasks.append(json.dumps({"id": len(tasks)+1, "title": title, "is_completed": "false"}))
index=len(tasks)
return json.dumps({"id": index}), 201
#List all tasks created
@app.route('/v1/tasks', methods=['GET'])
def getall():
app.logger.info({"tasks": tasks})
return json.dumps({"tasks": tasks})
After calling post twice, this is the output from get:
{"tasks": ["{\"is_completed\": \"false\", \"id\": 1, \"title\":\"Test Task 2\"}", "{\"is_completed\": \"false\", \"id\": 2, \"t:03] "POST /v1/tasks HTTP/1.1" 201 -itle\": \"Test Task 2\"}"]}
Instead, this is how I would like the format of the output:
{
tasks: [
{id: 1, title: "Test Task 1", is_completed: true},
{id: 2, title: "Test Task 2", is_completed: false}
]
}
Why is the order different and what do the \" mean?
Thank you for your help!
Edit 1: Could you also help me why the following test to post function throws this error?:
Does this not generate a valid json?
return json.dumps({"id": index}), 201
_____________________________________ test_create_task _____________________________________
def test_create_task():
r = requests.post('http://localhost:5000/v1/tasks', json={"title": "My First Task"})> assert isinstance(r.json()["id"], int)
project1-test3.py:6:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/home/alexanderfarr/.local/lib/python3.6/site-packages/requests/models.py:898: in json
return complexjson.loads(self.text, **kwargs)
/usr/lib/python3/dist-packages/simplejson/__init__.py:518: in loads
return _default_decoder.decode(s)
/usr/lib/python3/dist-packages/simplejson/decoder.py:370: in decode
obj, end = self.raw_decode(s)