How to Create an API in Python with Flask – Step by Step

In this tutorial, you will learn how to create an SDK from the scratch. We would build an API using Flask. This API would retrieve student data from a SQLite database and allow performing other operations such as PUT, POST and DELETE. Next, we would create an SDK that would perform the same operations.

At the end of this tutorial, you will understand the different between an SDK and an API.

  1. Create the Student Class
  2. Setup Your SQLite Database Connection
  3. Make a Get Request
  4. Get Record By ID
  5. POST Request
  6. Update Request
  7. DELETE Request

 

 Start a Server

This is the main function, that starts the server

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

Note: This has to be at the end of the file below all other functions in this file.

1. Create the Student Class

We would create a class the represents student details. This would be used to create Student object which we would store in our database.

The Student class is given below. Here we are using generating a UUID for each new student object create.

import uuid

class Student:

    def __init__(self, firstname, lastname, department):
        self.id = uuid.uuid4().hex
        self.firstname = firstname
        self.lastname = lastname
        self.department = department

    def __str__(self):
        return f'id:{self.id} ' \
               f'firstname: {self.firstname}; ' \
               f'Lastname: {self.lastname}; ' \
               f'Department: {self.department}'

 

2. Setup Your SQLite Database Connection

You need to simply import the sqlite3 and Flask module. You may also need to install Flask using pip

import sqlite3
from flask import *
import json
from student import Student

app = Flask(__name__)

def go_home():
    c = sqlite3.connect("student.db").cursor()
    c.execute("CREATE TABLE IF NOT EXISTS STUDENTS("
              "id TEXT, firstname TEXT, lastname TEXT, department TEXT)"
              )
    c.connection.close()

 

The function below returns a string for the ‘/’ route

@app.route('/', methods=['GET'])
def go_home():
    go_home()
    return 'Welcome to the Students API!'

 

3. Make a Get Request

We write a function to return a list of all records in the Students table.

@app.route('/getStudents', methods=['GET'])
def get_students():
    c = sqlite3.connect("student.db").cursor()
    c.execute("SELECT * FROM STUDENTS")
    data = c.fetchall()
    return jsonify(data)

 

4. Get Record By ID

The code below takes an student_id and returns the student’s record

@app.route('/getStudentById/<student_id>', methods=['GET'])
def get_student_by_id(student_id):
    c = sqlite3.connect("student.db").cursor()
    c.execute("SELECT * FROM STUDENTS WHERE id=?", (student_id,))
    data = c.fetchone()
    return json.dumps(data)

 

5. POST Request

To add a new student record to the database

@app.route('/addStudent', methods=['POST', 'GET'])
def add_student():
    db = sqlite3.connect("student.db")
    c = db.cursor()
    student = Student(request.form["firstname"],
                      request.form["lastname"],
                      request.form["department"]
                      )
    print(student)
    c.execute("INSERT INTO STUDENTS VALUES(?,?,?,?)",
              (student.id, student.firstname, student.lastname, student.department))
    db.commit()
    data = c.lastrowid
    return json.dumps(data)

 

6. Update Request

To update a student record we pass the student_id in a url and pass the student object in the request body. The request must be sent as x-www-form-urlencoded.

@app.route('/updateStudent/<student_id>', methods=['PUT'])
def update_student(student_id):
    db = sqlite3.connect("student.db")
    c = db.cursor()
    student = Student(request.form["firstname"],
                      request.form["lastname"],
                      request.form["department"]
                      )
    print(student)
    c.execute("UPDATE STUDENTS SET firstname = ?, lastname =?, department =? WHERE id=?",
              (student.firstname, student.lastname, student.department, student_id))
    db.commit()
    return json.dumps("Record was successfully updated")

 

7. DELETE Request

The function below deletes  a student record base on the Id in the url.

@app.route('/deleteStudent/<student_id>', methods=['DELETE'])
def delete_student(student_id):
    db = sqlite3.connect("student.db")
    c = db.cursor()
    c.execute("DELETE FROM STUDENTS WHERE id=?", (student_id,))
    db.commit()
    return json.dumps("Record was successfully deleted")

 

I hope you followed and did the procedure successfully. For more, please subscribe to my YouTube Channel.

kindsonthegenius

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *