Development Fundamentals

Back to Software Development Index

API Development

What is an API?

API (Application Programming Interface) คือชุดของกฎและโปรโตคอลที่กำหนดวิธีการที่ซอฟต์แวร์ต่างๆ สามารถสื่อสารกันได้

RESTful API

REST (Representational State Transfer) เป็นสถาปัตยกรรมที่นิยมใช้ในการออกแบบ web services

Key Principles:

  • Stateless - แต่ละ request มีข้อมูลครบถ้วน
  • Client-Server - แยกความรับผิดชอบชัดเจน
  • Cacheable - Response สามารถ cache ได้
  • Uniform Interface - ใช้ HTTP methods มาตรฐาน

HTTP Methods:

  • GET - ดึงข้อมูล (Read)
  • POST - สร้างข้อมูลใหม่ (Create)
  • PUT - อัพเดตข้อมูลทั้งหมด (Update)
  • PATCH - อัพเดตข้อมูลบางส่วน (Partial Update)
  • DELETE - ลบข้อมูล (Delete)

Status Codes:

2xx Success
├─ 200 OK
├─ 201 Created
└─ 204 No Content

3xx Redirection
├─ 301 Moved Permanently
└─ 304 Not Modified

4xx Client Error
├─ 400 Bad Request
├─ 401 Unauthorized
├─ 403 Forbidden
└─ 404 Not Found

5xx Server Error
├─ 500 Internal Server Error
└─ 503 Service Unavailable

Example:

GET    /api/users           # Get all users
GET    /api/users/1         # Get user by id
POST   /api/users           # Create new user
PUT    /api/users/1         # Update user
DELETE /api/users/1         # Delete user

API Best Practices

1. Use Nouns for Resources

✅ /api/users
✅ /api/products
❌ /api/getUsers
❌ /api/createProduct

2. Use Proper HTTP Methods

✅ GET /api/users/1
❌ POST /api/users/get/1

3. Versioning

/api/v1/users
/api/v2/users

4. Pagination

GET /api/users?page=1&limit=20

5. Filtering & Sorting

GET /api/users?role=admin&sort=created_at

6. Error Handling

{
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "User with id 123 not found",
    "details": {}
  }
}

Resources

สามารถศึกษาเพิ่มเติมได้ที่: RESTful API Design Guide


Blockchain Basics

What is Blockchain?

Blockchain คือเทคโนโลยีที่เก็บข้อมูลในรูปแบบของ chain of blocks ที่เชื่อมโยงกันด้วย cryptography

Key Concepts:

Block Structure

┌─────────────────────────┐
│   Block Header          │
├─────────────────────────┤
│ - Previous Hash         │
│ - Timestamp             │
│ - Nonce                 │
│ - Merkle Root           │
├─────────────────────────┤
│   Transactions          │
│ - Transaction 1         │
│ - Transaction 2         │
│ - Transaction 3         │
└─────────────────────────┘

Chain Structure

Block 1 → Block 2 → Block 3 → Block 4
  ↓         ↓         ↓         ↓
Hash 1    Hash 2    Hash 3    Hash 4

Core Principles

1. Decentralization (กระจายอำนาจ)

ไม่มีองค์กรกลางควบคุม ข้อมูลกระจายอยู่หลายๆ nodes

Traditional vs Blockchain:

Traditional:          Blockchain:
    [Server]          [Node] [Node]
      ↙  ↓  ↘          ↙ ↓ ↘ ↓ ↙
   [C] [C] [C]      [Node] [Node]
                         ↓
                      [Node]

Benefits:

  • ไม่มี single point of failure
  • โปร่งใส ตรวจสอบได้
  • ไม่สามารถแก้ไขข้อมูลได้ง่าย

2. Immutability (ไม่สามารถแก้ไขได้)

เมื่อข้อมูลถูกบันทึกลง blockchain แล้ว จะแก้ไขไม่ได้

Why?

  • แต่ละ block มี hash ของ block ก่อนหน้า
  • ถ้าแก้ไข block หนึ่ง hash จะเปลี่ยน
  • ทำให้ chain ขาด ต้องแก้ทุก block ถัดไป

3. Consensus Mechanisms (กลไกการตกลงยอมรับ)

วิธีที่ nodes ในเครือข่ายตกลงยอมรับว่า transaction ไหนถูกต้อง

Proof of Work (PoW):

  • ต้องแก้โจทย์คณิตศาสตร์ที่ยาก
  • ใช้พลังงานมาก
  • ปลอดภัยสูง
  • Example: Bitcoin
Miner 1 → [Calculating...] → Found! → Add Block
Miner 2 → [Calculating...] → Too late
Miner 3 → [Calculating...] → Too late

Proof of Stake (PoS):

  • เลือก validator ตามจำนวนเหรียญที่ stake
  • ประหยัดพลังงาน
  • เร็วกว่า PoW
  • Example: Ethereum 2.0
Validator Selection based on:
- Amount staked
- Random selection
- Age of stake

Blockchain Terminology

Hash:

  • ลายเซ็นดิจิทัลที่ unique
  • เปลี่ยนแปลงไม่ได้ (deterministic)
  • ใช้ SHA-256

Nonce:

  • Number used once
  • ใช้ใน mining เพื่อหา valid hash

Merkle Tree:

  • โครงสร้างข้อมูลที่เก็บ transactions
  • สามารถ verify ได้เร็ว

Smart Contract:

  • โค้ดที่รันบน blockchain
  • Execute automatically เมื่อตรงตามเงื่อนไข

Use Cases

1. Cryptocurrency

  • Bitcoin, Ethereum, etc.
  • Digital payments

2. Supply Chain

  • Track products from origin
  • Verify authenticity

3. Healthcare

  • Patient records
  • Drug traceability

4. Voting Systems

  • Transparent voting
  • Prevent fraud

5. Digital Identity

  • Self-sovereign identity
  • Privacy control

Programming Type Systems

What is a Type System?

Type system เป็นกฎเกณฑ์ที่กำหนดว่าตัวแปรสามารถเก็บข้อมูลประเภทใดได้

1. Strong vs Weak Typing

Strong Typing

ไม่ยอมให้แปลง type โดยอัตโนมัติ ต้องแปลงชัดเจน (explicit conversion)

Go Example (Strong):

var x int = 10
var y float64 = 3.14
 
// ❌ Error: cannot use x (type int) in assignment
// y = x
 
// ✅ Must explicitly convert
y = float64(x)

Benefits:

  • ป้องกัน type errors
  • Code ปลอดภัยกว่า
  • Catch errors at compile time

Weak Typing

ยอมให้แปลง type โดยอัตโนมัติ (implicit conversion)

JavaScript Example (Weak):

let x = 10;        // number
let y = "5";       // string
 
// ✅ JavaScript auto-converts
console.log(x + y);        // "105" (string concatenation)
console.log(x - y);        // 5 (number subtraction)
console.log("3" * "4");    // 12 (both converted to numbers)

Issues:

  • Unexpected behavior
  • Hard to debug
  • Runtime errors

2. Static vs Dynamic Typing

Static Typing

Type checking ตอน compile time

Go Example:

var name string = "John"
var age int = 30
 
// ❌ Error: cannot use "hello" (type string) as type int
// age = "hello"
 
func greet(name string) string {
    return "Hello, " + name
}
 
// ❌ Error: cannot use 123 (type int) as type string
// greet(123)

Benefits:

  • Errors caught early (compile time)
  • Better IDE support (autocomplete)
  • Better performance (no runtime checks)
  • Self-documenting code

Languages: Go, Java, C++, TypeScript, Rust

Dynamic Typing

Type checking ตอน runtime

JavaScript Example:

let x = 10;          // number
x = "hello";         // ✅ OK, now string
x = true;            // ✅ OK, now boolean
x = [1, 2, 3];       // ✅ OK, now array
 
function greet(name) {
    return "Hello, " + name;
}
 
greet("John");       // ✅ OK
greet(123);          // ✅ OK (converts to string)
greet({});           // ✅ OK (converts to "[object Object]")

Benefits:

  • Flexible
  • Faster to write
  • No type declarations needed

Drawbacks:

  • Errors only at runtime
  • Harder to refactor
  • Need more tests

Languages: Python, JavaScript, Ruby, PHP

Type System Comparison

StaticDynamic
Check TimeCompileRuntime
Errors CaughtEarlyLate
FlexibilityLowHigh
PerformanceFastSlower
IDE SupportExcellentGood
ExamplesGo, JavaPython, JS
StrongWeak
ConversionExplicitImplicit
SafetyHighLow
StrictnessStrictLoose
ExamplesGo, PythonJavaScript, PHP

Combinations

Static + Strong:

  • Go, Java, Rust
  • Safest, most predictable
  • Best for large projects

Static + Weak:

  • C (somewhat)
  • Fast but risky

Dynamic + Strong:

  • Python
  • Flexible but safe

Dynamic + Weak:

  • JavaScript (old)
  • Most flexible, least safe

Modern Solutions

TypeScript:

  • JavaScript + static typing
  • Best of both worlds
  • Optional type system
// With types
function greet(name: string): string {
    return "Hello, " + name;
}
 
// Still runs as JavaScript
greet("John");

Which to Choose?

Use Static + Strong When:

  • Large codebase
  • Multiple developers
  • Long-term project
  • Performance critical
  • Safety critical

Use Dynamic + Strong When:

  • Rapid prototyping
  • Small scripts
  • Data analysis
  • Quick iterations

Use Dynamic + Weak When:

  • Simple web pages
  • Legacy code
  • Quick scripts
  • Learning programming

Related:

References: