
CAUTION
Some files are private or not ready yet, if a link gives you a 404 that's why :)
This is a work in progress, new notes will be added daily
List of note Indexes
π PROJECTSπ ARTπ TECHNOLOGYπ SCIENCEπ PHILO-PSYCHOπ HISTORYπ HEALTHπ GAMINGπ KNOWLEDGE
.... |\| .|||. |\/| .|\\. .|.
.\\||/|. .\|..|| .\|..|||...||.....
.| .....||.|\\\\\\ ... |\\\/. .\\. .||
.\\| .|\\|..|\\ .\\\\ .\\|. .\\\\\| |\| |\\|
|\\ |\\|.. /\\\. |\|\\ \\\\|. .|\\. .\\\\|
.\\. |\\\\\\\|.. .\\| .\\||\\/|. |\\| .|/\|
\. .\\\||/\|.... \\| |\/ |\\\ |\\\| .\\| \\| ....
|\/ |\\| |\\\\\\\| |\|.\\\ \\\\. |\\\\| |\\ \\. ||..
..|||\| .. .\\\\. |\\\\\\ .\\|....|\\\. |\\\\\\ |/. |/
\\\|.. .\\\ |\\. .\\\| \\| |||\\\. ...|\\/||. .\\\
|\| |\/. /\\\\\| .\\\\. \\. .../|. .|\\\|. |\\\| |\\
. |||\\|. ..||| .\\|. |\| \\|..../\\| |\\| .\\\\\ ..
\\| .||\|.|.. |\\\|./\ \\||\. ||... .\\\\/. |\/||
..|/||. |\\\\\|. .|/\| ||. .||\\\ .|||. |\
.\/| \\\. .|\\\|||\\\||.. .|\\\\\\\|\\\\. /\\\\||. |
.|| |\\\\| .......|\\\\\\. .\\\. ..|||.... .\\\\|.. ...
\\||....|\\\\\\\\||\\\\\\\/ |\|....|||\\\\\\\/....|\\\|
||.|\||\\| .....|\\\\..\\| .|\\\. ||........ .|\|...
. |\ /\\/\\\\\\. |\. .\\\\\\. ./\\\\/ |\\\||.
.|\.|\| .|\|... .. ./\\|..|\\| ..
.|\\| .\\\\.\\\\\\\ \||...\\\|..|\\\|.||
|\. ..||....|| ... ..||\\\. .|.
... .......
β TypeScript
Great question! Both RPC (Remote Procedure Call) and REST (Representational State Transfer) are ways for a client to communicate with a server, but they have different philosophies, designs, and use cases.
Key Differences Between RPC and REST
| Feature | RPC (Remote Procedure Call) | REST (Representational State Transfer) |
|---|---|---|
| Design Approach | Focuses on actions (calling remote functions) | Focuses on resources (nouns like /users, /orders) |
| Communication Style | Like calling a function directly (e.g., getUser(123)) | Like interacting with resources via HTTP methods (e.g., GET /users/123) |
| Protocol | Can work over HTTP, but also custom protocols (gRPC, Thrift) | Strictly follows HTTP semantics |
| Data Formats | Often binary (Protocol Buffers, Thrift) or JSON-RPC | Typically JSON or XML over HTTP |
| Endpoint Structure | Usually procedure-oriented (e.g., /getUser) | Resource-oriented (e.g., /users/{id}) |
| Statefulness | Can be stateful (depends on implementation) | Stateless (each request contains all needed info) |
| Use Cases | High-performance microservices (gRPC), internal APIs | Public APIs, web services, CRUD apps |
1. RPC (Remote Procedure Call)
- Concept: Mimics calling a function/method on a remote server as if it were local.
- Example:
- Client calls
addUser(name: "Alice", age: 30)β Server executes the function. - Can use JSON-RPC, gRPC, or XML-RPC.
- Client calls
- Pros:
- Feels like normal programming (just calling functions).
- Efficient (especially with binary protocols like gRPC).
- Cons:
- Tight coupling between client and server (changing the function signature breaks clients).
- Less standardized than REST.
Example (gRPC):
// Define the service in a .proto file
service UserService {
rpc GetUser (UserRequest) returns (UserResponse);
}
β Client calls GetUser({ id: 123 }) β Server returns user data.
2. REST (Representational State Transfer)
- Concept: Treats everything as a resource (like a document or database entry).
- Example:
GET /users/123β Returns user with ID 123.- Uses HTTP methods (
GET,POST,PUT,DELETE).
- Pros:
- Standardized (works well with HTTP caching, proxies).
- Loose coupling (client only needs to know the resource URLs).
- Cons:
- Can be verbose (sometimes over-fetches data).
- Not ideal for real-time or high-performance systems.
Example (REST API):
GET /users/123 HTTP/1.1
Host: api.example.com
β Server responds with:
{ "id": 123, "name": "Alice", "age": 30 }
When to Use Which?
- Use RPC when:
- You need low latency (e.g., microservices with gRPC).
- You want strong typing (Protocol Buffers in gRPC).
- Youβre calling specific actions (e.g.,
processPayment()).
- Use REST when:
- Youβre building a public API (easy to understand).
- You work with CRUD operations (Create, Read, Update, Delete).
- You want caching, scalability, and simplicity.
TL;DR
- RPC = Calling remote functions directly (
getUser(123)). - REST = Interacting with resources via HTTP (
GET /users/123).
Would you like a real-world analogy or code examples in a specific language (e.g., Python, JavaScript)?
Absolutely! Below are JavaScript examples comparing RPC-style (using JSON-RPC) and REST-style APIs. I'll show both client and server code for each.
1. RPC Example (JSON-RPC over HTTP)
In RPC, you call a remote function (procedure) by name with parameters.
Server (Node.js with Express)
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// RPC-style endpoint
app.post('/rpc', (req, res) => {
const { method, params } = req.body;
if (method === 'getUser') {
const userId = params.id;
const user = { id: userId, name: 'Alice', age: 30 };
res.json({ result: user });
} else if (method === 'addUser') {
const { name, age } = params;
res.json({ result: { id: 1, name, age } });
} else {
res.status(404).json({ error: 'Method not found' });
}
});
app.listen(3000, () => console.log('RPC Server running on http://localhost:3000'));
Client (Browser or Node.js)
// Calling the RPC endpoint
fetch('http://localhost:3000/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
method: 'getUser', // Function name to call
params: { id: 123 } // Arguments
})
})
.then(res => res.json())
.then(data => console.log(data.result));
// Output: { id: 123, name: 'Alice', age: 30 }
Key Points:
- The client sends a method name (
getUser) and parameters ({ id: 123 }). - The server executes the corresponding function and returns the result.
2. REST Example (HTTP Methods)
In REST, you interact with resources using standard HTTP methods (GET, POST, etc.).
Server (Node.js with Express)
const express = require('express');
const app = express();
let users = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 }
];
// GET /users/1 β Returns user with ID 1
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
res.json(user);
});
// POST /users β Creates a new user
app.post('/users', express.json(), (req, res) => {
const newUser = { id: users.length + 1, ...req.body };
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3001, () => console.log('REST Server running on http://localhost:3001'));
Client (Browser or Node.js)
// GET a user
fetch('http://localhost:3001/users/1')
.then(res => res.json())
.then(user => console.log(user));
// Output: { id: 1, name: 'Alice', age: 30 }
// POST a new user
fetch('http://localhost:3001/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Charlie', age: 40 })
})
.then(res => res.json())
.then(newUser => console.log(newUser));
// Output: { id: 3, name: 'Charlie', age: 40 }
Key Points:
- REST uses HTTP methods (
GET,POST) and resource URLs (/users/1). - The server responds with resource representations (JSON).
Comparison Summary
| Aspect | RPC (JSON-RPC) | REST |
|---|---|---|
| Endpoint | /rpc (single endpoint) | /users, /users/1 (resource-based) |
| Method Call | { method: 'getUser', params: { id: 123 } } | GET /users/123 |
| Flexibility | Good for actions (calculateTax, processOrder) | Good for CRUD (GET, POST, PUT, DELETE) |
| HTTP Usage | Typically POST-only | Uses all HTTP methods properly |
Which Should You Use?
- Use RPC (gRPC/JSON-RPC) if:
- You need high performance (e.g., microservices).
- Youβre calling specific actions (e.g.,
sendEmail,processPayment).
- Use REST if:
- Youβre building a public API (easy to document and cache).
- You mostly do CRUD operations (Create, Read, Update, Delete).
Would you like a real-time example (e.g., WebSockets with RPC) or a TypeScript version? Let me know! π
Great! Letβs dive into a real-time RPC example using WebSockets (for live updates) and a TypeScript version of both RPC and REST APIs.
1. Real-Time RPC with WebSockets (JavaScript)
Here, the client can call server functions in real-time, and the server can push updates.
Server (Node.js with WebSocket)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Store connected clients
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('New client connected');
ws.on('message', (message) => {
const { method, params } = JSON.parse(message);
// Handle RPC calls
if (method === 'getUser') {
const user = { id: params.id, name: 'Alice', age: 30 };
ws.send(JSON.stringify({ result: user }));
} else if (method === 'broadcastMessage') {
// Broadcast to all clients
clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: 'newMessage',
data: { text: params.text }
}));
}
});
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
console.log('WebSocket RPC Server running on ws://localhost:8080');
Client (Browser)
const ws = new WebSocket('ws://localhost:8080');
// Call a remote method
ws.onopen = () => {
ws.send(JSON.stringify({
method: 'getUser',
params: { id: 123 }
}));
// Broadcast a message to all clients
ws.send(JSON.stringify({
method: 'broadcastMessage',
params: { text: 'Hello everyone!' }
}));
};
// Listen for responses
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.result) {
console.log('RPC Response:', data.result);
// Output: { id: 123, name: 'Alice', age: 30 }
} else if (data.event === 'newMessage') {
console.log('New message:', data.data.text);
// Output: "Hello everyone!" (from other clients)
}
};
Key Points:
- Real-time bidirectional communication (client calls methods, server pushes events).
- Works like traditional RPC but over WebSockets (instead of HTTP).
2. TypeScript Version (RPC & REST)
Now, letβs rewrite the HTTP-based RPC and REST examples in TypeScript for better type safety.
(A) RPC Server (TypeScript)
import express, { Request, Response } from 'express';
interface RPCRequest {
method: string;
params: Record<string, any>;
}
interface User {
id: number;
name: string;
age: number;
}
const app = express();
app.use(express.json());
app.post('/rpc', (req: Request, res: Response) => {
const { method, params }: RPCRequest = req.body;
if (method === 'getUser') {
const user: User = { id: params.id, name: 'Alice', age: 30 };
res.json({ result: user });
} else {
res.status(404).json({ error: 'Method not found' });
}
});
app.listen(3000, () => console.log('TypeScript RPC Server running on http://localhost:3000'));
(B) REST Server (TypeScript)
import express, { Request, Response } from 'express';
interface User {
id: number;
name: string;
age: number;
}
const app = express();
let users: User[] = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 }
];
app.get('/users/:id', (req: Request, res: Response) => {
const user = users.find(u => u.id === parseInt(req.params.id));
res.json(user);
});
app.post('/users', (req: Request, res: Response) => {
const newUser: User = { id: users.length + 1, ...req.body };
users.push(newUser);
res.status(201).json(newUser);
});
app.listen(3001, () => console.log('TypeScript REST Server running on http://localhost:3001'));
Client (TypeScript)
// RPC Client
async function callRpcMethod(method: string, params: Record<string, any>) {
const response = await fetch('http://localhost:3000/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ method, params }),
});
return await response.json();
}
// Example usage
callRpcMethod('getUser', { id: 123 }).then(data => {
console.log(data.result); // { id: 123, name: 'Alice', age: 30 }
});
// REST Client
async function getUsers(id: number) {
const response = await fetch(`http://localhost:3001/users/${id}`);
return await response.json();
}
getUsers(1).then(user => {
console.log(user); // { id: 1, name: 'Alice', age: 30 }
});
Key Takeaways
| Feature | RPC (WebSockets/HTTP) | REST (HTTP) |
|---|---|---|
| Real-Time | β Yes (WebSockets) | β No (unless using polling/SSE) |
| Type Safety | β Strong (TypeScript) | β Strong (TypeScript) |
| Use Case | Live updates, gaming, chat apps | CRUD APIs, public-facing services |
| Scalability | Great for real-time | Great for caching & stateless ops |
Which One to Choose?
- Need real-time updates? β WebSockets + RPC (e.g., chat, live feeds).
- Building a standard API? β REST (simple, cache-friendly, works everywhere).
- Microservices/internal calls? β gRPC (high-performance binary RPC).
Would you like an example with gRPC + TypeScript or a performance comparison? Let me know! π