neutrino
neutrino

Reputation: 924

can't POST data with Flask app using SQLAlchemy + Marshmallow

I'd like to POST some data to a database on AWS RDS. I have a Flask application, and I am trying to commit a SQLAlchemy object to the db.

here is a sqlalchemy class with 3 fields, and the accompanying marshmallow schema class :

class Plant(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    dur = db.Column(db.Integer)
    
    def __init__(self, name, dur):
        self.name = name
        self.dur = dur

class PlantSchema(ma.SQLAlchemySchema):
    class Meta:
        model = Plant

Here is the a POST request in app.py, in order to add a plant model to my database :

plant_schema = PlantSchema()

@app.route('/plants', methods=['POST'])
def add_plant():
    name = request.json.get('name', '')
    dur = request.json.get('dur', '')
    plant = Plant(name=name, dur=dur)
    db.session.add(plant)
    db.session.commit()
    return plant_schema.jsonify(plant)

unfortunately, when i POST my request in Postman, i get the following

<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Did not attempt to load JSON data because the request Content-Type was not &#x27;application/json&#x27;.</p>

this is the JSON that i am giving to postman, for the POST request.

{
    "name":"melon", 
    "dur":"1"
}

not sure where i went wrong, im not sure if the JSON is correctly structured, but i dont know the proper structure it should have, or where in the application the post is breaking down.

Upvotes: 0

Views: 279

Answers (1)

Rafael Marques
Rafael Marques

Reputation: 1872

You need to specify in your request that you are sending a json.

If you send without Content-Type, your application will return that you need to specify the Content-Type to application/json:

no content type informed

You just need to add the content type header:

with content type in header

Code for the example:

from flask import Flask
from flask import request


app = Flask(__name__)


@app.post("/")
def teste():
    a = request.json.get("teste", "")

    return a, 200


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

Upvotes: 1

Related Questions