(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:

  1. To create a store, we will first receive data in JSON format 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.

  2. 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
                }
            ]
        }
    ]
  1. The clients can then make other HTTP requests and include the newly created store.
  2. We will apply the HTTP method POST when creating this resource.
  3. 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:

  1. Import request from flask
from flask import Flask, request
  1. Use the @app.post decorator to define a route that handles POST requests at the '"/store"' path. Our route pattern will be @app.post("/store").
@app.post("/store")
  1. 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 a POST request to this route.
def create_store():
  1. 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()
  1. Next, we will create a new dictionary representing our new store; it will include a name field (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": []}
  1. Then, we append this store to our stores list.
 stores.append(new_store)
  1. 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
  1. 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
  1. 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
  1. We will now use the Insomnia client to test and ensure our endpoint functions as expected by creating and sending a new HTTP POST request.
  2. 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:

  1. API Endpoint URL: POST http://127.0.0.1:5000/store.
  2. Request Body: Please include the store name on the JSON body tab.
  3. 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:

  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.
  1. 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.
  1. Select an HTTP POST method on the Request Line, and then enter an API URL in the address field: POST http://127.0.0.1:5000/store.
  1. To change the route title of this resource, click on the 'New Request' tab and select Rename from the drop-down.
  1. You can call the route title of this resource '/store Create new store.'
  1. Select the JSON tab on the Request Body and enter the name of the store you'd like to create.
  1. Now, you can click the ' Send' tab to make a POST request to the endpoint URL. The server will receive the request, parse the JSON body, and process the data to create a new store.

Results:

  1. Our API returned a newly created store with an empty list '[]' and a status code of 201, which means created.
  1. To display a complete list of stores created in this API, send another HTTP request using the '/store Get all store data' endpoint.
  1. 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:

  1. Every response has a status code that tells the client whether the server was successful.
  1. The most common status code is 200, which means OK. Flask typically returns the same status code by default. If you look at the above screenshot, you will notice that the get_stores() function from the first endpoint we created returns the same 200 (OK) status code.
  2. 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.
  3. Therefore, our function 'create_store()' returned a customized success message with a status code of 201(OK), which means 'Created.'
  4. If we were to restart our app and make another GET HTTP 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.
  1. Thus, we will use a database instead of a Python list in the upcoming sections because it provides significant advantages.
  2. Since we now know how to create stores in a REST API, let's move forward in the next section and learn how to add items to each store.
  3. Here's the link to the next section of the tutorial: How to Create Items within a Store