(H). How to Create Stores in a REST API - ZamaZoe/2.-Kurro-REST-API-Tutorial_Basic-REST-API GitHub Wiki
Introduction
Welcome back!
Here, you will learn how to create stores in a REST API. We will continue to expand and develop our current code.
from flask import Flask
app = Flask(__name__)
stores = [
{
"name": "Kurro Stores",
"items": [
{
"name": "iMac",
"price": 37.99
}
]
}
]
# Our first endpoint
@app.get("/store") # http://127.0.0.1:5000/store
def get_stores():
return {"stores": stores}
About this task:
-
To create a store, we will first receive data in
JSONformat from a client. For this tutorial, our client is the insomnia client, but it could be another Python app, a JavaScript app, a mobile app, a web app, etc. -
The client will provide us with the 'store name,' and we will add it to the database (a Python list), as shown below. We will use this information from the client to create a resource and call this resource (
/store).
# Here's our Python list
stores = [
{
"name": "Kurro Stores",
"items": [
{
"name": "iMac",
"price": 37.99
}
]
}
]
- The clients can then make other HTTP requests and include the newly created store.
- We will apply the HTTP method
POSTwhen creating this resource. - To access the JSON body of a request, we must import '
request' from 'flask.' Your import list should now look like this:
from flask import Flask, request
The Steps to Create a Store in a REST API
Here, we will add a new store to the API using information received from the client (Insomnia).
Prerequisites for this task:
To ensure accuracy, have Visual Studio Code and Insomnia client screens open side by side. Always be in the Insomnia client, running requests, testing your app, and verifying your writing.
Here are the steps to create a store endpoint:
Step 1: Use the following steps to create a route and code your store endpoint:
- Import
requestfromflask
from flask import Flask, request
- Use the
@app.postdecorator to define a route that handlesPOSTrequests at the '"/store"' path. Our route pattern will be@app.post("/store").
@app.post("/store")
- To create a function for this endpoint, use the Python keyword '
def' and name it 'create_store.' This function is associated with the '@app.post("/store")' decorator, and it will execute when the clients make aPOSTrequest to this route.
def create_store():
- To retrieve the incoming JSON data from the request payload, use '
request_data= request.get_json().' That also assumes that the request contains valid JSON data.
request_data = request.get_json()
- Next, we will create a new dictionary representing our new store; it will include a
namefield (taken from the JSON payload), which will also initialize an empty list for the "items" field. Then, we will store our new store in a variable called 'new-store.'
new_store = {"name": request_data["name"], "items": []}
- Then, we append this store to our
storeslist.
stores.append(new_store)
- After creating the '
store', we will send a JSON response. This response includes the newly created store along with an empty list'[].' To confirm the successful creation of the store, we also include a '201' status code. That marks the end of our function.
return new_store, 201
- Here's the code for this endpoint:
@app.post("/store")
def create_store():
request_data = request.get_json()
new_store = {"name": request_data["name"], "items": []}
stores.append(new_store)
return new_store, 201
- Your code should look similar to the one provided here:
from flask import Flask, request
app = Flask(__name__)
stores = [
{
"name": "Kurro Stores",
"items": [
{
"name": "iMac",
"price": 37.99
}
]
}
]
# Our first endpoint
@app.get("/store") # http://127.0.0.1:5000/store
def get_stores():
return {"stores": stores}
# Store endpoint
@app.post("/store")
def create_store():
request_data = request.get_json()
new_store = {"name": request_data["name"], "items": []}
stores.append(new_store)
return new_store, 201
- We will now use the Insomnia client to test and ensure our endpoint functions as expected by creating and sending a new HTTP
POSTrequest. - Remember to restart your app before moving forward with the next step.
Step 2: Use the following steps to test the functionality of your endpoint:
To test the functionality of our API endpoint, we will send an HTTP request to the endpoint we created in Step 1 and review the responses. We will use an HTTP POST method with our route ("/store") to execute this request and include the store name in the JSON body.
Paremeters:
- API Endpoint URL:
POSThttp://127.0.0.1:5000/store. - Request Body: Please include the store
nameon the JSON body tab. - API Endpoint Title (Resource name):
/store Create a new store.
Here are the steps to test the functionality of an endpoint we created in Step 1:
- To send a new HTTP request in Insomnia, go to the homepage, choose your project (REST API Tutorial), and click the '
Request Collection' tab.
- On the '
Request Collection' tab, click the plus sign (+)next to the 'Filter tab' and select the 'HTTP Request' tab. Alternatively, type 'Ctrl + N' from the keyboard.
- Select an HTTP
POSTmethod on the Request Line, and then enter an API URL in the address field:POST http://127.0.0.1:5000/store.
- To change the route title of this resource, click on the '
New Request' tab and selectRenamefrom the drop-down.
- You can call the route title of this resource '
/store Create new store.'
- Select the JSON tab on the Request Body and enter the name of the store you'd like to create.
- Now, you can click the '
Send' tab to make aPOSTrequest to the endpoint URL. The server will receive the request, parse the JSON body, and process the data to create a new store.
Results:
- Our API returned a newly created store with an empty list '
[]' and a status code of201, which means created.
- To display a complete list of stores created in this API, send another HTTP request using the '
/store Get all store data' endpoint.
- Once again, the API returned two created stores: the one we have already hard-coded in our Python list and the new one we have just created.
Conclusion:
- Every response has a status code that tells the client whether the server was successful.
- The most common status code is
200, which meansOK. Flask typically returns the same status code by default. If you look at the above screenshot, you will notice that theget_stores()function from the first endpoint we created returns the same200(OK) status code. - Since we wanted the app to display a unique status code, we used Flask to redefine our code, and we made it the second output of an endpoint function.
- Therefore, our function '
create_store()' returned a customized success message with a status code of201(OK), which means 'Created.' - If we were to restart our app and make another
GETHTTP request, the store we created wouldn't appear because Python lists don't persist between app runs. They just get deleted because they live only in memory.
- Thus, we will use a database instead of a Python list in the upcoming sections because it provides significant advantages.
- Since we now know how to create
storesin a REST API, let's move forward in the next section and learn how to additemsto each store. - Here's the link to the next section of the tutorial: How to Create Items within a Store