How to create a stores Rest API using Flask
Published: 2023-03-29 07:42:06

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?](#what-is-an-api)
- [What makes an API Restful?](#what-makes-an-api-restful) 
- [Creating a store Restful API](#creating-a-store-restful-api)
- [Initial set up for Flask App](#initial-set-up-for-flask-app)
- [Defining the API endpoint](#defining-the-api-endpoint)
- [Testing the API](#testing-the-api)
- [Create New Stores](#create-new-stores) 
- [Conclusion](#conclusion)

## 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](https://www.python.org/downloads/release/python-3100/), 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4wttkmhk7a7nxtg25wi.png)

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

```
$ python --version
```

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/](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](https://www.python.org/ftp/python/3.10.0/python-3.10.0-macos11.pkg) to start the download right away.


![python3.10 installed for mac](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2wrzs17r1dy7uk0dl4v.jpg)
To check which python version you have, type the following on your command prompt:
```
$ python3 --version
```
### 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
```
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
```
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

```py
from flask import Flask 

app = Flask(__name__) #this creates a flask app
```
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
```
you should see something like this:

![flask running message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ea68bm9gp6trm68pc6u0.png)

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. 
```py
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}]
    }
    ]
    }
]
```
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:

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

```
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
```
Now you can open the link on your browser:


![api rendered on the web](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijz4k8oxua8k84z4hx8s.png)

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](https://insomnia.rest/download)

![Insomnia download](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6az6qnsiyhk0qolfw6z.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rav7ae5zdjrtcs4jnzur.png)
After entering the URL in the GET search bar, you can output like this:

![get request search bar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ngw48ybhewuyho88g6m.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mzms7y9ittjwtbs48n2.png) 
Now go into your text editor and add the following lines of code in the 'app.py' file:
```py
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

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6cflagvs8whf2xpkbjsa.png)

Let's include some JSON data:


![Include JSON](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8p8qq0w52pfrifqrpq6n.png)

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

![post created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1jtapaq2xxx3pmt6j3p.png)

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.