VibeKoding / Ensiklopedia ยท Fondasi KuatEnsiklopedia ยท Fondasi Kuat / Principles of HTTP Protocol: Frontend-Backend CommunicationPrinciples of HTTP Protocol: Frontend-Backend Communication
VK

Principles of HTTP Protocol: Frontend-Backend CommunicationPrinciples of HTTP Protocol: Frontend-Backend Communication

๐Ÿ“š Ensiklopedia ยท Fondasi KuatEnsiklopedia ยท Fondasi Kuat ๐ŸŒ Dual Bahasa (ID / EN) โšก VibeKoding Native

Ensiklopedia VibeKoding: Principles of HTTP Protocol: Frontend-Backend Communication.Ensiklopedia VibeKoding: Principles of HTTP Protocol: Frontend-Backend Communication.

๐Ÿ’ก Tips Praktis๐Ÿ’ก Pro Tip

How does HTTP work? It's like asking: how do two people hold a conversation? They need to agree on a language, grammar, and conversation rules. HTTP is the "conversation protocol" between frontend and backend.How does HTTP work? It's like asking: how do two people hold a conversation? They need to agree on a language, grammar, and conversation rules. HTTP is the "conversation protocol" between frontend and backend.

------

0. The Essence of HTTP0. The Essence of HTTP

HTTP (HyperText Transfer Protocol) is the foundational protocol for frontend-backend communication.HTTP (HyperText Transfer Protocol) is the foundational protocol for frontend-backend communication.

0.1 Communication Analogy0.1 Communication Analogy

Conversation ElementHTTP EquivalentDescription
LanguageHTTP protocolA language both sides can understand
GrammarRequest/response formatHow to "speak"
FlowRequest-response patternOne question, one answer
EndingHang upTCP connection closes

------

1. HTTP's Evolution1. HTTP's Evolution

HTTP has undergone several major upgrades since its creation in 1991.HTTP has undergone several major upgrades since its creation in 1991.

1.1 Version Comparison1.1 Version Comparison

VersionYearCore ImprovementKey Feature
HTTP/0.91991Only supported GETPlain text only, no response headers
HTTP/1.01996Added POST/HEADOne TCP connection per request
HTTP/1.11997Persistent connectionsKeep-Alive, multiple requests per connection
HTTP/22015MultiplexingBinary frames, header compression
HTTP/32022Based on QUICUDP transport, solves head-of-line blocking
๐Ÿ’ก Tips Praktis๐Ÿ’ก Pro Tip

Although HTTP/1.1 supports persistent connections, requests must be sent sequentially (the next request can only be sent after the previous response returns). HTTP/2 solves this problem through multiplexing, allowing multiple requests to be sent simultaneously.Although HTTP/1.1 supports persistent connections, requests must be sent sequentially (the next request can only be sent after the previous response returns). HTTP/2 solves this problem through multiplexing, allowing multiple requests to be sent simultaneously.

------

2. Structure of an HTTP Request2. Structure of an HTTP Request

2.1 Request Line2.1 Request Line

http
GET /api/users/123 HTTP/1.1

Contains three parts:Contains three parts:

2.2 Request Headers2.2 Request Headers

http
Host: api.example.com User-Agent: Mozilla/5.0 Accept: application/json Authorization: Bearer xxx Content-Type: application/json Content-Length: 45

Common request headers:Common request headers:

HeaderDescriptionExample
HostServer domainapi.example.com
User-AgentClient informationMozilla/5.0
AcceptAccepted response typesapplication/json
AuthorizationAuthentication informationBearer token
Content-TypeRequest body typeapplication/json

2.3 Request Body2.3 Request Body

json
{ "name": "Zhang San", "email": "zhangsan@example.com" }

Only POST, PUT, PATCH, and similar methods have a request body.Only POST, PUT, PATCH, and similar methods have a request body.

------

3. Structure of an HTTP Response3. Structure of an HTTP Response

3.1 Status Line3.1 Status Line

http
HTTP/1.1 200 OK

Contains three parts:Contains three parts:

3.2 Response Headers3.2 Response Headers

http
Content-Type: application/json Content-Length: 156 Cache-Control: max-age=3600 Set-Cookie: session=xxx; HttpOnly

Common response headers:Common response headers:

HeaderDescriptionExample
Content-TypeResponse body typeapplication/json
Content-LengthResponse body size156
Cache-ControlCache policymax-age=3600
Set-CookieSet Cookiesession=xxx

3.3 Response Body3.3 Response Body

json
{ "code": 0, "data": { "id": 123, "name": "Zhang San" } }

------

4. HTTP Methods in Detail4. HTTP Methods in Detail

MethodPurposeRequest BodyIdempotentSafe
GETRetrieve resourceNoneYesYes
POSTCreate resourceYesNoNo
PUTFull updateYesYesNo
PATCHPartial updateYesNoNo
DELETEDelete resourceNoneYesNo
HEADGet headers onlyNoneYesYes
OPTIONSQuery supported methodsNoneYesYes

4.1 GET vs POST4.1 GET vs POST

FeatureGETPOST
Parameter locationURL query parametersRequest body
CachingCacheableNot cached by default
BookmarksCan be bookmarkedCannot
Browser historySaved in historyNot saved
Data lengthLimited (URL length)Unlimited
SecurityParameters visible in URLParameters in request body
๐Ÿ’ก Tips Praktis๐Ÿ’ก Pro Tip

- GET: Query, retrieve data - POST: Create, submit data - PUT: Full update (replace the entire resource) - PATCH: Partial update (only modify specified fields) - DELETE: Delete a resource- GET: Query, retrieve data - POST: Create, submit data - PUT: Full update (replace the entire resource) - PATCH: Partial update (only modify specified fields) - DELETE: Delete a resource

------

5. HTTP Status Codes5. HTTP Status Codes

5.1 Status Code Categories5.1 Status Code Categories

CategoryDescriptionTypical Status Codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirection301 Permanent, 302 Temporary, 304 Not Modified
4xxClient error400 Bad Request, 401 Unauthorized, 404 Not Found
5xxServer error500 Internal Server Error, 503 Service Unavailable

5.2 Common Status Codes5.2 Common Status Codes

Status CodeDescriptionUse Case
200 OKRequest succeededSuccessful GET, PUT request
201 CreatedResource createdSuccessful POST creating a resource
204 No ContentNo contentSuccessful DELETE
301 Moved PermanentlyPermanent redirectURL permanently changed
302 FoundTemporary redirectURL temporarily changed
304 Not ModifiedNot modifiedCache still valid
400 Bad RequestBad requestMalformed request parameters
401 UnauthorizedUnauthorizedLogin required
403 ForbiddenForbiddenLogged in but insufficient permissions
404 Not FoundNot foundResource doesn't exist
500 Internal Server ErrorInternal errorServer exception
503 Service UnavailableUnavailableServer maintenance or overload

------

6. HTTPS: Secure HTTP6. HTTPS: Secure HTTP

6.1 HTTP vs HTTPS6.1 HTTP vs HTTPS

FeatureHTTPHTTPS
ProtocolTCPTCP + SSL/TLS
Port80443
DataPlaintextEncrypted
CertificateNot requiredSSL certificate required
PerformanceSlightly fasterSlightly slower (handshake overhead)
SEONo effectSearch engines prioritize HTTPS

6.2 How HTTPS Works6.2 How HTTPS Works

  1. Client Hello: Client sends supported cipher suitesClient Hello: Client sends supported cipher suites
  2. Server Hello: Server returns certificate and selected cipher suiteServer Hello: Server returns certificate and selected cipher suite
  3. Certificate verification: Client verifies the server certificate's validityCertificate verification: Client verifies the server certificate's validity
  4. Key exchange: Use asymmetric encryption to exchange a session keyKey exchange: Use asymmetric encryption to exchange a session key
  5. Encrypted communication: Use the session key for symmetric encryptionEncrypted communication: Use the session key for symmetric encryption
  6. ๐Ÿ’ก Tips Praktis๐Ÿ’ก Pro Tip

    - Anti-eavesdropping: Data is encrypted; third parties cannot read it - Anti-tampering: Data integrity verification - Anti-impersonation: SSL certificates verify server identity- Anti-eavesdropping: Data is encrypted; third parties cannot read it - Anti-tampering: Data integrity verification - Anti-impersonation: SSL certificates verify server identity

    ------

    7. HTTP Caching Mechanism7. HTTP Caching Mechanism

    7.1 Cache Headers7.1 Cache Headers

    HeaderDescriptionExample
    Cache-ControlCache policymax-age=3600
    ETagResource version identifier"33a64df551425fcc"
    Last-ModifiedLast modified timeWed, 21 Oct 2015 07:28:00 GMT

    7.2 Caching Strategies7.2 Caching Strategies

    Strong caching:Strong caching:

    http
    Cache-Control: max-age=3600
    

    Within 3600 seconds, the browser uses the cache directly without sending a request.Within 3600 seconds, the browser uses the cache directly without sending a request.

    Negotiated caching:Negotiated caching:

    http
    ETag: "33a64df551425fcc"
    

    The browser sends If-None-Match; the server returns 304 (not modified) or 200 (modified).The browser sends If-None-Match; the server returns 304 (not modified) or 200 (modified).

    ------

    8. Common Questions8. Common Questions

    8.1 The Real Difference Between GET and POST8.1 The Real Difference Between GET and POST

    Misconception: The only difference between GET and POST is where parameters are placed.Misconception: The only difference between GET and POST is where parameters are placed.

    The truth:The truth:

    • GET is idempotent; multiple requests produce the same resultGET is idempotent; multiple requests produce the same result
    • POST is non-idempotent; multiple requests may create multiple resourcesPOST is non-idempotent; multiple requests may create multiple resources
    • GET can be cached; POST is not cached by defaultGET can be cached; POST is not cached by default
    • GET can be bookmarked; POST cannotGET can be bookmarked; POST cannot

    8.2 HTTP/1.1 Head-of-Line Blocking8.2 HTTP/1.1 Head-of-Line Blocking

    The problem: Although HTTP/1.1 supports persistent connections, requests must be sent sequentially. If a previous request's response is slow, all subsequent requests must wait.The problem: Although HTTP/1.1 supports persistent connections, requests must be sent sequentially. If a previous request's response is slow, all subsequent requests must wait.

    Solutions:Solutions:

    • HTTP/2 multiplexingHTTP/2 multiplexing
    • Domain sharding (multiple domains for multiple connections)Domain sharding (multiple domains for multiple connections)
    • Connection pooling (limiting concurrency)Connection pooling (limiting concurrency)

    8.3 HTTP/2 Advantages8.3 HTTP/2 Advantages

    FeatureHTTP/1.1HTTP/2
    Transmission formatTextBinary frames
    MultiplexingNot supportedSupported
    Header compressionNoneHPACK algorithm
    Server pushNot supportedSupported

    ------

    GlossaryGlossary

    TermFull NameDescription
    HTTPHyperText Transfer ProtocolThe foundational web communication protocol
    HTTPSHTTP SecureHTTP + SSL/TLS
    TCPTransmission Control ProtocolReliable transport protocol
    SSL/TLSSecure Sockets LayerSecurity protocol layer
    Idempotent-Multiple requests produce the same result
    Keep-Alive-Sending multiple requests over one TCP connection
    Multiplexing-Sending multiple requests simultaneously
    Head-of-Line Blocking-Earlier requests blocking later ones