π Preview


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)
- Introduction (already provided)
- Global Overview: Project Structure & Tech Stack
- 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 - Conclusion: Key Points & Project Goals
- 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 <= 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
- 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.
<span>async def</span>: Coroutine syntax, FastAPI natively supports asynchronous IO;<span>salary: SalarySubmit</span>: Dependency injection, automatically deserialized by Pydantic.
- β 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
- Database: SQLAlchemy + SQLite/MySQL, switch with three lines of code;
- Authentication: OAuth2 password flow, financial data must be encrypted;
- Pagination:
<span>limit/offset</span><span> to avoid returning 100,000 records at once;</span> - Statistical Reports: Add
<span>/salary/report?month=2025-09</span>, aggregate total for the month; - 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γ
-
Python: QR code generator
-
Python-pgame implementation of maze
-
Python – implementation of weather clock assistant
-
Python-QrCode implementation of various QR codes
-
Python-pyglet implementation of HarmonyOS clock
-
Python-pickle parsing to get WeChat friend information
-
Python-wxPy initial version implementation of WeChat message bombing
-
Python implementation of Eight Trigrams Starry Sky Clock
-
Python implementation of National Day red flag avatar effect
-
Python-PIL implementation of adding icons to specified positions on images
γPractical 2γ
-
Python-wxPy initial version implementation of WeChat message bombing
-
Python-PIL library Image class parsing
-
Python-tlinter implementation of simple student management system
-
Python-itChat implementation of WeChat message push
-
Python implementation of Pdf to Word
-
Python – implementation of automatic couplet generation assistant
-
Py2Exe another way of packaging
-
Python-tts generating voice conversion assistant
-
python-win32 etc. to automatically add exe to computer startup options
-
python implementation of desktop video recording
-
PySimpleGUI-checkboxPython implementation of image cropping into a grid
-
python packaging into exe file
-
Python-faker generating virtual data
-
python implementation of player Python-FastApi simple implementation
-
python crawling Douban movie reviews
-
Python crawling public account article collection
γPractical 3γ
-
python implementation of simple flower order
-
python – get images to guess idioms
-
python-menu menu implementation
-
Python-pySimpleGUI implementation of interface
-
Python – color image conversion to white outline
-
Python-moviepy – implementation of audio and video player
-
Python operating SQLite database
-
Python-PySimpleGUI implementation of menu
-
python-Tkinter implementation of personalized signature
-
Python-WordCloud cloud word map
-
Python-customTkinter usage
-
Python-tkinter (down)
-
Python-tkinter (middle)
-
python-tkinter (1)
-
Python implementation of video assistant
γPractical 4γ
-
Python implementation of video assistant
-
Python-flask-1: building the main page
-
Python ttkbootstrap interface
-
python-PyQt5 implementation of image display and simple reader
-
Configuring Qt Designer and Pyuic on Pycharm
-
Python PIL implementation of cropping and generating images of one inch and two inches
-
Python crawling Jinshan dictionary query results
-
python implementation of generating personalized QR codes
-
AI human-computer battle version of Gomoku game (AI + pygame implementation)
-
python implementation of garbage classification query tool
-
python – implementation of menu
-
Python domain application: automated testing
-
Python domain application: web development
-
Python domain application: automated operations


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 <= 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