Skip to content

Commit c6248c4

Browse files
travisjneumanclaude
andcommitted
feat: add 10 advanced concept diagram files (Mermaid)
HTTP, API, async, testing, generators, collections, functools/itertools, terminal, regex, and security — each with 2-4 focused Mermaid diagrams for GitHub rendering. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 482bc83 commit c6248c4

10 files changed

+1396
-0
lines changed

concepts/diagrams/api-basics.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Diagrams: API Basics
2+
3+
[Back to concept](../api-basics.md)
4+
5+
---
6+
7+
## REST API Architecture
8+
9+
A REST API sits between the client and the database. It receives HTTP requests, processes them, and returns JSON responses.
10+
11+
```mermaid
12+
flowchart LR
13+
subgraph CLIENTS ["Clients"]
14+
PY["Python script<br/>requests.get()"]
15+
WEB["Web browser<br/>fetch()"]
16+
MOB["Mobile app<br/>HTTP client"]
17+
end
18+
19+
subgraph API ["REST API Server"]
20+
ROUTER["Router<br/>Match URL to handler"]
21+
AUTH["Auth middleware<br/>Verify token/key"]
22+
HANDLER["Route handler<br/>Business logic"]
23+
SERIAL["Serializer<br/>Dict to JSON"]
24+
end
25+
26+
subgraph DATA ["Data Layer"]
27+
DB[("Database<br/>PostgreSQL")]
28+
CACHE[("Cache<br/>Redis")]
29+
end
30+
31+
PY -->|"HTTP request"| ROUTER
32+
WEB -->|"HTTP request"| ROUTER
33+
MOB -->|"HTTP request"| ROUTER
34+
35+
ROUTER --> AUTH
36+
AUTH --> HANDLER
37+
HANDLER --> DB
38+
HANDLER --> CACHE
39+
DB --> SERIAL
40+
SERIAL -->|"JSON response"| PY
41+
SERIAL -->|"JSON response"| WEB
42+
SERIAL -->|"JSON response"| MOB
43+
44+
style CLIENTS fill:#4a9eff,stroke:#2670c2,color:#fff
45+
style API fill:#cc5de8,stroke:#9c36b5,color:#fff
46+
style DATA fill:#51cf66,stroke:#27ae60,color:#fff
47+
```
48+
49+
## CRUD to HTTP Method Mapping
50+
51+
REST maps the four database operations (Create, Read, Update, Delete) to HTTP methods and URL patterns.
52+
53+
```mermaid
54+
flowchart TD
55+
subgraph CRUD ["Database Operation"]
56+
CREATE["CREATE<br/>Insert new row"]
57+
READ["READ<br/>Select rows"]
58+
UPDATE["UPDATE<br/>Modify row"]
59+
DELOP["DELETE<br/>Remove row"]
60+
end
61+
62+
subgraph HTTP ["HTTP Method + URL"]
63+
POST["POST /users<br/>Body: {name, email}"]
64+
GET1["GET /users<br/>List all"]
65+
GET2["GET /users/42<br/>Get one"]
66+
PUT["PUT /users/42<br/>Body: {name, email}"]
67+
DEL["DELETE /users/42<br/>No body"]
68+
end
69+
70+
subgraph RESPONSE ["Response"]
71+
R201["201 Created<br/>{id: 43, name: ...}"]
72+
R200L["200 OK<br/>[{id: 1}, {id: 2}, ...]"]
73+
R200O["200 OK<br/>{id: 42, name: ...}"]
74+
R200U["200 OK<br/>{id: 42, name: ...}"]
75+
R204["204 No Content"]
76+
end
77+
78+
CREATE --> POST --> R201
79+
READ --> GET1 --> R200L
80+
READ --> GET2 --> R200O
81+
UPDATE --> PUT --> R200U
82+
DELOP --> DEL --> R204
83+
84+
style CRUD fill:#ff922b,stroke:#e8590c,color:#fff
85+
style HTTP fill:#4a9eff,stroke:#2670c2,color:#fff
86+
style RESPONSE fill:#51cf66,stroke:#27ae60,color:#fff
87+
```
88+
89+
## API Request/Response Flow
90+
91+
Step-by-step sequence of a typical API call from Python using the `requests` library.
92+
93+
```mermaid
94+
sequenceDiagram
95+
participant Script as Python Script
96+
participant Lib as requests library
97+
participant API as API Server
98+
participant Logic as Route Handler
99+
100+
Script->>Lib: requests.post(url, json=data, headers=headers)
101+
Note over Lib: Serialize dict to JSON<br/>Add Content-Type header
102+
103+
Lib->>API: POST /users HTTP/1.1<br/>Authorization: Bearer eyJ...<br/>Content-Type: application/json<br/>{"name": "Alice", "email": "..."}
104+
105+
API->>API: Validate auth token
106+
API->>Logic: Call create_user handler
107+
108+
Note over Logic: Validate input<br/>Insert into database<br/>Build response
109+
110+
Logic-->>API: {"id": 43, "name": "Alice"}
111+
API-->>Lib: HTTP/1.1 201 Created<br/>Content-Type: application/json
112+
113+
Lib-->>Script: Response object
114+
115+
Note over Script: response.status_code → 201<br/>response.json() → {"id": 43, ...}
116+
```
117+
118+
## Authentication Token Flow
119+
120+
How bearer token authentication works: login once, then include the token with every request.
121+
122+
```mermaid
123+
sequenceDiagram
124+
participant Client as Python Client
125+
participant API as API Server
126+
participant DB as User Database
127+
128+
Note over Client: Step 1: Login to get a token
129+
130+
Client->>API: POST /auth/login<br/>{"username": "alice", "password": "s3cret"}
131+
API->>DB: Verify credentials
132+
DB-->>API: User found, password matches
133+
134+
Note over API: Generate JWT token<br/>Encode user ID + expiry
135+
136+
API-->>Client: 200 OK<br/>{"token": "eyJhbGci...", "expires_in": 3600}
137+
138+
Note over Client: Save the token
139+
140+
Note over Client: Step 2: Use token for API calls
141+
142+
Client->>API: GET /users/me<br/>Authorization: Bearer eyJhbGci...
143+
144+
Note over API: Decode token<br/>Verify signature<br/>Check expiry
145+
146+
API-->>Client: 200 OK<br/>{"id": 1, "name": "Alice", "role": "admin"}
147+
148+
Note over Client: Step 3: Token expires
149+
150+
Client->>API: GET /users/me<br/>Authorization: Bearer eyJhbGci...
151+
152+
Note over API: Token expired!
153+
154+
API-->>Client: 401 Unauthorized<br/>{"detail": "Token expired"}
155+
156+
Note over Client: Must login again<br/>to get a new token
157+
```
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
# Diagrams: Async Explained
2+
3+
[Back to concept](../async-explained.md)
4+
5+
---
6+
7+
## Event Loop State Machine
8+
9+
The event loop is the engine that runs async code. It cycles through coroutines, running whichever one is ready and pausing those that are waiting.
10+
11+
```mermaid
12+
stateDiagram-v2
13+
[*] --> Created: async def called
14+
Created --> Scheduled: asyncio.create_task()
15+
Scheduled --> Running: Event loop picks it up
16+
Running --> Suspended: Hits await (I/O, sleep)
17+
Suspended --> Scheduled: Awaited operation completes
18+
Running --> Done: Returns a value
19+
Running --> Error: Raises exception
20+
Done --> [*]
21+
Error --> [*]
22+
23+
note right of Running: Only ONE coroutine<br/>runs at a time
24+
note right of Suspended: Event loop runs<br/>other tasks while waiting
25+
```
26+
27+
## Async/Await Execution Flow
28+
29+
This shows how three concurrent tasks share a single thread. The event loop switches between them whenever one hits an `await`.
30+
31+
```mermaid
32+
sequenceDiagram
33+
participant Loop as Event Loop
34+
participant A as Task A (fetch user)
35+
participant B as Task B (fetch posts)
36+
participant C as Task C (fetch comments)
37+
38+
Note over Loop: asyncio.gather(A, B, C)
39+
40+
Loop->>A: Start Task A
41+
Note over A: Send HTTP request
42+
A-->>Loop: await response (I/O wait)
43+
44+
Loop->>B: Start Task B
45+
Note over B: Send HTTP request
46+
B-->>Loop: await response (I/O wait)
47+
48+
Loop->>C: Start Task C
49+
Note over C: Send HTTP request
50+
C-->>Loop: await response (I/O wait)
51+
52+
Note over Loop: All 3 requests in flight<br/>Loop waits for first completion
53+
54+
Note over B: Response arrives first!
55+
Loop->>B: Resume Task B
56+
Note over B: Parse JSON, return data
57+
B-->>Loop: Task B done
58+
59+
Note over A: Response arrives
60+
Loop->>A: Resume Task A
61+
Note over A: Parse JSON, return data
62+
A-->>Loop: Task A done
63+
64+
Note over C: Response arrives
65+
Loop->>C: Resume Task C
66+
Note over C: Parse JSON, return data
67+
C-->>Loop: Task C done
68+
69+
Note over Loop: All tasks complete<br/>Total time ≈ slowest task
70+
```
71+
72+
## Concurrent vs Parallel Execution
73+
74+
Concurrent means tasks take turns on one thread. Parallel means tasks literally run at the same time on multiple cores.
75+
76+
```mermaid
77+
flowchart TD
78+
subgraph SYNC ["Synchronous (blocking)"]
79+
direction LR
80+
S1["Task A<br/>1 sec"] --> S2["Task B<br/>1 sec"] --> S3["Task C<br/>1 sec"]
81+
end
82+
SYNC_TIME["Total: 3 seconds"]
83+
84+
subgraph CONCURRENT ["Concurrent (asyncio)"]
85+
direction LR
86+
CA["Task A starts"] -.->|"await"| CB["Task B starts"] -.->|"await"| CC["Task C starts"]
87+
CC -.->|"all complete"| CDONE["All done"]
88+
end
89+
CONC_TIME["Total: ~1 second<br/>One thread, interleaved"]
90+
91+
subgraph PARALLEL ["Parallel (multiprocessing)"]
92+
direction LR
93+
PA["Core 1: Task A"]
94+
PB["Core 2: Task B"]
95+
PC["Core 3: Task C"]
96+
end
97+
PAR_TIME["Total: ~1 second<br/>Multiple cores, truly simultaneous"]
98+
99+
SYNC --- SYNC_TIME
100+
CONCURRENT --- CONC_TIME
101+
PARALLEL --- PAR_TIME
102+
103+
style SYNC fill:#ff6b6b,stroke:#c92a2a,color:#fff
104+
style CONCURRENT fill:#51cf66,stroke:#27ae60,color:#fff
105+
style PARALLEL fill:#4a9eff,stroke:#2670c2,color:#fff
106+
style SYNC_TIME fill:#ff6b6b,stroke:#c92a2a,color:#fff
107+
style CONC_TIME fill:#51cf66,stroke:#27ae60,color:#fff
108+
style PAR_TIME fill:#4a9eff,stroke:#2670c2,color:#fff
109+
```
110+
111+
## When to Use Which Approach
112+
113+
A decision tree for choosing between sync, async, and multiprocessing.
114+
115+
```mermaid
116+
flowchart TD
117+
START["What kind of work?"] --> Q1{"Waiting on I/O?<br/>(network, files, DB)"}
118+
119+
Q1 -->|"Yes"| Q2{"Multiple I/O<br/>operations?"}
120+
Q1 -->|"No"| Q3{"CPU-heavy?<br/>(math, image processing)"}
121+
122+
Q2 -->|"Yes"| ASYNC["Use asyncio<br/>async/await + gather()"]
123+
Q2 -->|"No, just one"| SYNC_OK["Plain sync is fine<br/>requests.get()"]
124+
125+
Q3 -->|"Yes"| Q4{"Need shared memory?"}
126+
Q3 -->|"No"| SYNC["Plain sync is fine<br/>No concurrency needed"]
127+
128+
Q4 -->|"Yes"| THREAD["Use threading<br/>with locks"]
129+
Q4 -->|"No"| MULTI["Use multiprocessing<br/>One process per core"]
130+
131+
style ASYNC fill:#51cf66,stroke:#27ae60,color:#fff
132+
style SYNC_OK fill:#4a9eff,stroke:#2670c2,color:#fff
133+
style SYNC fill:#4a9eff,stroke:#2670c2,color:#fff
134+
style THREAD fill:#ffd43b,stroke:#f59f00,color:#000
135+
style MULTI fill:#cc5de8,stroke:#9c36b5,color:#fff
136+
```

0 commit comments

Comments
 (0)