DEV Community

Cover image for How to create a stores Rest API using Flask
Aderibigbe Samuel
Aderibigbe Samuel

Posted on

How to create a stores Rest API using Flask

In this tutorial, I'll show you how to build an API using the RESTful architecture and here's what the API will be able to do; receive requests from a client(such as a web application) and respond with some data. Using the API, clients will be able to create store and create items within a store. One of the main benefits of REST APIs is that they rely on the HTTP standard, which means you can use XML, JSON, HTML, etc for processing data. This makes REST APIs fast, and lightweight-which is necessary for web apps.

Article Summary

What is an API?

API stands for Application Programming Interface, which is a way for two or more computer programs to communicate with each other. APIs are more like a contract, they tells us how to use them and what sort of data we should expect to receive, they are meant to make your work as a developer easier by providing abstraction from what happens underneath. Think of a simple website, it has HTML, CSS, and Javascript, all working together to give you a web page. An API is just the data, and you often need to combine data with HTML, CSS, and Javascript. In its basic form, an API is a data-only communication between the server and the client.

What makes an API Restful?

The term REST is an acronym for Representational State Transfer and it is an architectural style that describes the architecture of the web. It is a set of rules or conventions on how to structure an API. When you follow this set of rules to create an API, it gives your API some properties which then make the API restful. The REST architectural style defines six guiding constraints which are:

  • client-server communication
  • stateless communication
  • caching
  • uniform interface
  • layered system
  • code on demand

Creating a store Restful API

Let's build a store API

Prequisites:

You'll need:

  • pip installed on your pc
  • Python 3.10 on your Windows or Mac
  • A Text Editor
  • Insomnia(an API testing tool)

Installing Python 3.10 on Windows OS:

Before you can start this tutorial, you need python 3.10 or a later version installed on your pc. There are different ways to get python installed on your pc but I will be explaining the easiest way. You can download and install the Python 3.10 installer from the Python download page here, choose either the 32-bit or 64-bit version depending on your PC (check your PC's information) and make sure to add python 3.10 to path.

python3.10 installed for windows

To check if the installation was successful, You can go into your command prompt and type the following:

$ python --version
Enter fullscreen mode Exit fullscreen mode

it should output the version of python installed on your pc.

Installing Python 3.10 on Mac OS:

For mac users, the easiest way is probably using a macOS 64-bit universal2 installer. Just go to https://www.python.org/downloads/release/python-3100/ and choose the macOS 64-bit universal2 installer, download the installer, and run it on your mac. You can just click this link to start the download right away.

python3.10 installed for mac
To check which python version you have, type the following on your command prompt:

$ python3 --version
Enter fullscreen mode Exit fullscreen mode

Initial set up for Flask App

First, you need to create a virtual environment and install the dependencies. Before we proceed, you should have created a project folder and navigated to that folder on your terminal or powershell.
To create the virtual environment type:

python3.10 -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Depending on the text editor you are using, you need to select which interpreter to use and it should be the one that has the path to your virtual environment. Do not know how to do this? A quick google search will help you. for Visual studio code( a popular text editor) the shortcut is command+shift+P.

let step is to install flask:

pip install flask
Enter fullscreen mode Exit fullscreen mode

Now that You have flask installed, let's create a boiler plate. Go into your text editor and create a file, let's call it app.py and the follow lines of code

from flask import Flask 

app = Flask(__name__) #this creates a flask app
Enter fullscreen mode Exit fullscreen mode

make sure that your file name(app.py) is consistent with the name of your variable 'app' (remember python is case-sensitive).
The next step is to run the flask app, you can do these from your terminal or powershell. Make sure you are in the app.py directory and your virtual environment is activated. To run the flask app:

flask run
Enter fullscreen mode Exit fullscreen mode

you should see something like this:

flask running message

you get the information of where your app is running in our example, it is running on http://127.0.0.1:5000

Defining the API endpoint

When an API interacts with another system, the touchpoints of this communication are considered endpoints. The place that APIs send requests and where the resources are stored is called an endpoint. simply put, An endpoint is one end of a communication channel.
We need to define where we will store our data. Usually, you will make use of databases but for this tutorial we will store our data in a python list. So, you will create a list of stores that consists of one dictionary per store.

from flask import Flask

app = Flask(__name__)

stores = [
    {
    "name": "Ekaabo Cosmetics",
    "items":[
    {"name" : "lip gel",
     "price" : 20.36
     },
    {"name" : "moisturizer",
     "price" : 38.90
     }, 
     {"name" : "hair wigs",
      "price" : 50.89
      },
      {"name" : "Body Cream",
       "price": 12.46}]
    }
    ]
    }
]
Enter fullscreen mode Exit fullscreen mode

what we've done is simple, dictionaries consist of key-value pair. For the example above, there's a name key and the value is the actual name of the store. The confusing part would be the items, the key is "items", the value consists of a list which in turn consist of dictionaries of name and price pair, hope it sinks.

Now let's create an endpoint that will return data when a client requests for it. Add the following lines to your code:

@app.get("/store")
def get_stores():
    return {"stores" : stores}

Enter fullscreen mode Exit fullscreen mode

The endpoint is the "/store" while the function associated with it is the get_stores().
Since our app is running on http://127.0.0.1:5000, go to your browser and enter http://127.0.0.1:5000/store to access the page, but before that run the flask application again in the terminal:

flask run
Enter fullscreen mode Exit fullscreen mode

Now you can open the link on your browser:

api rendered on the web

Note that the data displayed is in JSON format and ordering does not matter as seen above that the order does not follow how we wrote the data.

Testing the API

To verify that the API works, you need to test it, by making requests and check that the responses match what we expect. There are tools you can use to test your API e.g Postman, Locust, Insomnia,etc. For the purpose of this tutorial, We'll use Insomnia, it has a free trial and ids easy to use. You can can download it by clicking here

Insomnia download

Now that the app is runnning on your pc, let's test our API, click on the + icon to select "HTTP Request", then enter the url http://127.0.0.1:5000/store in the GET search bar. You must ensure your flask app is running before you enter the URL and click send

how to get request
After entering the URL in the GET search bar, you can output like this:

get request search bar
You should see the data that your API returns. It means the API's GET request is working fine.

Create New Stores

To create new store in our API,we will be receiving JSON from our client(Insomnia App), We'll receive the stored data and add it to our stores list, so that it then stays and the client can make requests to retrieve them. Instead of using a GET request, You will use a POST request and you need to include some JSON data

post request
Now go into your text editor and add the following lines of code in the 'app.py' file:

from flask import Flask, request #I modified this line


app = Flask(__name__)

stores = [
    {
    "name": "Ekaabo Cosmetics",
    "items":[
    {"name" : "lip gel",
     "price" : 20.36
     },
    {"name" : "moisturizer",
     "price" : 38.90
     }, 
     {"name" : "hair wigs",
      "price" : 50.89
      },
      {"name" : "Body Cream",
       "price": 12.46}]
    }
    ]


@app.get("/store")
def get_stores():
    return {"stores" : stores}


@app.post("/store")
def post_store():
    request_data = request.get_json() # you need to import json
    new_store = {"name": request_data["name"], "items":[]}
    stores.append(new_store) #append new store to the list
    return new_store, 201 #return the store and status code

Enter fullscreen mode Exit fullscreen mode

Now run the flask application in the terminal or powershell and then go to the Insomnia app and make a POST request.

post and include Json

Let's include some JSON data:

Include JSON

Now, hit the send button and you will the output:

post created

You get a status message "successfully created".

Conclusion

In this article, we covered what APIs are and what makes an API Restful. You now understand how APIs helps with interaction between the client and the server. You built a simple stores API and tested it using Insomnia.

Top comments (0)