Hack Session #5
API Development
Find and sit with your�Group and Mentor!
SANDBOX <> OASIS
Agenda
⏱️ Project Series Timeline
HS 0 / EX 0
Git
(1/18)
HS 1 / EX 1
Web Basics
(1/25)
HS 2
React
(2/1)
HS 3
React Continued
(2/8)
HS 4
Databases
(2/22)
HS 5
API Development
(3/8)
HS 6
Co-op Panel
(3/15)
END
Demo Day
(TBD)
HS 7
Auth
(3/22)
HS 8
Deployment
(3/29)
0
1
2
3
4
5
6
7
8
E
Refresher 🧠
(before we build up)
CRUD
Create | Add new data |
Read | Get existing data |
Update | Change existing data |
Delete | Remove data |
Database
Tables
Courses
Ratings
etc.
Columns
id
Courses
course_code
course_name
last_run
etc.
Keys
course_code
course_name
last_run
etc.
id
first_run
text
text
uuid
date
…
date
APIs📡
Quick Check-In
So far we have built …
The Problem
Connecting to Supabase directly from our react frontend is insecure and suboptimal!
The Solution: Build an API!
React Frontend ↔ Your API ↔ Supabase Database
Real World Examples
You interact with APIs every day!
Every button you click, every post you see = API call happening behind the scenes
What is an API?
Think of it as a waiter at a restaurant:
API Endpoints
Endpoint = A location within an API where a client can send requests
HTTP: How the Web Talks
APIs use HTTP - the same system that loads web pages
HTTP Request Components
Every HTTP Request Has |
URL: Defines where the request is going localhost:8000/api/listings |
Method: What action you want to perform GET, POST, PUT, DELETE (We’ll explain more in depth next) |
Headers: Extra information about the request. Could include information regarding … … Authentication (who you are), Content Type (the format that the data is in) |
Body: The data you’re sending (this is optional - not used with GET or DELETE) { "title": "Calculus Book" } |
HTTP Methods Explained
Method | CRUD | Purpose | Has Body? | Example |
GET | READ | Retrieve data | NO | Get all listings |
POST | CREATE | Add new data | YES | Create new listing |
PUT/PATCH | UPDATE | Modify existing data | YES | Update listing price |
DELETE | DELETE | Remove data | NO | Delete a listing |
HTTP Response Components
Every HTTP Response Has |
Status Code: What happened with your request 200 OK, 404 Not Found, etc. (Will explain in detail next) |
Headers: Response metadata Date, server information, etc. |
Body: The data you get back JSON (Will explain soon) data from database e.g [{ "id": 1, "title": "Calculus Book", "price": 45 }] |
Status Codes
You saw "Status Code" in the HTTP Response - here's what those numbers mean:
JSON (JavaScript Object Notation)
Example
REST Architecture
REST = Representational State Transfer
REST APIs use:
Result: APIs become intuitive and consistent across different applications
RESTful Routing Pattern
Method | Action | Endpoint | Description |
GET | Read | /listings | Retrieve data |
POST | Create | /listings | Add new data |
PUT/PATCH | Update | /listings/:id | Modify data |
DELETE | Delete | /listings/:id | Remove data |
Notice the pattern:
What is Express.js?
How Express Works
Browser sends request
Express matches to route
Express runs function
Send back response
A Simple Endpoint
Let’s look at a very simple endpoint:�// GET endpoint - returns JSON
app.get('/api/hello', (req, res) => {
res.json({
message: 'Welcome to the API!',
timestamp: new Date() }); });
BUILDING APIS WITH EXPRESS - KEY CONCEPTS
1. Middleware
2. Async/Await
3. Error Handling
Middleware
Middleware = Functions that execute during the request-response cycle
app.use((req, res, next) => {
console.log(`${req.method} ${req.url} - ${new Date()}`);
next(); });
CORS Middleware
CORS = Cross-Origin Resource Sharing
What is CORS? CORS is a browser security feature that controls which websites can access your API. By default, browsers block requests between different origins (different domains or ports).
The Problem:
The Solution: CORS middleware tells the browser "it's okay to accept requests from my frontend"
app.use(cors({ origin: 'http://localhost:5173' }));
ASYNC/AWAIT
The Challenge: JavaScript doesn't wait by default
app.get('/api/listings', async (req, res) =>
{ const { data } = await supabase.from('listings').select('*');
res.json(data); // Now data has the results });
How it works:
Error Handling
Why Error Handling Matters: Without proper error handling, a single error can crash your entire server. Error handling ensures your API stays online and provides helpful feedback when things go wrong.
The Pattern: try-catch blocks
app.get('/api/listings/:id', async (req, res) => {
try { // Your code that might fail
} catch (error) {
res.status(500).json({ error: 'Failed to fetch listing' }); } });
Best Practices:
if (!title || !price) { return res.status(400).json({ error: 'Missing required fields' }); }
Complete Endpoint - Putting it All Together
Middleware
Endpoint
Demo 🛒
Attendance
Hack Time 🪓
See you next Sunday, Project Series Cohort!
Follow us on Instagram @oasisneu, and check out our website! oasisneu.com
Feel free to ask us�any questions!