Flask | Create Your First Flask API
Tags: flask, python
Published: 2024-02-19 20:16:40

## A Restaurant API

Let's set up a simple Flask API that returns a list of restaurants and their menu items in JSON format.
## What is an API?
In case you would like to learn what APIs are, feel free to visit the following excellent resources:
- [Postman - What is an API?](https://www.postman.com/what-is-an-api/)
- [freeCodeCamp - What is an API and How Does it Work? APIs for Beginners?](https://www.freecodecamp.org/news/how-apis-work/)
- [freeCodeCamp - API Cheat Sheet – What is an API, How it Works, and How to Choose the Right API Testing Tools?](https://www.freecodecamp.org/news/what-is-an-api-and-how-to-test-it/)


Now, let's begin.
## Steps:
### Before starting,make sure you have Flask installed on your machine
For installation steps go to [Flask's documentation](https://flask.palletsprojects.com/en/3.0.x/)

### Also, make sure you create and activate a new virtual environment
For steps go to any of the following great resources:
- [Real Python - Python Virtual Environments - A Primer](https://realpython.com/python-virtual-environments-a-primer/)
- [freeCodeCamp - How to Set Up a Virtual Environment in Python – And Why It's Useful?](https://www.freecodecamp.org/news/how-to-setup-virtual-environments-in-python/)
- [freeCodeCamp - Python Virtual Environments Explained with Examples](https://www.freecodecamp.org/news/python-virtual-environments-explained-with-examples/)
- [Python.Land](https://python.land/virtual-environments/virtualenv)
  

### 1. Open your terminal and create a directory for storing your code, 
```bash 
mkdir restaurant-api
```

### 2. Now, cd into the directory you just created
```bash 
cd restaurant-api
```

### 3. Within that directory, create a file named **app.py**
```bash 
touch app.py
```

### 4. Open your code editor (e.g. Visual Studio Code) and add the following code to the **app.py** file:

```python

from flask import Flask # Here we are importing the Flask class. This class is used to create the app.

app = Flask(__name__) # Here we are creating an instance of the Flask app.


"""
Below, you will see the `restaurants` list, which contains a few dictionaries.
Each dictionary within the `restaurants` list has a name and a list of items,
where each item is a dictionary with a name and a price.
"""

restaurants = [ 
    {
        "name": "Tasty Burgers",
        "items": [
            {
                "name": "Classic Burger",
                "price": 8.99
            },
            {
                "name": "Cheeseburger",
                "price": 9.99
            }
        ]
    },
    {
        "name": "Pizza Palace",
        "items": [
            {
                "name": "Pepperoni Pizza",
                "price": 11.99
            },
            {
                "name": "Margherita Pizza",
                "price": 10.99
            }
        ]
    }
]


@app.get("/restaurant")
# The above is a decorator that defines a route for handling GET requests
# to the `/restaurant` endpoint.

def get_restaurants():
    return {"restaurants": restaurants}
# The above is a function that returns a dictionary that contains the `restaurants` list
```



### 5. Now, let's start the app
```bash 
flask run
```
Flask will start a development server and host our application application, making it accessible at the following port http://127.0.0.1:5000/ by default. 


### 6. Open the browser of your preference and type in the following:
http://127.0.0.1:5000/restaurant

This is what you should see in your browser:

```JSON
{
  "restaurants": [
    {
      "items": [
        {
          "name": "Classic Burger",
          "price": 8.99
        },
        {
          "name": "Cheeseburger",
          "price": 9.99
        }
      ],
      "name": "Tasty Burgers"
    },
    {
      "items": [
        {
          "name": "Pepperoni Pizza",
          "price": 11.99
        },
        {
          "name": "Margherita Pizza",
          "price": 10.99
        }
      ],
      "name": "Pizza Palace"
    }
  ]
}
```

This JSON represents a data structure containing a list of restaurants, where each restaurant has a name and a list of items on its menu. Here's a breakdown of the structure:

- The outermost curly braces `{}` indicate an object.  
- The key `"restaurants"` maps to a value that is an array `[]` containing two objects, each representing a restaurant.  
- Each restaurant object has two key-value pairs:  
- The key `"name"` maps to the name of the restaurant (e.g., `"Tasty Burgers"` or `"Pizza Palace"`).  
- The key `"items"` maps to a value that is an array `[]` containing objects, each representing an item on the restaurant's menu.  
- Each item object has two key-value pairs:  
- The key `"name"` maps to the name of the item (e.g., `"Classic Burger"` or `"Pepperoni Pizza"`).  
- The key `"price"` maps to the price of the item (e.g., `8.99` or `11.99`).

### Further Reading
- [Flask Web Development: Developing Web Applications with Python, by Miguel Grinberg - 2018 - O'Reilly](https://www.amazon.com/Flask-Web-Development-Developing-Applications-dp-1491991739/dp/1491991739/ref=dp_ob_title_bk)
- [Full-Stack Flask and React: Learn, code, and deploy powerful web applications with Flask 2 and React 18
by Olatunde Adedeji - packt](https://www.amazon.com/Full-Stack-Flask-React-powerful-applications/dp/1803248440)

### References
- [Flask's documentation](https://flask.palletsprojects.com/en/3.0.x/)
- [Postman - What is an API?](https://www.postman.com/what-is-an-api/)
- [freeCodeCamp - What is an API and How Does it Work? APIs for Beginners?](https://www.freecodecamp.org/news/how-apis-work/)
- [freeCodeCamp - API Cheat Sheet – What is an API, How it Works, and How to Choose the Right API Testing Tools?](https://www.freecodecamp.org/news/what-is-an-api-and-how-to-test-it/)
- [Real Python - Python Virtual Environments - A Primer](https://realpython.com/python-virtual-environments-a-primer/)
- [freeCodeCamp - How to Set Up a Virtual Environment in Python – And Why It's Useful?](https://www.freecodecamp.org/news/how-to-setup-virtual-environments-in-python/)
- [freeCodeCamp - Python Virtual Environments Explained with Examples](https://www.freecodecamp.org/news/python-virtual-environments-explained-with-examples/)
- [Python.Land](https://python.land/virtual-environments/virtualenv)