2024-07-27
#api
#rest
#websockets
#backend
#architecture

REST API & WebSockets

Understanding RESTful constraints, API design principles, and Real-time communication with WebSockets.

REST API (Representational State Transfer)

API (Application Programming Interface) A contract that defines how software components communicate. "If you send X to /endpoint, I promise to return Y."

REST is an architectural style for designing networked applications over HTTP.

Key Constraints (The Rules)

  1. Client-Server: Separation of concerns. UI (Client) is independent of Data/Logic (Server).
  2. Stateless: The server stores no client context between requests. Every request must contain all necessary information (Tokens, Filters).
  3. Cacheable: Responses must define themselves as cacheable or not.
  4. Uniform Interface:
    • Resource-Based: URLs represent resources (nouns), not actions (verbs).
      • /api/books (Good)
      • /api/getBooks (Bad)
    • Standard Methods: Use GET, POST, PUT, DELETE correctly.
    • Standard Codes: Use correct HTTP status codes (200, 404, etc.).

WebSockets

Problem: HTTP is Unidirectional (Request -> Response). The server cannot "push" data to the client without a request. Old Solution: Short Polling (Client asks "New data?" every second).

Solution: WebSockets A persistent, Bidirectional communication channel over a single TCP connection.

HTTP vs WebSocket

  • HTTP: Request/Response. High overhead (headers sent every time). Good for documents/CRUD.
  • WebSocket: Full-duplex stream. Low overhead after handshake. Good for Real-time.

When to use?

  • Use WebSockets:

    • Chat Applications (WhatsApp, Slack).
    • Multiplayer Games.
    • Live Trading/Stock tickers.
    • Collaborative editing (Figma, Google Docs).
    • Real-time Notifications.
  • Avoid WebSockets:

    • Simple CMS / Blogs.
    • RESTful CRUD operations (GET/POST is sufficient and easier to cache/scale).
    • If browser compatibility is a major concern (though modern support is >95%).

Connected Thoughts

Egor Zdioruc | Lead Full Stack Developer | Laravel & AI Solutions