Implementing a Salary Management API with Python

πŸš€ Preview

Implementing a Salary Management API with PythonImplementing a Salary Management API with Python

In-Depth Analysis of the Salary Management API

“Boss, stop using Excel for payroll! Today, we will use 50 lines of Python to build a RESTful little powerhouse that calculates better than the finance ladyβ€”FastAPI Salary Management API! It not only helps you store payroll in the cloud but also allows one-click account checking and instant retrieval of the latest records. Take a sip of coffee, and in three seconds, it’s done. The boss no longer has to worry about me secretly changing the numbers!”

πŸ“š Article Navigation (Well-structured and clear hierarchy)

  1. Introduction (already provided)
  2. Global Overview: Project Structure & Tech Stack
  3. Step-by-step Breakdown of 6+ Core Modulesβ‘  Entry File and FastApp Initializationβ‘‘ Pydantic Data Models (Request/Response)β‘’ Simulated Database and Global Variablesβ‘£ POST <span>/salary/submit</span> Salary Submissionβ‘€ GET <span>/salary/records</span> Full Queryβ‘₯ GET <span>/salary/latest</span> Latest Record⑦ Exception Handling and HTTPExceptionβ‘§ Startup Method & Swagger Documentation
  4. Conclusion: Key Points & Project Goals
  5. Bonus: Real-World Expansion Ideas

2️⃣ Global Overview: Project Structure & Tech Stack

salary_api/
β”œβ”€ main.py              # All code in this article
β”œβ”€ requirements.txt     # fastapi uvicorn
└─ README.md            # Optional documentation

Tech Stack in a nutshell:

  • FastAPI β€” Asynchronous high-performance web framework, automatically generates Swagger documentation;
  • Pydantic β€” Type validation and serialization, rejects dirty data;
  • Python 3.8+ β€” Native asynchronous support, plenty of syntactic sugar.

3️⃣ Step-by-step Breakdown of 6+ Core Modules

β‘  Entry File and FastApp Initialization

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from datetime import date
from typing import List, Optional

# Initialize FastAPI application
app = FastAPI(title="Salary Management API", version="1.0")

Hierarchical Analysis

  • Lines 1-4: Importing the essentials, standard three-part structure: framework, validation, date, generics.
  • Line 7: Instantiating the <span>FastAPI</span> object, which sets up the “company door” and labels it (title & version) for easy Swagger recognition.

β‘‘ Pydantic Data Models (Request/Response)

class SalarySubmit(BaseModel):
    amount: float              # Salary amount (required)
    date: date                 # Submission date (required)
    remark: Optional[str] = None  # Remark (optional)

class SalaryRecord(SalarySubmit):
    id: int                    # Record ID (included in response)

Hierarchical Analysis

  • SalarySubmit: Pure “input” model, the frontend/client only needs to fill in these three items;
    • <span>amount: float</span> β€” Directly rejects strings like “five thousand”, must be <span>5000.00</span>;
    • <span>date: date</span> β€” ISO format <span>2025-09-04</span>, Pydantic helps convert to Python date;
    • <span>Optional[str] = None</span> β€” Remark can be null, a blessing for the lazy.
  • SalaryRecord: Inherits + extends, adds database primary key <span>id</span>, used for returning to the frontend, reflecting the classic design of “response has more fields than request”.

β‘’ Simulated Database and Global Variables

salary_db: List[SalaryRecord] = []
next_id = 1

Hierarchical Analysis

  • salary_db: In-memory List, serves as the simplest “financial ledger”. It will be cleared upon process restart; for production, switch to PostgreSQL;
  • next_id: Auto-incrementing primary key, global variables may conflict under high concurrency, but it’s sufficient for the demo.

β‘£ POST <span>/salary/submit</span> Salary Submission

@app.post("/salary/submit", response_model=SalaryRecord)
async def submit_salary(salary: SalarySubmit):
    global next_id
    # 1) Parameter validation
    if salary.amount &lt;= 0:
        raise HTTPException(status_code=400, detail="Salary amount must be positive")

    # 2) Business logic processing
    record = SalaryRecord(id=next_id, **salary.dict())
    salary_db.append(record)
    next_id += 1

    # 3) Return response
    return record

Hierarchical Analysis

  1. Route Decorator
  • <span>@app.post(...)</span> registers the function in the FastAPI routing table;
  • <span>response_model=SalaryRecord</span> tells the framework “return this format”, automatically generating JSON Schema.
  • Function Signature
    • <span>async def</span>: Coroutine syntax, FastAPI natively supports asynchronous IO;
    • <span>salary: SalarySubmit</span>: Dependency injection, automatically deserialized by Pydantic.
  • Business Logic Trilogy
    • β‘  Parameter validation:<span>amount <= 0</span> directly raises a 400 error, avoiding “losing money for the boss”;
    • β‘‘ Data persistence: constructs <span>SalaryRecord</span> and appends to the list;
    • β‘’ Return: FastAPI automatically serializes the object to JSON.

    β‘€ GET <span>/salary/records</span> Full Query

    @app.get("/salary/records", response_model=List[SalaryRecord])
    async def get_salary_records():
        return salary_db
    

    Hierarchical Analysis

    • Extremely simple read operation, directly returns the “ledger” to the frontend.
    • Type hint <span>List[SalaryRecord]</span> allows Swagger documentation to generate array examples, frontend developers will call it professional.

    β‘₯ GET <span>/salary/latest</span> Latest Record

    @app.get("/salary/latest", response_model=SalaryRecord)
    async def get_latest_salary():
        if not salary_db:
            raise HTTPException(status_code=404, detail="No salary records available")
        return max(salary_db, key=lambda x: x.date)
    

    Hierarchical Analysis

    • Empty Database Protection: <span>if not salary_db</span> raises a 404 in advance, avoiding <span>max()</span><span> crashing.</span>
    • max + lambda: One line of code finds the most recent date record, very Pythonic.
    • Response Model: still <span>SalaryRecord</span>, maintaining consistency in interface contracts.

    ⑦ Exception Handling and HTTPException

    Although there are only two instances of <span>raise HTTPException</span> in the code, FastAPI automatically translates exceptions into JSON, for example:

    {
      "detail": "Salary amount must be positive"
    }
    

    Hierarchical Analysis

    • Semantic Status Codes: 400 client error, 404 resource not found;
    • Unified Format: The frontend only needs to access the <span>detail</span> field to show a toast, reducing communication costs.

    β‘§ Startup Method & Swagger Documentation

    # 1. Install dependencies
    pip install fastapi uvicorn
    
    # 2. Run the service
    uvicorn main:app --reload
    

    Access the browser at <span>http://127.0.0.1:8000/docs</span> to see the interactive Swagger:

    • On the left, <span>/salary/submit</span> β†’ Try it out β†’ Input JSON and click Execute;
    • On the right, automatically generated <span>curl</span> command, supports export to Postman.

    4️⃣ Conclusion: Key Points & Project Goals

    Dimension Key Points Goal Achievement
    Framework FastAPI routing, dependency injection, asynchronous Write high-performance interfaces in 5 minutes
    Validation Pydantic models, Optional fields Reject dirty data, zero disputes between frontend and backend
    Data In-memory List simulation, global auto-increment ID Quick prototyping, painless migration to SQL later
    Exceptions HTTPException, status codes RESTful semantics, no surprises for the frontend
    Documentation Swagger/OpenAPI auto-generation No need to write a line of Markdown, interfaces are still understandable
    Deployment uvicorn hot reload 300% increase in development efficiency

    5️⃣ Bonus: Real-World Expansion Ideas

    1. Database: SQLAlchemy + SQLite/MySQL, switch with three lines of code;
    2. Authentication: OAuth2 password flow, financial data must be encrypted;
    3. Pagination: <span>limit/offset</span><span> to avoid returning 100,000 records at once;</span>
    4. Statistical Reports: Add <span>/salary/report?month=2025-09</span>, aggregate total for the month;
    5. Frontend Integration: Vue + Axios can be set up in 5 minutes, allowing the boss to view salaries in real-time on their phone.

    The full text is over 3000 words, guiding you step by step from 0 to 1 to create a runnable, viewable, and salary-increasing little powerhouse. Hurry up and throw the code into the terminal, let the boss experience the smoothness of “cloud finance”!

    Click 【Follow + Collect】 to get the latest practical code examples

    Python 20-day learning plan

    7-day Python learning plan

    Python implementation of similar Postman calls

    Python implementation of LAN file sharing tool

    Python implementation of online calligraphy generator

    Python implementation of leaf carving images

    Python ID photo generator with multiple sizes

    Python implementation of background replacement for portrait ID photos

    Python development of custom EXE packaging program

    Python implementation of seal generator

    Python implementation of simple rent summary calculator

    Python implementation of Nezha typing balloon game

    Python implementation of batch certificate production factory

    Python one-click generation of stamped Word leave requests

    Python quick PS image color picker and other editors

    Python implementation of batch certificate production factory

    Python quick PS image color picker and other editors

    Python implementation of custom color picker

    Python implementation of automatic watercolor sketch

    Python implementation of creative drawing board code

    Using Python to create a Chinese character stroke query tool: from GUI interface to stroke animation implementation

    Python implementation of meme maker

    Python implementation of Chinese chess mini-game

    Python implementation of seal generator

    Python simulation of Jinshan typing software

    Python super practical Markdown to rich text tool β€” full code analysis

    Python implementation of snake game source code analysis

    Python implementation of QR code generation

    Python implementation of video player

    Python implementation of seal generator

    Python implementation of online seal making

    Python + AI to implement a simple intelligent voice assistant

    Python implementation of simple notepad

    Python implementation of Markdown to HTML tool code

    Python implementation of creative drawing board code

    Python implementation of simple drawing tool code

    Python implementation of video player

    Python implementation of simple notepad

    Python implementation of the connect-the-dots game code analysis

    Python implementation of simple computer process manager

    A super practical tool in Python – word frequency statistics tool

    Python simple crawler weather tool

    Python scheduled task reminder tool

    Python “Guess the Number Game Code Analysis”

    Python “Simple Calculator Code Analysis”

    Python + AI online document generation assistant

    Python “Password Generator Code Analysis”

    Python | + AI to implement a simple intelligent voice assistant

    Python implementation of simple drawing tool code

    Python implementation of Markdown to HTML

    Python implementation of video player

    Python implementation of the connect-the-dots game code analysis

    Python implementation of volcanic AI call to generate stories

    Python implementation of Doubao AI call to generate stories

    Python implementation of simple notepad

    Python implementation of simple computer process manager

    【Practical 1】

    1. Python: QR code generator

    2. Python-pgame implementation of maze

    3. Python – implementation of weather clock assistant

    4. Python-QrCode implementation of various QR codes

    5. Python-pyglet implementation of HarmonyOS clock

    6. Python-pickle parsing to get WeChat friend information

    7. Python-wxPy initial version implementation of WeChat message bombing

    8. Python implementation of Eight Trigrams Starry Sky Clock

    9. Python implementation of National Day red flag avatar effect

    10. Python-PIL implementation of adding icons to specified positions on images

    【Practical 2】

    1. Python-wxPy initial version implementation of WeChat message bombing

    2. Python-PIL library Image class parsing

    3. Python-tlinter implementation of simple student management system

    4. Python-itChat implementation of WeChat message push

    5. Python implementation of Pdf to Word

    6. Python – implementation of automatic couplet generation assistant

    7. Py2Exe another way of packaging

    8. Python-tts generating voice conversion assistant

    9. python-win32 etc. to automatically add exe to computer startup options

    10. python implementation of desktop video recording

    11. PySimpleGUI-checkboxPython implementation of image cropping into a grid

    12. python packaging into exe file

    13. Python-faker generating virtual data

    14. python implementation of player Python-FastApi simple implementation

    15. python crawling Douban movie reviews

    16. Python crawling public account article collection

    【Practical 3】

    1. python implementation of simple flower order

    2. python – get images to guess idioms

    3. python-menu menu implementation

    4. Python-pySimpleGUI implementation of interface

    5. Python – color image conversion to white outline

    6. Python-moviepy – implementation of audio and video player

    7. Python operating SQLite database

    8. Python-PySimpleGUI implementation of menu

    9. python-Tkinter implementation of personalized signature

    10. Python-WordCloud cloud word map

    11. Python-customTkinter usage

    12. Python-tkinter (down)

    13. Python-tkinter (middle)

    14. python-tkinter (1)

    15. Python implementation of video assistant

    【Practical 4】

    1. Python implementation of video assistant

    2. Python-flask-1: building the main page

    3. Python ttkbootstrap interface

    4. python-PyQt5 implementation of image display and simple reader

    5. Configuring Qt Designer and Pyuic on Pycharm

    6. Python PIL implementation of cropping and generating images of one inch and two inches

    7. Python crawling Jinshan dictionary query results

    8. python implementation of generating personalized QR codes

    9. AI human-computer battle version of Gomoku game (AI + pygame implementation)

    10. python implementation of garbage classification query tool

    11. python – implementation of menu

    12. Python domain application: automated testing

    13. Python domain application: web development

    14. Python domain application: automated operations

    Implementing a Salary Management API with Python

    Implementing a Salary Management API with Python

    Complete Code

    from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom datetime import datefrom typing import List, Optional# Initialize FastAPI applicationapp = FastAPI(title="Salary Management API", version="1.0")# Data model definition (request/response format)class SalarySubmit(BaseModel):amount: float  # Salary amount (required)date: date  # Submission date (required)remark: Optional[str] = None  # Remark (optional)class SalaryRecord(SalarySubmit):id: int  # Record ID (included in response)# Simulated database (can be replaced with a real database in actual projects)salary_db: List[SalaryRecord] = []next_id = 11. Submit salary (POST request)@app.post("/salary/submit", response_model=SalaryRecord)async def submit_salary(salary: SalarySubmit):global next_id# Validate salary amount is positiveif salary.amount &lt;= 0:raise HTTPException(status_code=400, detail="Salary amount must be positive")# Save recordrecord = SalaryRecord(id=next_id, **salary.dict())salary_db.append(record)next_id += 1return record2. Query all salary records (GET request)@app.get("/salary/records", response_model=List[SalaryRecord])async def get_salary_records():return salary_db3. Query latest salary record (GET request)@app.get("/salary/latest", response_model=SalaryRecord)async def get_latest_salary():if not salary_db:raise HTTPException(status_code=404, detail="No salary records available")return max(salary_db, key=lambda x: x.date)# Startup instructions:1. Install dependencies: pip install fastapi uvicorn2. Run the service: uvicorn main:app --reload3. Access documentation: http://127.0.0.1:8000/docs

    Leave a Comment