The Student API is a RESTful service for managing student records. It allows you to create, retrieve, update, and delete student data stored in a SQLite database. The API is built using Go and follows best practices for configuration, error handling, and validation.
student-api/
├── cmd/
│ └── students-api/
│ └── main.go
├── internal/
│ ├── config/
│ ├── http/
│ │ └── handlers/
│ │ └── student/
│ │ └── students.go
│ ├── response/
│ ├── storage/
│ │ └── sqlite/
│ └── types/
└── go.mod / go.sum
File: cmd/students-api/main.go
- Loads configuration.
- Initializes SQLite storage.
- Sets up HTTP routes for student operations.
- Handles graceful shutdown on OS signals.
File: internal/config/config.go
- Loads environment variables and configures the server/database.
File: internal/http/handlers/student/students.go
Defines handlers for:
- POST
/api/students: Create a new student. - GET
/api/students/{id}: Get a student by ID. - GET
/api/students: List all students. - PUT
/api/students/{id}: Update a student. - DELETE
/api/students/{id}: Delete a student.
Each handler:
- Logs the request.
- Validates input using Go's
validatorpackage. - Returns JSON responses with appropriate status codes.
File: internal/storage/sqlite/sqlite.go
- Implements CRUD operations for students using SQLite.
- Provides methods like
New,GetStudentById,GetStudents,UpdateStudent,DeleteStudent.
File: internal/types/types.go
Defines the Student struct:
type Student struct {
ID string `json:"id" validate:"required"`
Name string `json:"name" validate:"required,min=2,max=100"`
Age int `json:"age" validate:"required,min=1,max=150"`
Grade string `json:"grade" validate:"required,oneof=A B C D E F"`
}- Validation: Only grades
A,B,C,D,E,Fare accepted.
File: internal/response/response.go
- Utility functions for writing JSON responses and error messages.
- POST
/api/students - Body:
{ "id": "1", "name": "Anurag", "age": 27, "grade": "A" } - Validation: All fields required. Grade must be one of
A B C D E F.
- GET
/api/students/{id}
- GET
/api/students
- PUT
/api/students/{id} - Body: Same as create.
- DELETE
/api/students/{id}
- All errors are returned as JSON:
{ "status": "error", "error": "Error message" } - Validation errors specify the field and reason.
- The server listens for
SIGINT/SIGTERMand shuts down gracefully, closing the database connection.
- Uses
log/slogfor structured logging of requests and errors.
- Grade Validation: Only
A,B,C,D,E,Fare accepted. To allowA+, update the validation tag intypes.Student. - Database: Uses SQLite for persistence.
- Extensibility: The modular structure allows easy addition of new features.
- Configure environment variables (see
internal/config). - Run the server:
go run cmd/students-api/main.go
- Use any HTTP client (e.g., curl, Postman) to interact with the API.
- Follow Go best practices.
- Write unit tests for new features.
- Document new endpoints and types.
For further details, review the code in each folder as described above.