Student Management REST API
Objective In this module, you will build a complete Student Management REST API using FastAPI without a database. By the end of this module, you will be able to:- Build REST APIs using FastAPI.
- Design request and response schemas using Pydantic.
- Store data using an in-memory dictionary.
- Implement CRUD operations.
- Search resources using query parameters.
- Handle API errors using
HTTPException. - Test REST APIs using Swagger UI.
Architecture
Implementation Roadmap
We will build the Student Management REST API from scratch using the following steps:- Create the Project Structure
- Initialize the FastAPI Application
- Create the Student Schemas
- Create the In-Memory Data Store
- Implement the Get All Students API
- Implement the Get Student by ID API
- Implement the Search Students API
- Handle Resource Not Found Errors Using HTTPException
- Implement the Create Student API
- Implement the Update Student API
- Implement the Delete Student API
- Test the Complete Application
Step 1: Create the Project Structure
Objective Create the project structure and install the required libraries for building the Student Management REST API. Instructions Create a new FastAPI project and install the required dependencies. Implementation Steps Step 1: Create a new project folder namedstudent-api.
Step 2: Open the project folder in your preferred editor (such as VS Code).
Step 3: Create and activate a Python virtual environment.
Step 4: Install the required libraries using uv.
Step 5: Create the project structure shown below.
Note: Create the folders and files using your preferred editor or your operating system’s file explorer. You may also use terminal commands if you are comfortable with the command line.Task Create the project structure and install the required dependencies for the Student Management REST API.
Solution
Solution
Create the ProjectCreate a Virtual EnvironmentActivate the Virtual EnvironmentmacOS / LinuxWindowsInstall the Required LibrariesCreate the Project StructureCreate the following folders and files.
- The project has been created successfully.
- The virtual environment has been activated.
- FastAPI and Uvicorn have been installed.
- The
appfolder has been created. - The
main.pyfile has been created. - The project structure matches the required layout.
Solution
Solution
Create a Initialize the Git repository and commit the project.
.gitignore file with the following content.Step 2: Initialize the FastAPI Application
Objective Initialize the FastAPI application and implement a simple Health Check endpoint. Instructions Open themain.py file and initialize the FastAPI application.
Implementation Steps
Step 1: Import the FastAPI class.
Step 2: Create a FastAPI application.
Step 3: Implement a Health Check endpoint.
Task
Initialize the FastAPI application and implement a Health Check endpoint.
Solution
Solution
Update
app/main.py- The application starts successfully.
- The Health Check endpoint is accessible.
- The Swagger UI loads successfully.
Solution
Solution
Step 3: Create the Student Schemas
Objective Create Pydantic schemas for validating API requests and formatting API responses. Instructions Create aschemas.py file and implement the required request and response schemas.
Implementation Steps
Step 1: Create a StudentBase schema containing the common student fields.
Step 2: Apply the required validations to each field.
Step 3: Create a StudentCreate schema by inheriting from StudentBase.
Step 4: Create a StudentUpdate schema with all fields optional.
Step 5: Create a StudentResponse schema by inheriting from StudentBase and adding the id field.
Task
Create the Student request and response schemas.
Solution
Solution
Create
app/schemas.py- The
StudentBaseschema has been created. - The
StudentCreateschema inherits fromStudentBase. - The
StudentUpdateschema contains optional fields. - The
StudentResponseschema inherits fromStudentBase. - All field validations have been implemented successfully.
Solution
Solution
Step 4: Create the In-Memory Data Store
Objective Create an in-memory data store for managing student records. Instructions Create adata.py file and initialize an in-memory dictionary with sample student records.
Implementation Steps
Step 1: Create an empty dictionary named students.
Step 2: Add a few sample student records to the dictionary.
Step 3: Use the student ID as the key and the student details as the value.
Task
Create the in-memory data store with sample student records.
Solution
Solution
Create
app/data.py- The
data.pyfile has been created. - The
studentsdictionary has been initialized. - The dictionary contains five student records.
- Each student has a unique ID.
Note: These sample records will be used to test the CRUD and Search APIs in the upcoming steps.Commit Changes
Solution
Solution
Step 5: Implement the Get All Students API
Objective Implement the Get All Students API to retrieve all student records from the in-memory data store. Instructions Open themain.py file and implement the Get All Students API.
Implementation Steps
Step 1: Import the StudentResponse schema.
Step 2: Create the GET /students endpoint.
Step 3: Retrieve all student records from the in-memory data store.
Step 4: Return the list of students.
Task
Implement the Get All Students API.
Solution
Solution
Update the imports in Implement the Get All Students endpoint
app/main.py/students endpoint.
Verify that:
- All student records are returned successfully.
- A 200 OK response is returned.
- The response contains all students stored in the in-memory data store.
Solution
Solution
Step 6: Implement the Get Student by ID API
Objective Implement the Get Student by ID API to retrieve a student using the student ID. Instructions Open themain.py file and implement the Get Student by ID API.
Implementation Steps
Step 1: Import the required classes.
Step 2: Define a validated path parameter for the student ID.
Step 3: Create the GET /students/{student_id} endpoint.
Step 4: Retrieve the student from the in-memory data store.
Step 5: Raise an HTTPException if the student does not exist.
Step 6: Return the student.
Task
Implement the Get Student by ID API.
Solution
Solution
Update the imports in Add the validated path parameterImplement the Get Student by ID endpoint
app/main.py/students/{student_id} endpoint.
Example
- The student details are returned successfully.
- A 200 OK response is returned.
- Requesting a non-existent student returns 404 Not Found.
- Providing a student ID less than or equal to 0 returns 422 Unprocessable Entity.
- The path parameter validation is visible in the Swagger UI.
Solution
Solution
Step 7: Implement the Search Students by Course API
Objective Implement the Search Students by Course API to retrieve students belonging to a specific course. Instructions Open themain.py file and implement the Search Students by Course API.
Implementation Steps
Step 1: Import the Query class.
Step 2: Define a validated query parameter for the course name.
Step 3: Create the GET /students/search endpoint.
Step 4: Search for students whose course matches the given course name.
Step 5: Return the matching students.
Task
Implement the Search Students by Course API.
Solution
Solution
Update the imports in Add the validated query parameterImplement the Search Students by Course endpoint
app/main.py/students/search endpoint.
Example
- Matching students are returned successfully.
- The search is case-insensitive.
- An empty list is returned when no matching students are found.
- The query parameter validation is visible in the Swagger UI.
Solution
Solution
Step 8: Implement the Create Student API
Objective Implement the Create Student API to add a new student to the in-memory data store. Instructions Open themain.py file and implement the Create Student API.
Implementation Steps
Step 1: Import the StudentCreate schema.
Step 2: Create the POST /students endpoint.
Step 3: Generate the next available student ID.
Step 4: Create a new student record.
Step 5: Add the student to the in-memory data store.
Step 6: Return the newly created student.
Task
Implement the Create Student API.
Solution
Solution
Update the imports in Implement the Create Student endpoint
app/main.py/students endpoint.
Request Body
- A new student is created successfully.
- A unique student ID is generated automatically.
- The student is added to the in-memory data store.
- A 201 Created response is returned.
Solution
Solution
Step 9: Implement the Update Student API
Objective Implement the Update Student API to modify an existing student record. Instructions Open themain.py file and implement the Update Student API.
Implementation Steps
Step 1: Import the StudentUpdate schema.
Step 2: Create the PUT /students/{student_id} endpoint.
Step 3: Retrieve the student from the in-memory data store.
Step 4: Raise an HTTPException if the student does not exist.
Step 5: Update only the fields provided in the request.
Step 6: Return the updated student.
Task
Implement the Update Student API.
Solution
Solution
Update the imports in Implement the Update Student endpoint
app/main.py/students/{student_id} endpoint.
Example
- The student record is updated successfully.
- Only the fields provided in the request are updated.
- Existing field values remain unchanged.
- Updating a non-existent student returns 404 Not Found.
Solution
Solution
Step 10: Implement the Delete Student API
Objective Implement the Delete Student API to remove a student from the in-memory data store. Instructions Open themain.py file and implement the Delete Student API.
Implementation Steps
Step 1: Create the DELETE /students/{student_id} endpoint.
Step 2: Retrieve the student from the in-memory data store.
Step 3: Raise an HTTPException if the student does not exist.
Step 4: Delete the student from the in-memory data store.
Step 5: Return a success message.
Task
Implement the Delete Student API.
Solution
Solution
Implement the Delete Student endpoint
/students/{student_id} endpoint.
Example
- The student is deleted successfully.
- A success message is returned.
- Deleting the same student again returns 404 Not Found.
Solution
Solution
Step 11: Test the Complete Student Management API
Objective Test all the REST APIs implemented in the Student Management application. Instructions Run the FastAPI application and test each endpoint using the Swagger UI. Implementation Steps Step 1: Start the FastAPI application. Step 2: Open the Swagger UI. Step 3: Test the Get All Students API. Step 4: Test the Get Student by ID API. Step 5: Test the Search Students by Course API. Step 6: Test the Create Student API. Step 7: Test the Update Student API. Step 8: Test the Delete Student API. Task Test all the APIs implemented in the Student Management application.Solution
Solution
Run the application.Open the Swagger UI.Test the APIs in the following order.
- All APIs execute successfully.
- The expected HTTP status codes are returned.
- Student records can be created, retrieved, updated, searched, and deleted.
- Invalid student IDs return 404 Not Found.
- Invalid path and query parameters return 422 Unprocessable Entity.
- All APIs are available in the Swagger UI.
Solution
Solution