Requirement:
Need to create a new store in our My store.
Scenario1:
We create a dummy post method in our code with pass , try to hit from post man using post request and see what is the response flask provides.
from flask import Flask,app
app = Flask(__name__)
stores = [
{
"name": "my store",
"items": [
{"name": "my item",
"price": 15.99
}
]
}
]
@app.get("/stores")
def get_stores():
return stores
@app.post("/stores")
def create_store():
pass
Output:
As we see we are getting 500 internal server error. This is due to Flask always expects a response.
Scenario 2:
Now change the code snippet to below:
@app.post("/stores")
def create_store():
pass
Restart the server and hot from post man you get below.
Scenario 3:
Now add a code to add the incoming data from post request to the stores in our app and show it back.
For this one to read the inputs from the request , we need to import request from flask like below. After using the request object read the values.
from flask import Flask, request
app = Flask(__name__)
stores = [
{
"name": "my store",
"items": [
{"name": "my item",
"price": 15.99
}
]
}
]
@app.get("/stores")
def get_stores():
return stores
@app.post("/stores")
def create_store():
request_data = request.get_json()
new_store = { "name": request_data["name"], "items": []}
stores.append(new_store)
return new_store, 201
output:
Now hit our get endpoint




Top comments (0)