๐ Chapter 5: Implementing REST APIs in Node.js
๐งฉ Express Setup
To build a REST API in Node.js, start by installing Express — a lightweight web framework.
npm install express Then create a basic server:
const express = require('express'); const app = express(); app.use(express.json()); app.listen(3000, () => { console.log('Server running on port 3000'); }); ๐งช Routing and Middleware
Define routes to handle different HTTP methods:
app.get('/api/advice', (req, res) => { res.json({ message: 'Crop advisory data' }); }); Use middleware for logging, authentication, or parsing:
app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); ๐ Connecting to Redis or Upstash
To cache data or track dashboard metrics, connect to Redis:
npm install @upstash/redis import { Redis } from '@upstash/redis'; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }); ๐งช Example: Advisory Endpoint with Caching
app.get('/api/advice', async (req, res) => { const cached = await redis.get('crop:advice:maize'); if (cached) return res.json(JSON.parse(cached)); const advice = { crop: 'maize', message: 'Apply nitrogen before rains' }; await redis.set('crop:advice:maize', JSON.stringify(advice), { ex: 3600 }); res.json(advice); }); ๐ง Engineering Addendum: Express + Upstash on GitHub + Vercel
Express apps are fully compatible with GitHub and Vercel for serverless deployment. Upstash enhances them with caching, rate limiting, and pub/sub.
- Zero-config Express backends
- Auto-deployments from GitHub branches
- Serverless function wrapping for each route
- Upstash Redis for advisory caching and dashboard metrics
๐ Footnote Glossary
| Term | Kid-Friendly Explanation |
|---|---|
| Node.js | A tool that lets you run JavaScript on a server, not just in a browser. |
| Express | A helper that makes it easier to build websites and APIs with Node.js. |
| Route | A specific web address your app listens to, like a door for certain requests. |
| Middleware | Code that runs before your main logic, like a security guard or helper. |
| Redis | A fast place to store and get data quickly, often used for caching. |
| Upstash | A cloud service that gives you Redis without needing to manage servers. |
| Caching | Saving data temporarily so it loads faster the next time. |
| Environment Variable | A hidden setting that stores secrets like passwords or URLs. |
| Vercel | A platform that hosts your app and turns each route into a serverless function. |
| Pub/Sub | A way for apps to send and receive messages instantly, like a walkie-talkie. |
No comments:
Post a Comment