view raw
Mike Johnson Mike Johnson - 6 months ago 44
Python Question

Building a REST API in Flask getting a 400 error when trying to make a POST request

I'm following a tutorial here, and I'm at the part where we first start setting up the create_task function. I keep getting the error

<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

I'm on windows and using the cURL command

curl -i -H "Content-Type: application/json" -X POST -d '{"title":"Read a book"}' http://localhost:5000/api/v1.0/tasks

Here's my code

from flask import Flask, jsonify, abort, make_response, request

app = Flask(__name__)

tasks = [
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the Web',
'done': False

def not_found(error):
return make_response(jsonify({'404': 'Resource Not Found'}), 404)

@app.route('/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = [task for task in tasks if task['id'] == task_id]
if len(task) == 0:
return jsonify({'task': task[0]})

@app.route('/api/v1.0/tasks', methods=['POST'])
def create_task():
if not request.json or not 'title' in request.json:
task = {
'id': tasks[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'done': False
return jsonify({'task': task}), 201

if __name__ == '__main__':

I've tried everything I can think of. Any help would be greatly appreciated.


Your code works perfectly fine. Try reinstalling flask.

Instead of cURL you can also try sending the request through POSTMAN (Chrome Plugin).

Through cURL: Right side window shows the Result

Right side window shows the Result

Through Postman (Chrome Plugin):

enter image description here