faizan shafiq
faizan shafiq

Reputation: 31

Getting error when calling flask Restful api in python

Hello there I am beginner in python and I am getting this error when calling api on my local machine 'localhost'

from flask import Flask,request
from flask_restful import Resource,Api

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

todos = {}
class HelloWorld(Resource):
    def get(self):
        return 'Hello, World War 3'

class Todo(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self,todo_id):
        todos[todo_id] : request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(HelloWorld,'/')
api.add_resource(Todo,'/<string:todoId>')

if __name__ == '__main__':
    app.run(debug=True)

and Here is the error I am getting while calling this api

raise JSONDecodeError("Expecting
value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Its a pretty small code and yet I am unable to catch the real issue. I am doing as it is on the official site of flask: Flask Site

I have seen other posts on the same issue but they are of high level which I am unable to understand. Any help would be appreciated, thanks

Upvotes: 0

Views: 1642

Answers (1)

Rahul Shelke
Rahul Shelke

Reputation: 2166

There are a few issues in your code which are as follows:

  • Instead of keeping Todo list empty, add something and test like: todos = {'1': "Say hello"}

  • The API endpoint for todo is having todoId as a string object but in the get and put method you have todo_id as a parameter. Both should be same.

  • Instead of returning a single string it's better to return a JSON object. Like in your code replace 'Hello, World War 3' by something like {'msg': 'Hello, World War 3'}

NOTE: The last one is just for your information to keep all returns standard, and not an issue really.

Use following code for testing, and compare with your code in question. You will get an idea.

from flask import Flask, request
from flask_restful import Resource, Api

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

todos = {'1': "Say hello"}

class HelloWorld(Resource):
    def get(self):
        return {'msg': 'Hello, World War 3'}

class Todo(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self,todo_id):
        todos[todo_id] : request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(HelloWorld,'/')
api.add_resource(Todo,'/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)

Upvotes: 1

Related Questions