All you need to know on API development in Flask

The Right Way to Build an API with Python

Photo by Steve Johnson on Unsplash

How can we set up a way to communicate from one software instance to another? It sounds simple, and — to be completely honest — it is.

All we need is an API.

An API (Application Programming Interface) is a simple interface that defines the types of requests (demands/questions, etc.) that can be made, how they are made, and how they are processed.

Flask API video walkthrough — covering everything in this article!

In our case, we will be building an API that allows us to send a range of GET/POST/PUT/PATCH/DELETE requests (more on this later), to different endpoints, and return or modify data connected to our API.

We will be using the Flask framework to create our API and Postman to test it. In short, we will cover:

> Setup
  - Our Toy Data
  - Initialize a Flask API
  - Endpoints
  - Running a Local Server
> Writing Our API
  - GET
  - POST
  - 401 Unauthorized
  - PUT
  - DELETE
  - Users Class (summary)
> That's It!

Setup

Our API will contain two endpoints, users and locations. The former will allow access to our registered user’s details, whereas the latter will include a list of cafe locations.

The hypothetical use-case here is of a multi-million cafe bookmarking app, where users open the app and bookmark their favorite cafe’s — like Google Maps, but not useful.

Our Toy Data

For the sake of simplicity, we are going to store this data in two local CSV files. In reality, you probably want to take a look at something like MongoDB or Google Firebase.

Our CSV files look like this:

User’s data in users.csv. Image by Author.
Location mappings in locations.csv. Image by Author.

You can download users.csv here, and locations.csv here.

Initialize a Flask API

Now to our Python script, we need to import modules and initialize our API, like so:

from flask import Flask
from flask_restful import Resource, Api, reqparse
import pandas as pd
import astapp = Flask(__name__)
api = Api(app)

Endpoints

As we already touched on, our API will have two endpoints, users and locations.

The result of this is — if our API was located at www.api.com, communication with the Users class would be provided at www.api.com/users and Locations at www.api.com/locations.

To create an endpoint, we define a Python class (with any name you want) and connect it to our desired endpoint with api.add_resource, like this:

  • Flask needs to know that this class is an endpoint for our API, and so we pass Resource in with the class definition.
  • Inside the class, we include our HTTP methods (GET, POST, DELETE, etc.).
  • Finally, we link our Users class with the /users endpoint using api.add_resource.

Because we want two endpoints, we replicate the logic:

Running a Local Server

Finally, when we write out our API, we need to test it!

To do this, we need to host our API, which we can do locally by adding app.runto the end of our script like this:

if __name__ == '__main__':
    app.run()  # run our Flask app

Now, when we run our script, we should see something like this:

Initialization of our localhost server. Image by Author.

Once our server is setup, we can test our API as we build it using Postman, if you haven’t used it before it is the de-facto standard for API testing. And, don’t worry — it’s incredibly simple to use — download Postman from here.

Before going ahead, you can find the full script that we will be building here. If you’re not sure where a code snippet should go, check there!

Writing API Methods

Inside each of our classes, we keep our HTTP methods, GET, POST, and DELETE.

To create a GET method, we use def get(self). POST and DELETE follow the same pattern.

GET

The GET method is the simplest. We return all data stored in users.csv wrapped inside a dictionary, like so:

We can then run the script to initialize our API, open Postman and send a GET request to our localhost address (typically http://127.0.0.1:5000)— this is our API entry point.

How to send a GET request to our API. Image by Author.

To send a GET request to our API in Postman we:

  1. Select GET from the dropdown
  2. Type the entry point of our API instance + /users (the endpoint)
  3. Hit Send
  4. Check the status code returned by our API (we should see 200 OK)
  5. View our API’s response, which is users.csv in JSON (like a dictionary) format

POST

The POST method allows us to add records to our data. In this case, we will take arguments for usedId, name, and city.

These arguments are passed to our API endpoint as URL parameters, which look like this:

http://127.0.0.1:5000/users?userId=abc123&name=The Rock&city=Los Angeles

We can specify the required parameters, and then parse the values provided using reqparse — like this:

Let’s break our parser code down:

Gallery for All you need to know on API development in Flask

Leave a Reply