Skip to content

API Endpoints - GET & POST#10

Open
d3shira wants to merge 4 commits into
mainfrom
API-endpoints
Open

API Endpoints - GET & POST#10
d3shira wants to merge 4 commits into
mainfrom
API-endpoints

Conversation

@d3shira

@d3shira d3shira commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator
  • api endpoints using schemas (via pydantic) for data validation (what fields of the model we want to work with)
  • simple html table via index.html file to show the table in the web
# FastAPI Fullstack Architecture Overview

This document explains the structure of the project, including the database connection, models, schemas, API routes, templates, and how all the components work together.

---

# 1. Database Connection

**File:** `database/connection.py`

This file is responsible for connecting the application to the PostgreSQL database using SQLAlchemy.

## Database Configuration

```python
DATABASE_URL = "postgresql://postgres:1234@localhost:5433/salary_prediction"
```

This connection string contains:

- **Host:** `localhost`
- **Port:** `5433`
- **Database:** `salary_prediction`
- **Username:** `postgres`
- **Password:** `1234`

## SQLAlchemy Engine

```python
engine = create_engine(DATABASE_URL)
```

The engine manages the connection between the application and PostgreSQL.

## Database Sessions

```python
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine,
)
```

`SessionLocal` creates database sessions that are used throughout the application to execute queries.

The session configuration:

- `autocommit=False` – changes must be committed manually.
- `autoflush=False` – changes are not automatically written before queries.
- `bind=engine` – connects sessions to the configured database engine.

## Connection Test

When the application starts, a simple query (`SELECT 1`) is executed to verify that the database connection is working correctly.

---

# 2. Database Models

**File:** `database/models.py`

The project uses SQLAlchemy ORM with `DeclarativeBase` to define database tables as Python classes.

## Department

Represents the `departments` table.

Fields:

- `id` (Primary Key)
- `name`

## Employee

Represents the `employees` table.

Fields:

- `id`
- `first_name`
- `last_name`
- `email`
- `department_id`

`department_id` is a foreign key referencing `departments.id`.

## EmployeeRecord

Represents the `employee_records` table.

Fields:

- `id`
- `employee_id`
- `exam_score`
- `years_exp`
- `salary`

`employee_id` is a foreign key referencing `employees.id`.

## Table Relationships

The database follows this structure:

```
Department

    └── Employee

            └── EmployeeRecord
```

This means:

- A department can have multiple employees.
- Each employee belongs to one department.
- Each employee can have one or more salary records.

---

# 3. Pydantic Schemas

**File:** `schemas/employee.py`

Pydantic schemas define the data accepted by the API and the format of the responses returned to the client.

## Department Schemas

### `DepartmentCreate`

Used when creating a department.

Required field:

- `name`

### `DepartmentSchema`

Returned by the API after a department is created.

Fields:

- `id`
- `name`

---

## Employee Schemas

### `EmployeeCreate`

Used when creating an employee.

Fields:

- `first_name`
- `last_name`
- `email` *(optional)*
- `department_id` *(optional)*

### `EmployeeSchema`

Returned by the API.

Fields:

- `id`
- `first_name`
- `last_name`
- `email`
- `department_id`

---

## Employee Record Schemas

### `EmployeeRecordCreate`

Used when creating a salary record.

Fields:

- `employee_id`
- `exam_score`
- `years_exp`
- `salary`

### `EmployeeRecordSchema`

Returned by the API.

Fields:

- `id`
- `employee_id`
- `exam_score`
- `years_exp`
- `salary`

## Why Separate Schemas?

Using separate schemas for requests and responses provides a clear separation of responsibilities:

- Request schemas define what the client is allowed to send.
- Response schemas define what the API returns.

This improves validation, readability, and maintainability.

---

# 4. FastAPI Application

**File:** `main.py`

This file creates the FastAPI application and defines all routes.

## Application Setup

```python
app = FastAPI()
```

Creates the FastAPI application instance.

## Templates

```python
templates = Jinja2Templates(directory="app/templates")
```

Loads HTML templates that are rendered for the frontend.

---

# 5. Database Session Dependency

The application uses a dependency to provide a database session for each request.

```python
def get_db():
```

For every request:

1. A new database session is created.
2. The session is passed to the route.
3. The session is automatically closed after the request finishes.

This is the standard SQLAlchemy pattern used with FastAPI.

---

# 6. Page Routes (GET)

These routes render HTML pages using Jinja2 templates.

## `/`

Displays the home page (`index.html`).

## `/departments`

- Retrieves all departments.
- Renders `departments.html`.

## `/employees`

- Retrieves departments and employees.
- Renders `employees.html`.

## `/records`

- Retrieves employees and employee records.
- Renders `records.html`.

Each route queries the database and passes the retrieved data to the corresponding template.

---

# 7. API Routes (POST)

These routes receive JSON data, validate it using Pydantic, and write it to the database.

## `POST /departments`

- Accepts `DepartmentCreate`
- Creates a new department
- Returns `DepartmentSchema`

---

## `POST /employees`

- Accepts `EmployeeCreate`
- Validates the provided department
- If no department is supplied, the application uses (or creates) a default **General** department
- Returns `EmployeeSchema`

---

## `POST /records`

- Accepts `EmployeeRecordCreate`
- Verifies that the employee exists
- Creates a salary record
- Returns `EmployeeRecordSchema`

---

# 8. Frontend Templates

The application contains four templates:

- `index.html`
- `departments.html`
- `employees.html`
- `records.html`

Each page contains:

- Navigation links
- A form for creating new records
- JavaScript that submits data using `fetch()`

The workflow is:

1. The page loads existing data using a GET route.
2. The user submits the form.
3. JavaScript sends a POST request containing JSON.
4. FastAPI validates the request.
5. SQLAlchemy stores the data.
6. The API returns a JSON response.
7. The page updates the displayed data without reloading.

---

# 9. Application Architecture

The project is organized into four layers:

## Database Layer

- `connection.py`
- `models.py`

Responsible for database connectivity and table definitions.

## Validation Layer

- `schemas/`

Defines request and response models using Pydantic.

## Application Layer

- `main.py`

Contains the API endpoints and business logic.

## Presentation Layer

- `templates/`
- JavaScript

Responsible for rendering pages and interacting with the backend.

---

# 10. Running the Application

Assuming the project root is `stupid_project`:

## Start PostgreSQL

Make sure PostgreSQL is running with:

- Host: `localhost`
- Port: `5433`
- Database: `salary_prediction`
- Username: `postgres`
- Password: `1234`

## Start the FastAPI Server

```bash
uvicorn backend.app.main:app --reload
```

## Open the Application

Navigate to:

```
http://127.0.0.1:8000/
```

Available pages:

- `/`
- `/departments`
- `/employees`
- `/records`

---

# 11. End-to-End Request Flow

The application follows this workflow:

```
Browser


GET Request


FastAPI Route


Database Query (SQLAlchemy)


Jinja2 Template


HTML Page

User submits form


POST Request (JSON)


Pydantic Validation


SQLAlchemy


PostgreSQL


JSON Response


JavaScript updates the page
```

---

# 12. Technologies Used

| Technology | Purpose |
|------------|---------|
| FastAPI | Web framework and API routing |
| SQLAlchemy | ORM for interacting with PostgreSQL |
| Pydantic | Request validation and response serialization |
| Jinja2 | HTML template rendering |
| PostgreSQL | Relational database |
| Uvicorn | ASGI server for running the application locally |

---

# Summary

The project follows a standard full-stack architecture:

- **Database models** define the database tables.
- **Pydantic schemas** validate incoming requests and format API responses.
- **FastAPI routes** handle requests and coordinate interactions between the frontend and the database.
- **Jinja2 templates** render the user interface.
- **JavaScript** sends asynchronous requests to the backend and updates the page dynamically.
- **SQLAlchemy** manages all communication with the PostgreSQL database.

@d3shira d3shira changed the title API Endpoints - GET API Endpoints - GET & POST Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant