Building your first REST API

How to build a REST API using Python and Flask

The code

For this example, we will be building a simple API that will return a basic JSON payload with some mock data. We will also be securing our API using JWT authentication to ensure that no one can access the API without proper authentication.

  1. Step 2: Create the routes (endpoints)
  2. Step 3: Secure the application using JWT
pip install Flask
pip install flask-jwt-extended
# Import the relevant librariesfrom flask import Flask, jsonify, make_response, request
from flask_jwt_extended import jwt_required, create_access_token, JWTManager
import json
# Generate the test payload
test_data = {
'test': ['this', 'is', 'a', 'test']
}
# Create the login details
username = 'admin'
password = 'password'
# Initialise the application
app = Flask(__name__)
# Update the secret key
app.config['SECRET_KEY'] = 'my_precious'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = int(3600)
# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"
jwt = JWTManager(app)
JWTManager(app)
  1. get_data (GET) — the endpoint that we will be accessing to return the mock data
# Create the login route - this is a POST
@app.route('/login', methods=['POST'])
def login():
auth = request.authorization

if not auth or not auth.username or not auth.password:
return make_response('Could not verify your details'.format(auth, auth.username, auth.password),
401,
{'WWW-authenticate': 'Login required'})

user = username

if not user:
return make_response('Could not verify your details', 401,
{'WWW-authenticate': 'Login required'})
# Return a token if the login is successful
if password == auth.password:
token = create_access_token(identity=auth.username)
return jsonify(token=token)
@app.route('/get_data', methods=['GET'])
@jwt_required
def get():
return jsonify(test_data)
# Run the application
if
__name__ == '__main__':
app.run(debug=True)
Photo by Caspar Camille Rubin on Unsplash

Testing the application using Postman

Now that our API is ready, we can run it by typing python main.py into the terminal.

# The authentication details
{
‘user’: ‘admin’,
‘password’: ‘password’
}
{"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTM2ODIyMjgsIm5iZiI6MTYxMzY4MjIyOCwianRpIjoiN2E3YzU1NjktYjU1Ni00Zjk5LThhYWQtYjZiNzUxMDk2NWQxIiwiZXhwIjoxNjEzNjg1ODI4LCJpZGVudGl0eSI6ImFkbWluIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.B2ukLRkZBfZHvcvoNw3MB6r1a5KlPww8Bnz9E6O2Ovo"}
# This is the message that we get
{
"test": ["this","is","a","test"]
}

Conclusion

That’s it for our very brief tutorial on creating our first REST API using Python and the Flask framework. Flask is a beginner friendly micro-framework that will help you build web applications that scale well. Using the steps laid out here, you will be well on your way to creating your own REST API.

An industrial engineer with a passion for data science.