top of page

Creating a Simple Student Information System With FastAPI


Simple  Student Information System With FastAPI

In the previous blog, we introduced FastAPI and set up a basic application. Now, let's take the next step and create a simple Student Information System With FastAPI. In this blog post, we'll walk through the process of creating a basic Student Information System using FastAPI. The provided code will define a FastAPI application that allows you to perform CRUD (Create, Read, Update, Delete) operations on a list of students stored in an in-memory database.


Step 1: Importing Required Modules


from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

We begin by importing the necessary modules. FastAPI is the main framework for building APIs, HTTPException is used to handle HTTP exceptions, BaseModel is a part of the Pydantic library for data validation, and List is used for typing when dealing with lists.


Step 2: Creating a FastAPI Application


app = FastAPI()

Here, we create an instance of the FastAPI class. This instance will be the main entry point for our application.


Step 3: Defining an In-Memory Database


db = []

We initialize an empty list called db to serve as our in-memory database for storing student information.


Step 4: Creating a Pydantic Model for Student


class Student(BaseModel):
    name: str
    age: int
    grade: str

A Student class is defined, inheriting from BaseModel. It specifies the data model for a student, including attributes like name, age, and grade.


Step 5: Adding a New Student


@app.post("/students/", response_model=Student)
def add_student(student: Student):
    db.append(student.dict())
    return student

This route allows us to add a new student to the database. The @app.post decorator specifies that this function handles HTTP POST requests. The response_model parameter indicates the expected response format, and the function appends the student's information to the in-memory database.


Step 6: Getting All Students


@app.get("/students/", response_model=List[Student])
def get_all_students():
    return db

This route retrieves all students from the database. The @app.get decorator indicates that this function handles HTTP GET requests, and the response_model parameter defines the expected response format as a list of students.


Step 7: Getting a Specific Student by ID


@app.get("/students/{id}", response_model=Student)
def get_student(id: int):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    return db[id]

This route retrieves a specific student from the database based on the provided ID. The @app.get decorator is used with a path parameter ({id}), and the function checks if the ID is within valid bounds. If not, it raises an HTTP exception with a 404 status code.


Step 8: Modifying a Student by ID


@app.put("/students/{id}", response_model=Student)
def modify_student(id: int, updated_student: Student):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    db[id] = updated_student.dict()
    return updated_student

This route allows us to update the information of a specific student. The @app.put decorator indicates that this function handles HTTP PUT requests. Similar to the previous route, it checks the validity of the provided ID and updates the corresponding student's information.


Step 9: Removing a Student by ID


@app.delete("/students/{id}", response_model=List[Student])
def remove_student(id: int):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    db.pop(id)
    return db

This route deletes a specific student from the database based on the provided ID. The @app.delete decorator is used, and the function checks the validity of the ID before removing the student. The updated list of students is then returned.


Complete Code


from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

# Create an instance of FastAPI
app = FastAPI()

# Define a simple in-memory database for student information
db = []

# Pydantic model for the Student
class Student(BaseModel):
    name: str
    age: int
    grade: str

# Route to add a new student
@app.post("/students/", response_model=Student)
def add_student(student: Student):
    db.append(student.dict())
    return student

# Route to get all students
@app.get("/students/", response_model=List[Student])
def get_all_students():
    return db

# Route to get a specific student by ID
@app.get("/students/{id}", response_model=Student)
def get_student(id: int):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    return db[id]

# Route to modify a student by ID
@app.put("/students/{id}", response_model=Student)
def modify_student(id: int, updated_student: Student):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    db[id] = updated_student.dict()
    return updated_student

# Route to remove a student by ID
@app.delete("/students/{id}", response_model=List[Student])
def remove_student(id: int):
    if id < 0 or id >= len(db):
        raise HTTPException(status_code=404, detail="Student not found")
    db.pop(id)
    return db

Run the FastAPI App:

In the terminal, execute the following command to start the FastAPI application using Uvicorn:

uvicorn main:app --reload

The --reload option enables automatic code reloading during development.

Note : all the code are saved in main.py file.


The URL "http://127.0.0.1:8000/students/" corresponds to the endpoint for retrieving all student information in the Student Information System created with FastAPI. In the database dont have any records. We need to first add records (Student information).



Accessing the API:

Open your web browser and navigate to http://127.0.0.1:8000 or http://localhost:8000 to see the FastAPI documentation provided by Swagger UI.


Exploring the API Documentation:

FastAPI generates interactive API documentation. Access Swagger documentation at http://127.0.0.1:8000/docs or ReDoc documentation at http://127.0.0.1:8000/redoc to explore and test API endpoints interactively.


Add Student Information

Let's first add the records to the database. Run this URL http://127.0.0.1:8000/docs. After that, this type of interface will open, as shown in the screenshot below.



After clicking on Add Student this page will open as shown in the below screenshot. To add the Student information click on the Try it out button.




After clicking on the 'Try it out' button, this page will open. Simply add the student information as demonstrated in the GIF below. Repeat this process as many times as needed to add the desired student information.



Get Student Information

After adding student information Run This url  "http://127.0.0.1:8000/students/". You can see the Student information in the web browser.



If you want to display specific student information in the web browser, run this URL 'http://127.0.0.1:8000/students/id'. For example, http://127.0.0.1:8000/students/2.




Update Student Information


To update student information, run this URL http://127.0.0.1:8000/docs. After that, click on the 'Try it out' button, then enter the ID. In the screenshot below, I entered 2. Fill in the information, and finally, click on the 'Execute' button. The information will be updated.



Updated Information




Remove Student Information

To Remove student information, run this URL http://127.0.0.1:8000/docs. After that, click on the 'Try it out' button, then enter the ID. In the screenshot below, I entered 2, and finally, click on the 'Execute' button. The information will be deleted.




Get all Student Information After removing the student information.




Now that you've completed the implementation of your basic Student Information System using FastAPI, you've taken a significant step in understanding how to build web APIs with this powerful framework. This simple application provides a foundation that you can expand upon to meet more complex requirements.

Tags:

Comments


bottom of page