Creating APIs with Python Flask

Cho Zin Thet
3 min readSep 17, 2021

--

Application Programming Interface

What is API ?

Application Programming Interface (API) is an application interface that allows two applications to communicate each other. Creating API is creating routes(endpoint and parameter) and response back some data. Means that other application can use our service with requesting API. RESTFul (Representational state transfer) is style or rules of creating APIs.

Example of API and HTTP request, response

For example, there is application A and application B. Application A wants weather forecast data to show user the weather data in application. Application B have weather data and create some routes(api routes) to allow other application to use weather data(services). Then application A request application B (creating HTTP request) and application B response back requested weather data to application A. Then application A can use data to show user the weather data in application.

Creating RESTFUL APIs

RESTFUL ➜ Representational state transfer

Representational

  • use suitable request method (GET, POST, PUT, PATCH, DELETE)
  • represent resources in url

Stateful protocol and Stateless protocol

Mostly use in authentication, user login. Server record data or not when client request to server. Next time client request to server, server remember the user.

Stateful

store information in server and waiting for the next request. Session make stateful protocols. Example session authentication, user state store in server memory. In flask, flask-login use cookies-server authentication.

Stateless

No information remain in server when communicate client and server. when client request to server, server create jwt with user information and response jwt back to client. Client store in cookies or localstorage in browser. Every time requesting to server, client pass that token to server. Server only check token(jwt) and no need to store user information to server memory. Token authentication are stateless. You can test python json web token.

Creating API with Flask

  • use module jsonify to response json data

Get all posts.

  • method ➜ GET
  • represent resource ➜ posts
from flask import Flask, jsonify@app.route("/posts/all", methods=['GET'])
def get_all_post():
return jsonify(posts)

Create new post

  • method ➜ POST
  • represent resource ➜ posts
@app.route("/posts/", methods=['POST'])
def add():
new_post = Post(
title = request.form["title"],
content = request.form["content"],
)
db.session.add(new_post)
db.session.commit()
return jsonify({"success": "Successfully added."})

Update post

  • method ➜ PUT (update all data that match with id)
  • represent resource ➜ posts
@app.route("/posts/<id>", methods=['PUT'])
def update(id):
# get post that match with requested id
post = Post.query.get(request.args['id'])

if post:
# update data
post.title = request.form['title']
post.content = request.form['content']
db.session.add(post)
db.session.commit()
return jsonify({"success": "Successfully updated"})
else:
return jsonify({"error": "not found id"})

Update post

  • method ➜ PATCH (update some data that match with id)
  • represent resource ➜ posts
@app.route("/posts/<id>", methods=['PATCH'])
def update_title(id):
post = Post.query.get(id)
if post:
try:
# get title parameter in url
post.title = request.args["title"]
except:
return jsonify({"error": "you must pass title as parameter"})
else:
db.session.commit()
return jsonify({"success": "Successfully updated"})
else:
return jsonify({"error": "not found id"})

Delete post

  • method ➜ DELETE
  • represent resource ➜ posts
@app.route("/posts/<id>", methods=['DELETE'])
def delete(id):
post = Post.query.get(id)
db.session.delete(cafe)
db.session.commit()
return jsonify({"success": "successfully deleted"})
else:
return jsonify({"error": "not found id"})

--

--

Cho Zin Thet
Cho Zin Thet

Written by Cho Zin Thet

Learning javascript and web-development

No responses yet