-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMasterClass_AppDevelopment.html
More file actions
2025 lines (1771 loc) · 88.3 KB
/
Copy pathMasterClass_AppDevelopment.html
File metadata and controls
2025 lines (1771 loc) · 88.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MasterClass: How Modern Applications Are Built</title>
<style>
/* Import Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400;700;900&family=Source+Code+Pro:wght@400;600&family=Inter:wght@400;500;600;700&display=swap');
/* CSS Variables */
:root {
--primary: #1a365d;
--secondary: #2c5282;
--accent: #ed8936;
--text: #2d3748;
--text-light: #4a5568;
--bg: #ffffff;
--bg-alt: #f7fafc;
--border: #e2e8f0;
--code-bg: #1a202c;
--success: #38a169;
--warning: #d69e2e;
}
/* Reset & Base */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 11pt;
line-height: 1.7;
color: var(--text);
background: var(--bg);
max-width: 850px;
margin: 0 auto;
padding: 40px;
}
/* Print Styles */
@media print {
body {
padding: 0;
font-size: 10pt;
}
.page-break {
page-break-before: always;
}
.no-break {
page-break-inside: avoid;
}
h1, h2, h3 {
page-break-after: avoid;
}
pre, table, .diagram-box {
page-break-inside: avoid;
}
}
/* Cover Page */
.cover {
text-align: center;
padding: 100px 40px;
background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
color: white;
margin: -40px -40px 40px -40px;
border-radius: 0 0 20px 20px;
}
.cover h1 {
font-family: 'Merriweather', serif;
font-size: 2.8em;
font-weight: 900;
margin-bottom: 20px;
letter-spacing: -1px;
}
.cover .subtitle {
font-size: 1.4em;
opacity: 0.9;
margin-bottom: 40px;
}
.cover .meta {
font-size: 1em;
opacity: 0.8;
}
.cover .badge {
display: inline-block;
background: var(--accent);
color: white;
padding: 8px 24px;
border-radius: 30px;
font-weight: 600;
margin-top: 30px;
}
/* Typography */
h1 {
font-family: 'Merriweather', serif;
font-size: 2em;
color: var(--primary);
margin: 50px 0 20px 0;
padding-bottom: 10px;
border-bottom: 3px solid var(--accent);
}
h2 {
font-family: 'Merriweather', serif;
font-size: 1.5em;
color: var(--secondary);
margin: 40px 0 15px 0;
}
h3 {
font-size: 1.2em;
color: var(--text);
margin: 30px 0 12px 0;
font-weight: 600;
}
h4 {
font-size: 1em;
color: var(--text-light);
margin: 20px 0 10px 0;
font-weight: 600;
}
p {
margin-bottom: 15px;
}
/* Table of Contents */
.toc {
background: var(--bg-alt);
padding: 30px;
border-radius: 12px;
margin: 30px 0;
}
.toc h2 {
margin-top: 0;
color: var(--primary);
}
.toc ol {
counter-reset: toc;
list-style: none;
padding-left: 0;
}
.toc > ol > li {
counter-increment: toc;
margin: 12px 0;
}
.toc > ol > li::before {
content: "Part " counter(toc) ": ";
font-weight: 700;
color: var(--accent);
}
.toc a {
color: var(--text);
text-decoration: none;
}
.toc a:hover {
color: var(--accent);
}
/* Diagrams & Boxes */
.diagram-box {
background: var(--code-bg);
color: #e2e8f0;
padding: 25px;
border-radius: 12px;
margin: 20px 0;
font-family: 'Source Code Pro', monospace;
font-size: 0.85em;
line-height: 1.5;
overflow-x: auto;
white-space: pre;
}
.concept-box {
background: linear-gradient(135deg, #ebf8ff 0%, #e6fffa 100%);
border-left: 4px solid var(--secondary);
padding: 20px 25px;
border-radius: 0 12px 12px 0;
margin: 20px 0;
}
.concept-box h4 {
color: var(--secondary);
margin-top: 0;
}
.warning-box {
background: #fffaf0;
border-left: 4px solid var(--warning);
padding: 20px 25px;
border-radius: 0 12px 12px 0;
margin: 20px 0;
}
.warning-box h4 {
color: var(--warning);
margin-top: 0;
}
.success-box {
background: #f0fff4;
border-left: 4px solid var(--success);
padding: 20px 25px;
border-radius: 0 12px 12px 0;
margin: 20px 0;
}
/* Code Blocks */
pre {
background: var(--code-bg);
color: #e2e8f0;
padding: 20px;
border-radius: 10px;
margin: 15px 0;
overflow-x: auto;
font-family: 'Source Code Pro', monospace;
font-size: 0.85em;
line-height: 1.6;
}
code {
font-family: 'Source Code Pro', monospace;
background: #edf2f7;
padding: 2px 6px;
border-radius: 4px;
font-size: 0.9em;
}
pre code {
background: none;
padding: 0;
}
.code-label {
background: var(--accent);
color: white;
padding: 4px 12px;
border-radius: 6px 6px 0 0;
font-size: 0.8em;
font-weight: 600;
display: inline-block;
margin-bottom: -5px;
}
/* Syntax Highlighting */
.keyword { color: #f687b3; }
.string { color: #68d391; }
.comment { color: #718096; font-style: italic; }
.function { color: #63b3ed; }
.number { color: #fbd38d; }
.decorator { color: #b794f4; }
/* Tables */
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-size: 0.9em;
}
th {
background: var(--primary);
color: white;
padding: 12px 15px;
text-align: left;
font-weight: 600;
}
td {
padding: 12px 15px;
border-bottom: 1px solid var(--border);
}
tr:nth-child(even) {
background: var(--bg-alt);
}
/* Lists */
ul, ol {
margin: 15px 0;
padding-left: 25px;
}
li {
margin: 8px 0;
}
/* Checklist */
.checklist {
list-style: none;
padding-left: 0;
}
.checklist li {
padding-left: 30px;
position: relative;
}
.checklist li::before {
content: "☐";
position: absolute;
left: 0;
color: var(--secondary);
}
/* Columns */
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin: 20px 0;
}
@media (max-width: 700px) {
.two-column {
grid-template-columns: 1fr;
}
}
/* Flow Arrows */
.flow-step {
display: flex;
align-items: flex-start;
margin: 15px 0;
}
.flow-number {
background: var(--accent);
color: white;
width: 30px;
height: 30px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: 700;
margin-right: 15px;
flex-shrink: 0;
}
.flow-content {
flex: 1;
}
/* Part Headers */
.part-header {
background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
color: white;
padding: 30px;
border-radius: 12px;
margin: 50px 0 30px 0;
text-align: center;
}
.part-header h1 {
color: white;
border: none;
margin: 0;
padding: 0;
}
.part-header .part-number {
font-size: 0.9em;
opacity: 0.8;
margin-bottom: 10px;
}
/* Summary Box */
.summary-box {
background: var(--bg-alt);
border: 2px solid var(--primary);
border-radius: 12px;
padding: 25px;
margin: 30px 0;
}
.summary-box h3 {
color: var(--primary);
margin-top: 0;
}
/* Footer */
.footer {
text-align: center;
padding: 40px 0;
margin-top: 60px;
border-top: 2px solid var(--border);
color: var(--text-light);
}
/* Highlight */
mark {
background: #fefcbf;
padding: 2px 4px;
border-radius: 3px;
}
/* Blockquote */
blockquote {
border-left: 4px solid var(--accent);
padding-left: 20px;
margin: 20px 0;
font-style: italic;
color: var(--text-light);
}
</style>
</head>
<body>
<!-- Cover Page -->
<div class="cover">
<h1>MasterClass:<br>How Modern Applications Are Built</h1>
<p class="subtitle">A Complete Guide to Full-Stack Development</p>
<p class="meta">Using FridgeChef as a Real-World Case Study</p>
<span class="badge">From Zero to Production</span>
</div>
<!-- Table of Contents -->
<div class="toc">
<h2>Table of Contents</h2>
<ol>
<li><a href="#part1">The Fundamental Mental Model</a></li>
<li><a href="#part2">The Three-Tier Architecture</a></li>
<li><a href="#part3">The Frontend - In Depth</a></li>
<li><a href="#part4">The Backend - In Depth</a></li>
<li><a href="#part5">The Database - In Depth</a></li>
<li><a href="#part6">How Everything Connects</a></li>
<li><a href="#part7">Authentication Deep Dive</a></li>
<li><a href="#part8">Configuration & Environment</a></li>
<li><a href="#part9">Deployment - Going Live</a></li>
<li><a href="#part10">Security Essentials</a></li>
<li><a href="#part11">Complete File Reference</a></li>
<li><a href="#part12">The App Building Checklist</a></li>
</ol>
</div>
<!-- PART 1 -->
<div class="part-header page-break" id="part1">
<div class="part-number">PART 1</div>
<h1>The Fundamental Mental Model</h1>
</div>
<h2>The Restaurant Analogy</h2>
<p>Before diving into technical details, you need a mental model. Think of a web application like a <strong>restaurant</strong>:</p>
<div class="diagram-box">
┌─────────────────────────────────────────────────────────────────────────┐
│ THE RESTAURANT ANALOGY │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ FRONTEND BACKEND DATABASE │
│ (Dining Room) (Kitchen) (Pantry) │
│ ═══════════════ ═══════════ ═════════════ │
│ │
│ • What customers see • Where food is made • Where all │
│ • Menu (UI) • Chef processes ingredients │
│ • Waiter takes orders requests are stored │
│ (sends requests) • Has recipes • Organized │
│ • Serves food (business rules) storage │
│ (displays data) │
│ │
└─────────────────────────────────────────────────────────────────────────┘
THE FLOW:
═════════
Customer → Waiter → Kitchen → Pantry → Kitchen → Waiter → Customer
(User) (HTTP) (Server) (DB) (Process) (JSON) (UI)
1. Customer (User) looks at menu (Frontend UI)
2. Customer tells waiter what they want (HTTP Request)
3. Waiter goes to kitchen (Request hits Backend)
4. Chef checks pantry for ingredients (Backend queries Database)
5. Chef prepares the dish (Backend processes data)
6. Waiter brings food to customer (HTTP Response)
7. Customer enjoys the meal (User sees result on screen)
</div>
<div class="concept-box">
<h4>Key Insight</h4>
<p>Every web application, from a simple blog to Facebook, follows this same fundamental pattern. The complexity increases, but the core flow remains: <strong>User → Frontend → Backend → Database → Backend → Frontend → User</strong></p>
</div>
<h2>Why This Separation?</h2>
<div class="two-column">
<div>
<h4>Separation of Concerns</h4>
<ul>
<li>Each layer has ONE job</li>
<li>Easier to understand</li>
<li>Easier to modify</li>
<li>Easier to test</li>
</ul>
</div>
<div>
<h4>Scalability</h4>
<ul>
<li>Scale each layer independently</li>
<li>Replace technologies without rewriting everything</li>
<li>Different teams can work on different layers</li>
</ul>
</div>
</div>
<!-- PART 2 -->
<div class="part-header page-break" id="part2">
<div class="part-number">PART 2</div>
<h1>The Three-Tier Architecture</h1>
</div>
<div class="diagram-box">
┌─────────────────────────────────────────────────────────────────────────┐
│ THREE-TIER ARCHITECTURE │
└─────────────────────────────────────────────────────────────────────────┘
┌───────────────────────────────┐
│ USER'S BROWSER │
│ (Chrome, Firefox, Safari) │
└───────────────┬───────────────┘
│
┌───────────────▼───────────────┐
│ TIER 1: FRONTEND │
│ ═════════════════ │
│ │
│ • Next.js (React Framework) │
│ • TypeScript │
│ • Tailwind CSS │
│ • Runs in browser │
│ │
│ Location: frontend/ folder │
└───────────────┬───────────────┘
│
HTTP Requests
(JSON over HTTPS)
│
┌───────────────▼───────────────┐
│ TIER 2: BACKEND │
│ ════════════════ │
│ │
│ • FastAPI (Python) │
│ • Business Logic │
│ • Authentication │
│ • External API calls │
│ │
│ Location: backend/ folder │
└───────────────┬───────────────┘
│
SQL Queries
│
┌───────────────▼───────────────┐
│ TIER 3: DATABASE │
│ ════════════════ │
│ │
│ • SQLite (Development) │
│ • PostgreSQL (Production) │
│ • Stores all data │
│ │
└───────────────────────────────┘
</div>
<h2>Your Project's Technology Stack</h2>
<table>
<tr>
<th>Layer</th>
<th>Technology</th>
<th>Purpose</th>
<th>Location</th>
</tr>
<tr>
<td><strong>Frontend</strong></td>
<td>Next.js 14 + TypeScript</td>
<td>User interface, runs in browser</td>
<td><code>frontend/</code></td>
</tr>
<tr>
<td><strong>Styling</strong></td>
<td>Tailwind CSS</td>
<td>Visual appearance</td>
<td><code>frontend/tailwind.config.ts</code></td>
</tr>
<tr>
<td><strong>State</strong></td>
<td>Zustand</td>
<td>Frontend memory (auth state)</td>
<td><code>frontend/src/store/</code></td>
</tr>
<tr>
<td><strong>Backend</strong></td>
<td>FastAPI (Python)</td>
<td>API server, business logic</td>
<td><code>backend/</code></td>
</tr>
<tr>
<td><strong>Database</strong></td>
<td>SQLite / PostgreSQL</td>
<td>Persistent data storage</td>
<td><code>backend/app.db</code></td>
</tr>
<tr>
<td><strong>ORM</strong></td>
<td>SQLAlchemy</td>
<td>Python ↔ Database translation</td>
<td><code>backend/app/models/</code></td>
</tr>
<tr>
<td><strong>AI</strong></td>
<td>Groq</td>
<td>Image recognition, recipe generation</td>
<td><code>backend/app/services/Groq.py</code></td>
</tr>
</table>
<!-- PART 3 -->
<div class="part-header page-break" id="part3">
<div class="part-number">PART 3</div>
<h1>The Frontend - In Depth</h1>
</div>
<h2>What is the Frontend?</h2>
<p>The frontend is <strong>code that runs in the user's browser</strong>. When you visit a website, your browser downloads HTML, CSS, and JavaScript files, then executes them locally on your computer.</p>
<div class="concept-box">
<h4>Think of it this way</h4>
<p>The frontend is like a <strong>restaurant menu and dining area</strong>. It's what customers see and interact with. The menu shows what's available, the decor creates ambiance, and the ordering process guides the customer through their experience.</p>
</div>
<h2>Frontend Folder Structure</h2>
<div class="diagram-box">
frontend/
├── src/
│ ├── app/ # PAGES (Routes)
│ │ ├── page.tsx # → yoursite.com/
│ │ ├── login/page.tsx # → yoursite.com/login
│ │ ├── register/page.tsx # → yoursite.com/register
│ │ ├── layout.tsx # Wraps ALL pages (shared structure)
│ │ │
│ │ └── (app)/ # PROTECTED routes (need login)
│ │ ├── layout.tsx # Layout for protected pages
│ │ ├── dashboard/page.tsx # → yoursite.com/dashboard
│ │ ├── scan/page.tsx # → yoursite.com/scan
│ │ ├── recipes/page.tsx # → yoursite.com/recipes
│ │ └── settings/page.tsx # → yoursite.com/settings
│ │
│ ├── components/ # REUSABLE UI PIECES
│ │ ├── ui/ # Generic components
│ │ │ ├── Button.tsx # <Button> component
│ │ │ ├── Input.tsx # <Input> component
│ │ │ └── Card.tsx # <Card> component
│ │ ├── layout/ # Structure components
│ │ │ ├── Navbar.tsx # Navigation bar
│ │ │ └── Footer.tsx # Page footer
│ │ └── recipe/ # Feature-specific
│ │ └── RecipeCard.tsx # Recipe display card
│ │
│ ├── lib/ # UTILITIES
│ │ ├── api.ts # HTTP client (talks to backend)
│ │ └── utils.ts # Helper functions
│ │
│ ├── store/ # STATE MANAGEMENT
│ │ └── auth.ts # Login/logout state
│ │
│ └── types/ # TYPE DEFINITIONS
│ └── api.ts # What data shapes look like
│
├── public/ # STATIC FILES
│ └── images/ # Images, fonts, etc.
│
├── package.json # Dependencies & scripts
├── tailwind.config.ts # CSS configuration
├── next.config.ts # Framework configuration
└── tsconfig.json # TypeScript settings
</div>
<h2>Key Frontend Concepts</h2>
<h3>A) Components - Building Blocks</h3>
<p>React applications are built from <strong>components</strong> - reusable pieces of UI. Think of them like LEGO blocks that you combine to build pages.</p>
<div class="code-label">frontend/src/app/page.tsx - Home Page Component</div>
<pre><code><span class="keyword">export default function</span> <span class="function">Home</span>() {
<span class="keyword">return</span> (
<<span class="function">main</span> className=<span class="string">"min-h-screen flex flex-col items-center"</span>>
<span class="comment">{/* Title */}</span>
<<span class="function">h1</span> className=<span class="string">"text-6xl"</span>>FridgeChef</<span class="function">h1</span>>
<span class="comment">{/* Tagline */}</span>
<<span class="function">p</span> className=<span class="string">"text-2xl"</span>>What can I make with what I have?</<span class="function">p</span>>
<span class="comment">{/* Reusable Button Component */}</span>
<<span class="function">Button</span> size=<span class="string">"lg"</span> variant=<span class="string">"primary"</span>>
Join the Kitchen
</<span class="function">Button</span>>
</<span class="function">main</span>>
);
}</code></pre>
<div class="concept-box">
<h4>Component Reusability</h4>
<p>Notice <code><Button></code> is a custom component defined once in <code>components/ui/Button.tsx</code>. You use it everywhere with different props (size, variant). Change it once, it updates everywhere.</p>
</div>
<h3>B) State - The Frontend's Memory</h3>
<p>The frontend needs to remember things: Is the user logged in? What data was fetched? State management handles this.</p>
<div class="code-label">frontend/src/store/auth.ts - Authentication State</div>
<pre><code><span class="keyword">import</span> { create } <span class="keyword">from</span> <span class="string">'zustand'</span>;
<span class="keyword">const</span> useAuthStore = <span class="function">create</span>((set) => ({
<span class="comment">// State (data being stored)</span>
user: <span class="keyword">null</span>, <span class="comment">// Currently logged in user</span>
token: <span class="keyword">null</span>, <span class="comment">// JWT authentication token</span>
isAuthenticated: <span class="keyword">false</span>, <span class="comment">// Quick check: logged in?</span>
<span class="comment">// Actions (ways to change state)</span>
<span class="function">login</span>: <span class="keyword">async</span> (email, password) => {
<span class="keyword">const</span> response = <span class="keyword">await</span> authApi.<span class="function">login</span>(email, password);
<span class="function">set</span>({
token: response.access_token,
isAuthenticated: <span class="keyword">true</span>
});
localStorage.<span class="function">setItem</span>(<span class="string">'auth_token'</span>, response.access_token);
},
<span class="function">logout</span>: () => {
localStorage.<span class="function">removeItem</span>(<span class="string">'auth_token'</span>);
<span class="function">set</span>({ user: <span class="keyword">null</span>, token: <span class="keyword">null</span>, isAuthenticated: <span class="keyword">false</span> });
}
}));</code></pre>
<h3>C) API Client - Talking to Backend</h3>
<p>The frontend communicates with the backend via HTTP requests. The API client centralizes this communication.</p>
<div class="code-label">frontend/src/lib/api.ts - HTTP Client</div>
<pre><code><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'axios'</span>;
<span class="comment">// Where the backend lives</span>
<span class="keyword">const</span> API_URL = <span class="string">'http://localhost:8000/api/v1'</span>;
<span class="comment">// Create axios instance (HTTP client)</span>
<span class="keyword">export const</span> api = axios.<span class="function">create</span>({
baseURL: API_URL,
headers: { <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span> }
});
<span class="comment">// INTERCEPTOR: Add auth token to EVERY request automatically</span>
api.interceptors.request.<span class="function">use</span>((config) => {
<span class="keyword">const</span> token = localStorage.<span class="function">getItem</span>(<span class="string">'auth_token'</span>);
<span class="keyword">if</span> (token) {
config.headers.Authorization = <span class="string">`Bearer </span>${token}<span class="string">`</span>;
}
<span class="keyword">return</span> config;
});
<span class="comment">// Auth API functions</span>
<span class="keyword">export const</span> authApi = {
<span class="function">register</span>: <span class="keyword">async</span> (email, password, name) => {
<span class="keyword">const</span> { data } = <span class="keyword">await</span> api.<span class="function">post</span>(<span class="string">'/auth/register'</span>, { email, password, name });
<span class="keyword">return</span> data;
},
<span class="function">login</span>: <span class="keyword">async</span> (email, password) => {
<span class="keyword">const</span> { data } = <span class="keyword">await</span> api.<span class="function">post</span>(<span class="string">'/auth/login'</span>, { email, password });
<span class="keyword">return</span> data;
}
};</code></pre>
<div class="warning-box">
<h4>Interceptors are Powerful</h4>
<p>The request interceptor automatically adds the authentication token to every request. You don't have to remember to add it manually each time. This is a common pattern in production applications.</p>
</div>
<!-- PART 4 -->
<div class="part-header page-break" id="part4">
<div class="part-number">PART 4</div>
<h1>The Backend - In Depth</h1>
</div>
<h2>What is the Backend?</h2>
<p>The backend is a <strong>program running on a server</strong> that receives requests, processes them, and sends responses. It's where the "real work" happens.</p>
<div class="concept-box">
<h4>Think of it this way</h4>
<p>The backend is like the <strong>kitchen in a restaurant</strong>. Customers never see it, but it's where all the magic happens. The chef (backend) receives orders (requests), prepares dishes using ingredients from the pantry (database), and sends completed meals back to customers.</p>
</div>
<h2>Backend Folder Structure</h2>
<div class="diagram-box">
backend/
├── app/
│ ├── main.py # APPLICATION ENTRY POINT
│ │ # Everything starts here
│ │
│ ├── config.py # SETTINGS
│ │ # Environment variables, configuration
│ │
│ ├── database.py # DATABASE CONNECTION
│ │ # How to talk to the database
│ │
│ ├── models/ # DATABASE TABLES (ORM)
│ │ ├── user.py # users table definition
│ │ ├── scan.py # scans table definition
│ │ ├── recipe.py # recipes table definition
│ │ └── shopping_list.py # shopping_lists table
│ │
│ ├── schemas/ # DATA VALIDATION
│ │ ├── auth.py # What login/register accepts
│ │ ├── recipe.py # What recipe endpoints accept
│ │ └── scan.py # What scan endpoints accept
│ │
│ ├── api/v1/ # API ROUTES (endpoints)
│ │ ├── router.py # Combines all endpoints
│ │ └── endpoints/
│ │ ├── auth.py # /auth/register, /auth/login
│ │ ├── scans.py # /scans endpoints
│ │ ├── recipes.py # /recipes endpoints
│ │ └── health.py # /health check
│ │
│ ├── services/ # BUSINESS LOGIC
│ │ ├── auth.py # User creation, verification
│ │ ├── Groq.py # AI integration
│ │ └── image.py # Image processing
│ │
│ ├── core/ # SECURITY
│ │ └── security.py # Password hashing, JWT tokens
│ │
│ └── utils/ # UTILITIES
│ └── logger.py # Logging setup
│
├── requirements.txt # Python dependencies
├── Dockerfile # Container configuration
└── alembic/ # Database migrations
</div>
<h2>Key Backend Concepts</h2>
<h3>A) The Entry Point - main.py</h3>
<p>This is where the application starts. It creates the FastAPI app, adds middleware, and connects all the pieces.</p>
<div class="code-label">backend/app/main.py - Application Entry Point</div>
<pre><code><span class="keyword">from</span> fastapi <span class="keyword">import</span> FastAPI
<span class="keyword">from</span> fastapi.middleware.cors <span class="keyword">import</span> CORSMiddleware
<span class="keyword">from</span> app.api.v1.router <span class="keyword">import</span> api_router
<span class="keyword">from</span> app.database <span class="keyword">import</span> Base, engine
<span class="comment"># Create the FastAPI application</span>
app = <span class="function">FastAPI</span>(
title=<span class="string">"FridgeChef API"</span>,
description=<span class="string">"Backend API for FridgeChef"</span>,
version=<span class="string">"1.0.0"</span>
)
<span class="comment"># Create database tables (if they don't exist)</span>
Base.metadata.<span class="function">create_all</span>(bind=engine)
<span class="comment"># Add CORS middleware (allow frontend to talk to us)</span>
app.<span class="function">add_middleware</span>(
CORSMiddleware,
allow_origins=[<span class="string">"http://localhost:3000"</span>], <span class="comment"># Frontend URL</span>
allow_credentials=<span class="keyword">True</span>,
allow_methods=[<span class="string">"*"</span>], <span class="comment"># Allow all HTTP methods</span>
allow_headers=[<span class="string">"*"</span>], <span class="comment"># Allow all headers</span>
)
<span class="comment"># Mount all API routes under /api/v1</span>
app.<span class="function">include_router</span>(api_router, prefix=<span class="string">"/api/v1"</span>)
<span class="comment"># Root endpoint</span>
<span class="decorator">@app.get("/")</span>
<span class="keyword">async def</span> <span class="function">root</span>():
<span class="keyword">return</span> {<span class="string">"message"</span>: <span class="string">"Welcome to FridgeChef API"</span>}</code></pre>
<h3>B) Models - Database Tables</h3>
<p>Models define what data looks like in the database. Each model class becomes a table.</p>
<div class="code-label">backend/app/models/user.py - User Database Model</div>
<pre><code><span class="keyword">from</span> sqlalchemy <span class="keyword">import</span> Column, String, DateTime, JSON
<span class="keyword">from</span> sqlalchemy.sql <span class="keyword">import</span> func
<span class="keyword">import</span> uuid
<span class="keyword">from</span> app.database <span class="keyword">import</span> Base
<span class="keyword">class</span> <span class="function">User</span>(Base):
<span class="string">"""User model for authentication and preferences."""</span>
__tablename__ = <span class="string">"users"</span> <span class="comment"># Table name in database</span>
<span class="comment"># Columns (fields in the table)</span>
id = <span class="function">Column</span>(String(<span class="number">36</span>), primary_key=<span class="keyword">True</span>,
default=<span class="keyword">lambda</span>: <span class="function">str</span>(uuid.<span class="function">uuid4</span>()))
email = <span class="function">Column</span>(String(<span class="number">255</span>), unique=<span class="keyword">True</span>, nullable=<span class="keyword">False</span>)
name = <span class="function">Column</span>(String(<span class="number">100</span>))
password_hash = <span class="function">Column</span>(String(<span class="number">255</span>), nullable=<span class="keyword">False</span>) <span class="comment"># NEVER plain text!</span>
created_at = <span class="function">Column</span>(DateTime, default=func.<span class="function">now</span>())
preferences = <span class="function">Column</span>(JSON, default={})</code></pre>
<p>This creates a database table that looks like:</p>
<table>
<tr>
<th>id</th>
<th>email</th>
<th>name</th>
<th>password_hash</th>
<th>created_at</th>
</tr>
<tr>
<td>abc-123</td>
<td>john@mail.com</td>
<td>John</td>
<td>$2b$12$hash...</td>
<td>2024-01-01</td>
</tr>
<tr>
<td>def-456</td>
<td>jane@mail.com</td>
<td>Jane</td>
<td>$2b$12$hash...</td>
<td>2024-01-02</td>
</tr>
</table>
<h3>C) Schemas - Data Validation</h3>
<p>Schemas define what the API accepts and returns. They validate incoming data and document the API.</p>
<div class="code-label">backend/app/schemas/auth.py - Auth Schemas</div>
<pre><code><span class="keyword">from</span> pydantic <span class="keyword">import</span> BaseModel, EmailStr
<span class="comment"># What frontend sends to REGISTER</span>
<span class="keyword">class</span> <span class="function">UserRegister</span>(BaseModel):
email: EmailStr <span class="comment"># Must be valid email format</span>
password: <span class="function">str</span> <span class="comment"># Required</span>
name: <span class="function">str</span> | <span class="keyword">None</span> = <span class="keyword">None</span> <span class="comment"># Optional</span>
<span class="comment"># What frontend sends to LOGIN</span>
<span class="keyword">class</span> <span class="function">UserLogin</span>(BaseModel):
email: EmailStr
password: <span class="function">str</span>
<span class="comment"># What backend RETURNS after login</span>
<span class="keyword">class</span> <span class="function">Token</span>(BaseModel):
access_token: <span class="function">str</span>
token_type: <span class="function">str</span> = <span class="string">"bearer"</span></code></pre>
<h3>D) Endpoints - API Routes</h3>
<p>Endpoints are URLs that do specific things. Each endpoint handles a specific action.</p>
<div class="code-label">backend/app/api/v1/endpoints/auth.py - Auth Endpoints</div>
<pre><code><span class="keyword">from</span> fastapi <span class="keyword">import</span> APIRouter, Depends, HTTPException
<span class="keyword">from</span> app.schemas.auth <span class="keyword">import</span> UserRegister, UserLogin, Token
<span class="keyword">from</span> app.services.auth <span class="keyword">import</span> create_user, authenticate_user
<span class="keyword">from</span> app.core.security <span class="keyword">import</span> create_access_token
router = <span class="function">APIRouter</span>()
<span class="decorator">@router.post("/register", response_model=Token)</span>
<span class="keyword">async def</span> <span class="function">register</span>(user_data: UserRegister, db = <span class="function">Depends</span>(get_db)):
<span class="string">"""Register a new user."""</span>
<span class="comment"># 1. Create user in database</span>
user = <span class="function">create_user</span>(
db=db,
email=user_data.email,
password=user_data.password,
name=user_data.name
)
<span class="comment"># 2. Create JWT token</span>
access_token = <span class="function">create_access_token</span>(data={<span class="string">"sub"</span>: <span class="function">str</span>(user.id)})
<span class="comment"># 3. Return token to frontend</span>
<span class="keyword">return</span> {<span class="string">"access_token"</span>: access_token, <span class="string">"token_type"</span>: <span class="string">"bearer"</span>}
<span class="decorator">@router.post("/login", response_model=Token)</span>
<span class="keyword">async def</span> <span class="function">login</span>(user_data: UserLogin, db = <span class="function">Depends</span>(get_db)):