0

I know this seems like a dumb question, but I've dug and dug and can't find any answer that seems to provide a fix.

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

app = Flask(__name__)

basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.sqlite')
db = SQLAlchemy(app)
ma = Marshmallow(app)

class Guide(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), unique=False)
    content = db.Column(db.String(144), unique=False)

    def __init__(self, title, content):
        self.title = title
        self.content = content


class GuideSchema(ma.Schema):
    class Meta:
        fields = ('title', 'content')


guide_schema = GuideSchema()
guides_schema = GuideSchema(many=True)

# Endpoint to create a new guide
@app.route('/guide', methods=["POST"])
def add_guide():
    title = request.json['title']
    content = request.json['content']

    new_guide = Guide(title, content)

    db.session.add(new_guide)
    db.session.commit()

    guide = Guide.query.get(new_guide.id)

    return guide_schema.jsonify(guide)


# endpoint to query all guides
@app.route('/guides', methods=["GET"])
def get_guides():
    all_guides = Guide.query.all()
    result = guides_schema.dump(all_guides)
    return jsonify(result.data)


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


Full Traceback:

Traceback (most recent call last):
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 2088, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/bmoney/Documents/python_projects/flask-practice/venv/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/Users/bmoney/Documents/python_projects/flask-practice/app.py", line 34, in add_guide
    title = request.json['title']
TypeError: 'NoneType' object is not subscriptable

I know that None isn't iterable in this case, but I can't see what would be running a NoneType error.

For what the information is worth, I'm running GET and POST requests through Postman, at the correct localhost.

Thank you in advance, I really appreciate this community!

  • can you [edit](https://stackoverflow.com/posts/68280221/edit) and paste the full traceback error. and try using `request.form['title']` and `request.form['content']` – charchit Jul 07 '21 at 04:58
  • Sorry about that! I gave changing ```request.json``` to ```request.form```, and that didn't seem to work out :/ – Bryson Fulton Jul 07 '21 at 05:07

1 Answers1

2

request.json is None when the Flask server is not receiving any JSON data or any request with the Content-Type of application/json.

To fix this, make sure your client (if you are using JS or Postman) uses application/json as the Content-Type in the headers, and it should have JSON payload.

Take a look at this, and I hope you will find out how to make your client-side send JSON payload in the request: Fetch: POST JSON data

DevGuyAhnaf
  • 141
  • 1
  • 2
  • 12
  • Normally, I'm able to see ```Content-Type``` in the headers, but it doesn't look like it's there. Why wouldn't that be populated, if I'm able to see a ```Content-Length```, although the length is set at 0. – Bryson Fulton Jul 07 '21 at 05:17
  • @BrysonFulton If that's the case, then you should arbitrarily set the Content-Type in your JS POST request. Make sure it's `application/json` – DevGuyAhnaf Jul 07 '21 at 05:18