Learn how to create an API in Python with Flask step by step, using SQLite to build GET, POST, PUT, and DELETE endpoints for student data.
TL;DR
-
Create a Student class to represent student data.
-
Connect the Flask API to a SQLite database.
-
Build GET endpoints to retrieve all students or a student by ID.
-
Add POST and PUT endpoints to create and update student records.
-
Add a DELETE endpoint to remove student records from the database.
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.
- Create the Student Class
- Setup Your SQLite Database Connection
- Make a Get Request
- Get Record By ID
- POST Request
- Update Request
- 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.
FAQs
How do I create an API in Python?
You can create an API in Python using Flask by defining routes that handle HTTP requests and connect to your application’s data or database.
What is Flask used for in this tutorial?
Flask is used to create the REST API and define endpoints for performing operations on student records.
How does the API connect to the SQLite database?
The tutorial uses Python’s sqlite3 module to connect to the SQLite database and execute SQL queries for retrieving and modifying student records.
What HTTP methods are implemented in the Python API?
The API implements GET, POST, PUT, and DELETE methods for retrieving, creating, updating, and deleting student records.
What is the difference between an API and an SDK?
An API provides endpoints that applications can communicate with, while an SDK provides reusable functions and tools that developers can use to interact with or build applications.
Final Thoughts
Creating an API in Python with Flask is a practical way to understand how REST APIs work. This tutorial demonstrates the basic operations needed to manage student data, from retrieving records to creating, updating, and deleting them.
The project also provides a foundation for the next step: building an SDK that performs the same operations. Together, the API and SDK tutorials help demonstrate the difference between exposing functionality through an API and providing reusable development tools through an SDK.
[…] tutorial follows from the previous tutorial on How to Build an API in Python. You can review it as well. In that tutorial, we build an API for managing Student data (performing […]