This tutorial will focus majorly on basic introduction to API and building APIs using Flask . Please checkout my previous tutorial – Getting started with flask (Python)

Also read through what Application Programming Interfaces APIs are, how they are used and different types of APIs in the – What are APIs and how do they work blog

Introduction

Having talked about Flask and how to use Flask to build a web application, Its time to look at how can we build a simple Flask API using beginner level knowledge in Flask. Let’s take a look at how to crack this out!

The first step of doing this is creating virtual environment, installing flask and maybe let’s say building a simple hello world flask application. That’s where we are going to start. All these can be gotten here

run.py

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return 'hello world at Kenya-tech'


if __name__ == '__main__':
	app.run()

Next, we are going to change your our decorator to add the method type to our route

from flask import Flask
app = Flask(__name__)

@app.route('/get_hello', methods=['GET'])
def hello():
    return 'This is a content from Kenya-tech.com'

if __name__ == '__main__':
	app.run()

The methods  attributed define the type of request method the the endpoint expects and handles.

Lets add a few more endpoints to our app and see how it turns up:

from flask import Flask, jsonify, make_response, request

app = Flask(__name__)

user_list = []
@app.route('/get_hello', methods=['GET'])
def hello():
    return 'This is a content from Kenya-tech.com'

@app.route('/adduser', methods=['POST'])
def add_user():
    data = request.get_json()
    name = data['name']
    email = data['email']

    new_user = {
        "name": name,
        "email": email
    }

    user_list.append(new_user)
    return make_response(jsonify({
        "Message": "User added succesfully",
        "user name": new_user['name']
    }), 201)

@app.route('/users', methods=['GET'])
def users():
    return make_response(jsonify({
        "users": user_list,
        "status": "Ok"
    }), 200)

if __name__ == '__main__':
    app.run()

In the above code, we have added two more endpoints and they are for POST (adding a user) and GET (retrieving all users).

Also, note that make_response is used to beautifully define how our response should actually look like while jsonify converts our list (since return function cannot return a list but string only) into a json string. We have also added http status code into our return statements for our response

POST users Request and Response in postman

GET users Request and Response in postman

Please watch the full tutorial below and do not forget to subscribe to our channel.

LEAVE A REPLY

Please enter your comment!
Please enter your name here