<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ http - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ http - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 25 Aug 2026 22:03:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/http/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Clients and Servers Communicate: Full Handbook on HTTP/1.1, HTTP/2, REST, WebSockets, GraphQL, gRPC, and Protocol Buffers ]]>
                </title>
                <description>
                    <![CDATA[ You've built and consumed APIs. You know what a GET request is, what a JSON response looks like, and how to add an Authorization header. You've used REST, maybe tried GraphQL, and perhaps heard of gRP ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-clients-and-servers-communicate-handbook-http-rest-websockets-graphql-grpc-protobuf/</link>
                <guid isPermaLink="false">6a62a069f97a6bd65ce3cd8f</guid>
                
                    <category>
                        <![CDATA[ server ]]>
                    </category>
                
                    <category>
                        <![CDATA[ clients ]]>
                    </category>
                
                    <category>
                        <![CDATA[ networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software ]]>
                    </category>
                
                    <category>
                        <![CDATA[ engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ gRPC ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http2 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ protobuf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwaseyi Fatunmole ]]>
                </dc:creator>
                <pubDate>Thu, 23 Jul 2026 23:14:49 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/b44f7067-5398-492a-b1f7-789f73673c34.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You've built and consumed APIs. You know what a GET request is, what a JSON response looks like, and how to add an Authorization header. You've used REST, maybe tried GraphQL, and perhaps heard of gRPC.</p>
<p>But do you know what actually happens when your application sends a request? What travels through the wire? Why does HTTP/2 make things faster? Why do WebSockets exist when HTTP already works? What makes Protocol Buffers different from JSON at a fundamental level?</p>
<p>And when you're designing a system, how do you decide which communication approach to use?</p>
<p>These are the questions this handbook answers.</p>
<p>This isn't a beginner's guide to APIs. This is a deep dive into how clients and servers actually communicate: the protocols, the trade-offs, the history of why each approach was built, and the engineering thinking behind choosing one over another.</p>
<p>By the end, you won't just know what these technologies are. You'll understand why they exist, how they work at a level that makes you a better engineer, and how to make deliberate architectural decisions about communication in your systems.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#the-foundation-how-two-machines-talk-to-each-other">The Foundation: How Two Machines Talk to Each Other</a></p>
</li>
<li><p><a href="#http11-the-protocol-that-built-the-web">HTTP/1.1: The Protocol That Built the Web</a></p>
</li>
<li><p><a href="#the-problems-http11-could-not-solve">The Problems HTTP/1.1 Could Not Solve</a></p>
</li>
<li><p><a href="#http2-rebuilding-the-foundation">HTTP/2: Rebuilding the Foundation</a></p>
</li>
<li><p><a href="#http3-and-quic-the-next-evolution">HTTP/3 and QUIC: The Next Evolution</a></p>
</li>
<li><p><a href="#data-formats-how-information-is-encoded">Data Formats: How Information Is Encoded</a></p>
</li>
<li><p><a href="#rest-the-architecture-that-took-over-the-world">REST: The Architecture That Took Over the World</a></p>
</li>
<li><p><a href="#the-limits-of-rest">The Limits of REST</a></p>
</li>
<li><p><a href="#graphql-letting-the-client-decide">GraphQL: Letting the Client Decide</a></p>
</li>
<li><p><a href="#websockets-when-http-is-not-enough">WebSockets: When HTTP Is Not Enough</a></p>
</li>
<li><p><a href="#server-sent-events-the-simpler-real-time-option">Server-Sent Events: The Simpler Real-Time Option</a></p>
</li>
<li><p><a href="#protocol-buffers-a-new-language-for-data">Protocol Buffers: A New Language for Data</a></p>
</li>
<li><p><a href="#grpc-remote-procedure-calls-at-scale">gRPC: Remote Procedure Calls at Scale</a></p>
</li>
<li><p><a href="#the-complete-comparison">The Complete Comparison</a></p>
</li>
<li><p><a href="#how-to-choose-the-engineering-decision-framework">How to Choose: The Engineering Decision Framework</a></p>
</li>
<li><p><a href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-the-foundation-how-two-machines-talk-to-each-other">The Foundation: How Two Machines Talk to Each Other</h2>
<p>Before any protocol, data format, or architectural style enters the picture, two machines need to establish a connection. Understanding this foundation makes everything else click.</p>
<h3 id="heading-ip-addresses-and-ports">IP Addresses and Ports</h3>
<p>Every device on a network has an IP address: a unique identifier that works like a postal address. When your application sends a request to <code>api.example.com</code>, the first thing that happens is a DNS lookup, which translates that human-readable name into an IP address like <code>93.184.216.34</code>. That IP address is where the packet is going.</p>
<p>But an IP address alone isn't enough. A single server might be running dozens of different services simultaneously: a web server, a database, an email server, an SSH daemon.</p>
<p>Ports tell the operating system which service should handle the incoming connection. Port 80 is the conventional port for HTTP. Port 443 is for HTTPS. Port 5432 is for PostgreSQL. Port 22 is for SSH. When you call <code>api.example.com/users</code>, you are actually calling <code>api.example.com:443/users</code>. The browser fills in the port automatically.</p>
<h3 id="heading-tcp-the-reliable-foundation">TCP: The Reliable Foundation</h3>
<p>Most web communication runs over TCP (Transmission Control Protocol). TCP is a connection-oriented protocol, which means before any data is exchanged, both parties go through a handshake to establish a connection.</p>
<p>The TCP handshake works in three steps, which is why it's called the three-way handshake:</p>
<pre><code class="language-plaintext">Client                    Server
  |                          |
  |-------- SYN -----------&gt;|   "I want to connect"
  |                          |
  |&lt;------- SYN-ACK --------|   "Okay, I acknowledge. Ready?"
  |                          |
  |-------- ACK -----------&gt;|   "Great, let's go"
  |                          |
  [Connection established]
</code></pre>
<p>SYN stands for synchronize. ACK stands for acknowledge. After these three packets, the connection exists and data can flow.</p>
<p>TCP guarantees three things that make it the foundation of reliable communication:</p>
<ol>
<li><p><strong>Delivery</strong>: if a packet is lost in transit, TCP detects this and retransmits it automatically. The application layer never has to worry about lost packets.</p>
</li>
<li><p><strong>Order</strong>: packets arrive in the same order they were sent. If packets arrive out of order (which happens frequently on real networks), TCP reorders them before delivering them to the application.</p>
</li>
<li><p><strong>Error detection</strong>: every TCP packet includes a checksum. If the data is corrupted in transit, TCP detects and discards the corrupted packet, then requests a retransmission.</p>
</li>
</ol>
<p>This reliability comes at a cost: the overhead of the handshake, the acknowledgment packets, and the retransmission logic.</p>
<p>For many use cases, this cost is worth it. For some (live video streaming, online gaming, DNS lookups), UDP (User Datagram Protocol) is preferred because it sends packets without any of this overhead, accepting some loss in exchange for speed. HTTP/3, which we'll cover later, is built on a protocol that brings reliability to UDP.</p>
<h3 id="heading-tls-encrypting-the-connection">TLS: Encrypting the Connection</h3>
<p>On the modern web, most connections use HTTPS rather than plain HTTP. The S stands for Secure, and the security is provided by TLS (Transport Layer Security), the successor to SSL.</p>
<p>TLS adds an additional handshake on top of the TCP connection. During the TLS handshake:</p>
<ol>
<li><p>The client and the server agree on which version of TLS to use and which encryption algorithms to support</p>
</li>
<li><p>The server presents its digital certificate (issued by a trusted Certificate Authority)</p>
</li>
<li><p>The client verifies the certificate is valid and belongs to the server it intended to reach</p>
</li>
<li><p>They exchange encryption keys using asymmetric cryptography</p>
</li>
<li><p>From that point forward, all communication is encrypted with symmetric encryption</p>
</li>
</ol>
<p>The TLS handshake adds latency. In TLS 1.2, it takes two round trips before any application data can flow. TLS 1.3, released in 2018, reduced this to one round trip, and even supports zero round-trip resumption for returning connections.</p>
<p>Understanding TCP and TLS matters because every protocol we discuss runs on top of them (until HTTP/3, which changes the underlying transport). When people talk about the "overhead" of HTTPS or the "cost" of establishing a connection, they're talking about the time and packets spent on these handshakes before a single byte of your actual request travels.</p>
<h2 id="heading-http11-the-protocol-that-built-the-web">HTTP/1.1: The Protocol That Built the Web</h2>
<p>HTTP (HyperText Transfer Protocol) was invented by Tim Berners-Lee in 1991 to transfer HTML documents between computers. HTTP/1.0 was simple: one request per connection, then the connection closes.</p>
<p>HTTP/1.1, standardized in 1997, brought significant improvements and became the dominant version of HTTP for nearly two decades. It introduced persistent connections (keep connections open across multiple requests), chunked transfer encoding, and more sophisticated caching mechanisms.</p>
<h3 id="heading-how-an-http11-request-works">How an HTTP/1.1 Request Works</h3>
<p>An HTTP request is a text message with a specific structure:</p>
<pre><code class="language-plaintext">POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Accept: application/json
Content-Length: 45
User-Agent: MyApp/2.0

{"name": "John Smith", "email": "john@example.com"}
</code></pre>
<p>The first line is the request line: the HTTP method (POST), the path (/api/users), and the protocol version.</p>
<p>Below that are the headers: key-value pairs that provide metadata about the request. The host, the content type, the authorization token, what format the client accepts, and how large the body is.</p>
<p>After a blank line comes the body: the actual data being sent.</p>
<p>The server processes this and responds:</p>
<pre><code class="language-plaintext">HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/users/usr_789
Date: Mon, 21 Jul 2026 09:15:00 GMT
Content-Length: 89

{"id": "usr_789", "name": "John Smith", "email": "john@example.com", "created_at": "..."}
</code></pre>
<p>The response has a status line (the protocol version, the status code, and a reason phrase), headers, and a body.</p>
<h3 id="heading-http-methods-and-their-semantics">HTTP Methods and Their Semantics</h3>
<p>HTTP/1.1 defines several methods, each with specific semantics:</p>
<ul>
<li><p><strong>GET</strong> retrieves a resource. A GET request should have no side effects. It shouldn't create or modify anything. It's safe and idempotent, meaning calling it multiple times has the same effect as calling it once.</p>
</li>
<li><p><strong>POST</strong> submits data to create a new resource or trigger an action. It's neither safe nor idempotent: calling POST twice typically creates two resources.</p>
</li>
<li><p><strong>PUT</strong> replaces a resource entirely with the provided data. It's idempotent: calling PUT twice with the same data has the same effect as calling it once.</p>
</li>
<li><p><strong>PATCH</strong> partially updates a resource. Only the fields provided are changed.</p>
</li>
<li><p><strong>DELETE</strong> removes a resource. It's idempotent: deleting something that doesn't exist is still considered successful.</p>
</li>
<li><p><strong>HEAD</strong> is identical to GET but the server only returns headers, not the body. It's used to check if a resource exists or has been modified without downloading the full content.</p>
</li>
<li><p><strong>OPTIONS</strong> asks the server what methods are allowed for a resource. It's used in CORS preflight requests.</p>
</li>
</ul>
<h3 id="heading-status-codes">Status Codes</h3>
<p>HTTP status codes are three-digit numbers grouped into five categories:</p>
<p><strong>1xx Informational</strong> — the server has received the request and is continuing to process it. These are rarely seen in practice outside of specific use cases like HTTP upgrade (used to establish WebSocket connections).</p>
<p><strong>2xx Success</strong> — the request was received, understood, and accepted.</p>
<ul>
<li><p>200 OK: standard success response</p>
</li>
<li><p>201 Created: a new resource was created</p>
</li>
<li><p>204 No Content: success but nothing to return (common for DELETE)</p>
</li>
</ul>
<p><strong>3xx Redirection</strong> — further action is required to complete the request.</p>
<ul>
<li><p>301 Moved Permanently: the resource has a new URL forever</p>
</li>
<li><p>302 Found: temporary redirect</p>
</li>
<li><p>304 Not Modified: the cached version is still valid (used with ETags)</p>
</li>
</ul>
<p><strong>4xx Client Error</strong> — the request contains bad syntax or can't be fulfilled.</p>
<ul>
<li><p>400 Bad Request: the request is malformed</p>
</li>
<li><p>401 Unauthorized: authentication is required (despite the name, it means unauthenticated)</p>
</li>
<li><p>403 Forbidden: authenticated but not authorized to access this resource</p>
</li>
<li><p>404 Not Found: the resource doesn't exist</p>
</li>
<li><p>422 Unprocessable Entity: the request is syntactically valid but semantically wrong (common for validation errors)</p>
</li>
<li><p>429 Too Many Requests: rate limit exceeded</p>
</li>
</ul>
<p><strong>5xx Server Error</strong> — the server failed to fulfill a valid request.</p>
<ul>
<li><p>500 Internal Server Error: something went wrong on the server</p>
</li>
<li><p>502 Bad Gateway: the server received an invalid response from an upstream server</p>
</li>
<li><p>503 Service Unavailable: the server is temporarily unavailable</p>
</li>
<li><p>504 Gateway Timeout: the upstream server did not respond in time</p>
</li>
</ul>
<h3 id="heading-caching-in-http11">Caching in HTTP/1.1</h3>
<p>One of HTTP/1.1's most powerful features is its built-in caching model. Responses can include headers that tell clients and intermediate caches how long to store a response and when to revalidate it.</p>
<ul>
<li><p><code>Cache-Control: max-age=3600</code> tells the client to cache this response for one hour.</p>
</li>
<li><p><code>Cache-Control: no-cache</code> tells the client to always revalidate with the server before using a cached response.</p>
</li>
<li><p><code>Cache-Control: no-store</code> tells the client never to cache this response.</p>
</li>
</ul>
<p><code>ETag</code> is a fingerprint of the response content. When the client makes a subsequent request, it sends the ETag back in an <code>If-None-Match</code> header. If the content hasn't changed, the server responds with 304 Not Modified and no body, saving bandwidth.</p>
<p><code>Last-Modified</code> works similarly: the client sends <code>If-Modified-Since</code> and the server confirms whether the content has changed.</p>
<p>Caching is one of the key reasons REST over HTTP became dominant. GET requests to well-designed REST APIs can be cached at the CDN level, meaning the same response is served to thousands of users without the request ever reaching your origin server.</p>
<h2 id="heading-the-problems-http11-could-not-solve">The Problems HTTP/1.1 Could Not Solve</h2>
<p>HTTP/1.1 served the web well for two decades. But as the web grew more complex, applications more dynamic, and user expectations higher, its architectural limitations became significant performance bottlenecks.</p>
<h3 id="heading-head-of-line-blocking">Head-of-Line Blocking</h3>
<p>HTTP/1.1 processes requests sequentially on a single connection. The server must finish responding to one request before the next one on the same connection begins.</p>
<pre><code class="language-plaintext">Connection 1:
Request 1 (slow database query) -----&gt; [3 seconds] -----&gt; Response 1
Request 2 (fast in-memory read) -----&gt; [waits 3 seconds] -----&gt; Response 2
Request 3 (static file) -----------&gt; [waits 3+ seconds] -----&gt; Response 3
</code></pre>
<p>Request 2 and Request 3 are fast operations. But they're stuck waiting for Request 1 to complete. This is head-of-line blocking: the head of the queue blocks everything behind it.</p>
<p>Browsers worked around this by opening multiple parallel TCP connections to the same server, typically six. But each connection requires its own TCP handshake and TLS negotiation, consuming resources on both the client and server.</p>
<h3 id="heading-verbose-headers-on-every-request">Verbose Headers on Every Request</h3>
<p>Every HTTP/1.1 request sends its complete headers as plain text. Consider a mobile application making fifty requests during a session. On every single request, the following headers are sent in full:</p>
<pre><code class="language-plaintext">Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfMTIzIn0...
Content-Type: application/json
Accept: application/json
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)...
</code></pre>
<p>The Authorization header alone, carrying a JWT, can be 400 to 600 bytes. Multiplied by fifty requests, that is 20 to 30 kilobytes of data carrying nothing but headers that haven't changed between requests.</p>
<p>On a 4G mobile connection with limited bandwidth, this is waste. On a 2G connection in a network-constrained environment, it's a significant performance penalty.</p>
<h3 id="heading-no-server-push">No Server Push</h3>
<p>HTTP/1.1 is strictly request-response. The server can't send data until the client asks for it. This fundamental limitation means the server can never proactively inform the client of changes.</p>
<p>For applications requiring real-time updates, short polling became a common workaround: the client sends a request every few seconds asking "has anything changed?" This is inefficient because most polling requests receive a "no, nothing has changed" response, consuming bandwidth and server resources for no purpose.</p>
<p>Long polling was a refinement: the client sends a request and the server holds it open until something changes or a timeout occurs. This reduces unnecessary responses but keeps connections open indefinitely, consuming server resources.</p>
<p>Both are workarounds for a fundamental limitation of HTTP/1.1's request-response model.</p>
<h3 id="heading-inefficient-use-of-connections">Inefficient Use of Connections</h3>
<p>Opening a new TCP connection requires the three-way handshake plus the TLS handshake: a process that can take 200 to 500 milliseconds on a mobile connection.</p>
<p>HTTP/1.1 introduced keep-alive connections to reuse connections across multiple requests, but head-of-line blocking made this only partially effective. Browsers opened multiple connections to compensate, but six parallel connections per domain is both a client limitation and a server resource concern at scale.</p>
<h2 id="heading-http2-rebuilding-the-foundation">HTTP/2: Rebuilding the Foundation</h2>
<p>Google published a protocol called SPDY (pronounced "speedy") in 2009, designed to address HTTP/1.1's performance limitations. SPDY demonstrated that significant improvements were possible without changing the fundamental HTTP semantics. HTTP/2, standardized by the IETF in 2015, was heavily based on SPDY and became the successor to HTTP/1.1.</p>
<p>HTTP/2 doesn't change what you send. From the application developer's perspective, requests still have methods, paths, headers, and bodies. Responses still have status codes, headers, and bodies. What HTTP/2 changes is how all of this is transmitted.</p>
<h3 id="heading-binary-framing-the-core-change">Binary Framing: The Core Change</h3>
<p>HTTP/1.1 is a text protocol. Headers, status lines, and method names are all ASCII text. Machines must parse this text character by character to interpret it.</p>
<p>HTTP/2 is a binary protocol. Every piece of information is encoded as binary frames rather than text. Binary is more compact and significantly faster for machines to parse. Instead of tokenizing a string looking for colons and newlines to separate header names from values, a binary parser reads fixed-length fields directly from memory.</p>
<p>The binary framing layer is the foundation everything else in HTTP/2 is built upon.</p>
<h3 id="heading-multiplexing-many-streams-one-connection">Multiplexing: Many Streams, One Connection</h3>
<p>HTTP/2 introduces the concept of streams. A stream is an independent, bidirectional sequence of frames within a single TCP connection. Multiple streams can exist simultaneously on the same connection.</p>
<pre><code class="language-plaintext">Single TCP connection to api.example.com

Stream 1: GET /user/profile ---------&gt; Response arrives
Stream 2: GET /user/balance ---------&gt; Response arrives
Stream 3: POST /transactions --------&gt; Response arrives
Stream 4: GET /notifications --------&gt; Response arrives

All four streams active simultaneously
No stream waits for any other stream
</code></pre>
<p>This is multiplexing: many independent requests and responses interleaved on the same connection. Head-of-line blocking at the HTTP level is eliminated. A slow request on Stream 1 doesn't prevent Stream 2, 3, or 4 from receiving their responses.</p>
<p>One connection replaces six parallel connections. The TCP handshake and TLS negotiation happen once. Connection overhead drops dramatically.</p>
<h3 id="heading-header-compression-with-hpack">Header Compression with HPACK</h3>
<p>HTTP/2 compresses headers using an algorithm called HPACK specifically designed for HTTP headers.</p>
<p>HPACK works in two ways. First, it maintains a table of previously seen headers. Instead of retransmitting a header that was sent on the previous request, it sends a reference to the table entry: a single integer instead of hundreds of bytes of text.</p>
<p>Second, HPACK uses Huffman encoding for new header values, reducing the size of strings that can't be referenced from the table.</p>
<p>The result: a mobile application sending the same Authorization header on every request transmits it in full on the first request, then sends a one-byte or two-byte reference on every subsequent request. What was 500 bytes of overhead becomes 2 bytes.</p>
<p>Across fifty requests in a session, this eliminates thousands of bytes of redundant header transmission.</p>
<h3 id="heading-stream-prioritization">Stream Prioritization</h3>
<p>HTTP/2 allows clients to assign priority to streams. A browser loading a web page can signal that the CSS file (needed to render anything) is higher priority than the analytics script (not needed for initial render). The server can use these priorities to decide the order in which it sends frames when multiple streams are active.</p>
<p>In practice, stream prioritization has been inconsistently implemented and is being redesigned in HTTP/3.</p>
<h3 id="heading-server-push">Server Push</h3>
<p>HTTP/2 allows the server to proactively send resources to the client without waiting for a request. When a browser requests an HTML file, the server can immediately push the CSS and JavaScript files it knows the browser will need next, before the browser has even parsed the HTML to discover it needs them.</p>
<pre><code class="language-plaintext">Client: GET /index.html
Server: Here is index.html
Server: (push) Here is styles.css — you will need this
Server: (push) Here is app.js — you will need this too
</code></pre>
<p>In practice, server push has had mixed adoption due to implementation complexity and the risk of pushing resources the client already has cached. HTTP/3 is reconsidering how push should work.</p>
<h3 id="heading-http2-and-grpc">HTTP/2 and gRPC</h3>
<p>HTTP/2's multiplexing and persistent connections make it the ideal transport for gRPC. A single HTTP/2 connection can carry many concurrent gRPC calls, including long-running streaming calls that push data continuously. This is why gRPC requires HTTP/2: the features that make gRPC efficient are provided by the transport layer.</p>
<h2 id="heading-http3-and-quic-the-next-evolution">HTTP/3 and QUIC: The Next Evolution</h2>
<p>Even with HTTP/2's improvements, one fundamental problem remained: TCP head-of-line blocking.</p>
<p>HTTP/2 eliminated head-of-line blocking at the HTTP level. Multiple HTTP/2 streams can proceed independently. But all of those streams share a single TCP connection. TCP guarantees ordered delivery of all bytes in a connection. If a single TCP packet is lost, the entire connection stalls while TCP retransmits that packet, even for streams that have nothing to do with the lost packet.</p>
<pre><code class="language-plaintext">HTTP/2 over TCP — packet loss scenario:

Stream 1: data in flight...
Stream 2: data in flight...
Stream 3: packet LOST — TCP retransmission required

Stream 1: STALLED (waiting for TCP retransmission)
Stream 2: STALLED (waiting for TCP retransmission)
Stream 3: retransmission in progress...
</code></pre>
<p>Both streams 1 and 2 are blocked by a packet loss that affected only stream 3. This is TCP head-of-line blocking, and HTTP/2 can't eliminate it because it operates above the TCP layer.</p>
<h3 id="heading-quic-a-new-transport-protocol">QUIC: A New Transport Protocol</h3>
<p>Google developed QUIC (Quick UDP Internet Connections) to solve this problem. QUIC is a new transport protocol built on UDP instead of TCP, designed to provide some very helpful new features:</p>
<ol>
<li><p><strong>Multiplexing without head-of-line blocking:</strong> QUIC understands streams natively. A packet loss in one QUIC stream only stalls that stream. Other streams on the same connection continue flowing freely.</p>
</li>
<li><p><strong>Built-in encryption:</strong> Unlike TLS which runs on top of TCP, QUIC has TLS 1.3 built into the protocol itself. The transport and security layers are integrated, reducing the number of round trips required before data can flow.</p>
</li>
<li><p><strong>Faster connection establishment:</strong> A new QUIC connection requires one round trip before data can flow. For returning connections where a session ticket exists, QUIC can send data in zero round trips (0-RTT).</p>
</li>
<li><p><strong>Connection migration:</strong> A TCP connection is identified by the four-tuple of source IP, source port, destination IP, and destination port. If any of these change (say, a mobile device switches from WiFi to cellular), the TCP connection breaks and must be re-established. QUIC connections are identified by a connection ID that survives network changes, enabling seamless handoff.</p>
</li>
</ol>
<h3 id="heading-http3">HTTP/3</h3>
<p>HTTP/3 is HTTP semantics over QUIC. The request and response model remains the same. Headers, status codes, and methods are all identical. The transport underneath is QUIC instead of TCP.</p>
<p>HTTP/3 is particularly impactful for:</p>
<ol>
<li><p><strong>Mobile networks</strong> where packet loss is more common and devices frequently switch between networks.</p>
</li>
<li><p><strong>High-latency connections</strong> where the reduced handshake round trips save meaningful time.</p>
</li>
<li><p><strong>Applications with many concurrent streams</strong> where TCP head-of-line blocking was a real bottleneck.</p>
</li>
</ol>
<p>As of 2026, HTTP/3 is supported by major browsers, CDNs, and an increasing number of backend servers. Adoption continues to grow.</p>
<h2 id="heading-data-formats-how-information-is-encoded">Data Formats: How Information Is Encoded</h2>
<p>Independent of which protocol carries data, systems need to agree on how data is encoded. The most important formats for API communication are JSON and Protocol Buffers.</p>
<h3 id="heading-json-the-universal-language">JSON: The Universal Language</h3>
<p>JSON (JavaScript Object Notation) was derived from JavaScript syntax and formalized as a standalone data format. Its design philosophy is human readability and simplicity.</p>
<p>A JSON object is a collection of key-value pairs enclosed in curly braces. Keys are always strings. Values can be strings, numbers, booleans, null, arrays, or other objects.</p>
<pre><code class="language-plaintext">{
  "id": "usr_001",
  "name": "John Smith",
  "age": 28,
  "is_verified": true,
  "scores": [98, 87, 92],
  "address": {
    "city": "Lagos",
    "country": "Nigeria"
  }
}
</code></pre>
<p>JSON became the dominant API data format for several reasons. It's human-readable: a developer can look at a JSON response in a browser's developer tools and immediately understand it. It maps naturally to data structures in virtually every programming language. It requires no special tooling or schema definition. And it's flexible: fields can be added or removed without necessarily breaking existing clients.</p>
<h3 id="heading-the-structural-cost-of-json">The Structural Cost of JSON</h3>
<p>JSON's human-readable design comes with a structural cost that becomes significant at scale.</p>
<p>Every field name is a string that travels over the network on every single response. In the example above, the strings <code>"is_verified"</code>, <code>"address"</code>, <code>"country"</code> aren't data. They're labels for data. They consume bytes, they must be tokenized and parsed, and they're repeated on every response for every user.</p>
<p>JSON is a text format, which means it must be parsed from text into the application's native data structures. This parsing isn't free: it requires allocating memory for strings, walking the text byte by byte to find delimiters, and constructing objects from the parsed values.</p>
<p>For a fintech platform with an internal API that returns a 1000-field response and is called by dozens of internal services millions of times per day, the cumulative cost of JSON's verbosity and parsing overhead becomes measurable in bandwidth bills and server CPU time.</p>
<p>JSON also has no formal schema at the network level. There's nothing in the JSON format itself that prevents a backend from changing <code>"account_balance"</code> to <code>"balance"</code>. The change compiles fine. The server deploys. Clients that depend on <code>"account_balance"</code> break silently at runtime.</p>
<h3 id="heading-xml-the-predecessor">XML: The Predecessor</h3>
<p>Before JSON, XML (eXtensible Markup Language) was the dominant data format for web services (used in SOAP, the predecessor to REST). XML is more verbose than JSON, wrapping every value in opening and closing tags:</p>
<pre><code class="language-plaintext">&lt;user&gt;
  &lt;id&gt;usr_001&lt;/id&gt;
  &lt;name&gt;John Smith&lt;/name&gt;
  &lt;age&gt;28&lt;/age&gt;
  &lt;is_verified&gt;true&lt;/is_verified&gt;
&lt;/user&gt;
</code></pre>
<p>XML has advantages: it supports schemas (XSD), namespaces, and complex document structures. It's still used in enterprise systems, document formats (DOCX, SVG, RSS), and configuration files. But for API communication, JSON's simplicity won.</p>
<h2 id="heading-rest-the-architecture-that-took-over-the-world">REST: The Architecture That Took Over the World</h2>
<p>REST (Representational State Transfer) was defined by Roy Fielding in his doctoral dissertation in 2000. Fielding was one of the principal authors of the HTTP specification, and REST emerged from his analysis of what made HTTP architecturally successful.</p>
<p>REST isn't a protocol. It's an architectural style: a set of constraints that, when applied to a distributed system, produce desired properties including scalability, simplicity, and modifiability.</p>
<h3 id="heading-the-six-rest-constraints">The Six REST Constraints</h3>
<p>Fielding defined six constraints that define a RESTful architecture. Most APIs described as "REST" implement a subset of these, which is why the term "RESTful" covers a wide spectrum.</p>
<p><strong>1. Client-Server:</strong> The client and server are separate concerns. The client manages the user interface. The server manages data storage and business logic. They evolve independently. This separation allows each to scale and change without affecting the other.</p>
<p><strong>2. Stateless:</strong> Each request from the client to the server must contain all the information needed to understand and process the request. The server doesn't store any session state between requests. If a client needs to be authenticated, the authentication information (typically a token) travels with every request.</p>
<p>Statelessness is what makes REST APIs horizontally scalable. Any server instance can handle any request because no session state needs to be co-located with the request. Load balancers can route requests freely.</p>
<p><strong>3. Cacheable:</strong> Responses must define themselves as cacheable or non-cacheable. If a response is cacheable, clients and intermediate layers (CDN, reverse proxies) can store and reuse the response without hitting the server.</p>
<p>Caching is one of the most powerful properties of REST. A well-designed REST API can serve millions of identical GET requests from CDN cache, with only a fraction ever reaching the origin server.</p>
<p><strong>4. Uniform Interface:</strong> The interface between client and server is standardized. Resources are identified by URIs. Resources are manipulated through representations. Messages are self-descriptive. This uniformity is what makes REST APIs universally accessible: a developer in any language can call a REST API using standard HTTP tooling.</p>
<p><strong>5. Layered System:</strong> The client doesn't need to know whether it's connected directly to the server or to an intermediary (load balancer, CDN, API gateway, caching proxy). Each layer only sees the layer it is interacting with. This enables transparent scaling and security.</p>
<p><strong>6. Code on Demand (Optional):</strong> Servers can extend client functionality by sending executable code (JavaScript). This is the only optional constraint and is the basis for how browsers work, but rarely relevant to API design.</p>
<h3 id="heading-resources-and-uris">Resources and URIs</h3>
<p>The central concept in REST is the resource. A resource is any piece of information that can be named, like a user, an order, a product, or a collection of transactions.</p>
<p>Resources are identified by URIs (Uniform Resource Identifiers). The URI identifies what the resource is, not what to do with it. The HTTP method expresses the operation.</p>
<pre><code class="language-plaintext">GET    /users           — retrieve all users
GET    /users/123       — retrieve user 123
POST   /users           — create a new user
PUT    /users/123       — replace user 123 entirely
PATCH  /users/123       — partially update user 123
DELETE /users/123       — delete user 123

GET    /users/123/orders        — orders belonging to user 123
POST   /users/123/orders        — create an order for user 123
GET    /users/123/orders/456    — order 456 belonging to user 123
</code></pre>
<p>The URI structure forms a hierarchy that reflects the relationships between resources. This makes APIs predictable: a developer who understands the resource model can guess the correct URIs.</p>
<h3 id="heading-why-rest-won">Why REST Won</h3>
<p>REST became the dominant architectural style for web APIs for reasons that go beyond technical merit:</p>
<p><strong>Universal accessibility:</strong> Any device, any language, any framework that can make an HTTP request can call a REST API. There's no special client library needed.</p>
<p><strong>HTTP alignment:</strong> REST leverages HTTP's existing infrastructure. CDN caching works for free. Load balancers understand HTTP. Monitoring tools speak HTTP. The entire ecosystem is built around HTTP semantics.</p>
<p><strong>Simplicity:</strong> A REST API can be designed, documented, and consumed with minimal tooling. A developer can test endpoints in a browser or with <code>curl</code> immediately.</p>
<p><strong>Developer experience:</strong> JSON over HTTP is something every web developer already understands. The learning curve is essentially zero.</p>
<p><strong>Ecosystem maturity:</strong> OpenAPI/Swagger provides standardized documentation. Postman provides testing. Every programming language has robust HTTP client libraries.</p>
<h3 id="heading-the-limits-of-rest">The Limits of REST</h3>
<p>REST's success is real. But so are its limitations, and understanding them is essential to knowing when to reach for something else.</p>
<h4 id="heading-overfetching-getting-more-than-you-need">Overfetching: Getting More Than You Need</h4>
<p>A REST endpoint returns a fixed shape of data. The <code>/users/123</code> endpoint returns the full user object: name, email, phone, address, preferences, account status, and thirty other fields.</p>
<p>A mobile screen that displays only the user's name and avatar must receive all of those fields to use two of them. The rest is waste: wasted bandwidth, serialization on the server, and deserialization on the client.</p>
<p>On a constrained mobile connection, this overfetching isn't just inefficient. It's a measurable degradation of user experience.</p>
<h4 id="heading-underfetching-not-getting-enough-at-once">Underfetching: Not Getting Enough at Once</h4>
<p>The opposite problem is equally common. A screen needs data from multiple resources: the user's profile, their recent orders, their notification count, and their account balance.</p>
<p>A REST API typically models these as separate endpoints. Loading this screen requires four separate HTTP requests, each with its own round-trip latency.</p>
<pre><code class="language-plaintext">GET /users/123         → profile data
GET /users/123/orders  → orders data
GET /notifications?user=123 → notification count
GET /accounts/123/balance   → balance data
</code></pre>
<p>Four sequential round trips. On a 200ms latency connection, that's 800ms of network time before the screen can render completely.</p>
<h4 id="heading-the-n1-problem">The N+1 Problem</h4>
<p>A common variant of underfetching: you fetch a list of resources, then must fetch additional data for each item in the list.</p>
<pre><code class="language-plaintext">GET /orders            → returns 20 orders (each with a user_id)
GET /users/1           → user for order 1
GET /users/2           → user for order 2
...
GET /users/20          → user for order 20
</code></pre>
<p>21 requests to load one screen. This pattern appears constantly in REST APIs and is addressed in various ways: including nested data in responses, adding query parameters to expand related resources, or creating purpose-built endpoints for specific screens.</p>
<p>All of these workarounds create tension: the API becomes less general as it's optimized for specific client needs.</p>
<h4 id="heading-no-native-real-time-support">No Native Real-Time Support</h4>
<p>REST is request-response. The client initiates every interaction. The server can never proactively push data.</p>
<p>Real-time features like live notifications, collaborative editing, and streaming data require either polling (inefficient), long-polling (complex), or a separate real-time technology bolted alongside the REST API.</p>
<h4 id="heading-the-documentation-drift-problem">The Documentation Drift Problem</h4>
<p>A REST API contract lives in documentation. Nothing in the HTTP protocol enforces that the documentation accurately reflects the API's actual behavior. As APIs evolve, documentation falls behind. Fields are renamed, types change, endpoints are deprecated. Clients built against outdated documentation break.</p>
<p>This isn't a theoretical problem. It's a daily reality in engineering teams where the backend and frontend evolve at different speeds.</p>
<h2 id="heading-graphql-letting-the-client-decide">GraphQL: Letting the Client Decide</h2>
<p>GraphQL was developed at Facebook starting in 2012 and open-sourced in 2015. Facebook built it to solve a specific problem: their mobile app needed to fetch complex, interconnected social data from a REST API, and the resulting overfetching and multiple round trips were degrading performance on mobile devices.</p>
<p>GraphQL's core insight is simple and radical: instead of the server deciding what data to return, let the client specify exactly what it needs.</p>
<h3 id="heading-the-query-language">The Query Language</h3>
<p>GraphQL is both a query language for APIs and a runtime for executing those queries. Rather than calling different endpoints for different data, all GraphQL requests go to a single endpoint (typically <code>/graphql</code>) and include a query that describes precisely what data is needed.</p>
<p>A GraphQL query for a user profile screen:</p>
<pre><code class="language-plaintext">query UserProfile {
  user(id: "usr_123") {
    name
    avatarUrl
    recentOrders(limit: 3) {
      id
      total
      status
      createdAt
    }
    notificationCount
  }
}
</code></pre>
<p>The response contains exactly and only the fields requested. Nothing more. If the client needs only <code>name</code> and <code>avatarUrl</code>, it requests only those two fields. The response contains only two fields.</p>
<h3 id="heading-mutations-and-subscriptions">Mutations and Subscriptions</h3>
<p>GraphQL has three operation types:</p>
<ol>
<li><p><strong>Queries</strong> fetch data. They're the GraphQL equivalent of GET requests.</p>
</li>
<li><p><strong>Mutations</strong> modify data: creating, updating, or deleting resources. They're the GraphQL equivalent of POST, PUT, PATCH, and DELETE.</p>
</li>
<li><p><strong>Subscriptions</strong> establish a persistent connection and push data in real-time when specified events occur. A subscription to <code>orderStatusChanged</code> receives a push every time any order's status changes. This is GraphQL's real-time capability, typically implemented over WebSockets.</p>
</li>
</ol>
<h3 id="heading-the-schema">The Schema</h3>
<p>Every GraphQL API is defined by a schema written in the Schema Definition Language (SDL). The schema declares every type, query, mutation, and subscription the API supports.</p>
<pre><code class="language-plaintext">type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order!]!
  notificationCount: Int!
}

type Order {
  id: ID!
  total: Float!
  status: OrderStatus!
  createdAt: String!
}

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
}

type Query {
  user(id: ID!): User
  orders(userId: ID!, limit: Int): [Order!]!
}

type Mutation {
  createOrder(userId: ID!, items: [OrderItemInput!]!): Order!
}
</code></pre>
<p>The schema is introspectable: clients can query the schema itself to discover what types and operations are available. This enables powerful tooling: GraphQL IDEs can autocomplete queries, validate them against the schema before sending, and display documentation inline.</p>
<h3 id="heading-where-graphql-wins">Where GraphQL Wins</h3>
<p><strong>Precise data fetching:</strong> Clients request exactly what they need. Overfetching is eliminated by design.</p>
<p><strong>Single round trip for complex data:</strong> Data from multiple resources is fetched in a single request. The N+1 problem is solved at the query level rather than requiring the client to make multiple requests.</p>
<p><strong>Strongly typed schema:</strong> The schema is the contract. Clients can validate their queries against it at build time. Type mismatches are caught before deployment.</p>
<p><strong>Frontend agility:</strong> Frontend teams can evolve their data requirements without asking backend teams to create new endpoints. New screens, data combinations, and features are all handled by writing a new query.</p>
<p><strong>Excellent tooling:</strong> GraphiQL and Apollo Studio provide interactive schema exploration, query building, and performance analysis.</p>
<h3 id="heading-where-graphql-struggles">Where GraphQL Struggles</h3>
<p><strong>Query complexity:</strong> A malicious or poorly written query can request enormous amounts of nested data. A query that fetches every user, each user's orders, each order's items, and each item's product details can bring a server to its knees.</p>
<p>REST endpoints can be individually optimized. GraphQL requires query complexity analysis, depth limiting, and rate limiting to protect the server.</p>
<p><strong>Caching is harder:</strong> REST GET requests are cacheable at the HTTP level by default. GraphQL queries all go through POST requests to a single endpoint, breaking standard HTTP caching. Clients must implement their own caching (Apollo Client does this), but CDN-level caching is essentially unavailable for dynamic queries.</p>
<p><strong>Over-engineering simple APIs:</strong> If your API is straightforward CRUD operations with no complex data relationships and no mobile clients with aggressive data constraints, GraphQL's added setup cost exceeds its benefit.</p>
<p><strong>Real-time at scale is complex:</strong> GraphQL subscriptions work, but scaling WebSocket connections for thousands of concurrent subscribers is infrastructure-intensive and requires careful architecture.</p>
<p><strong>Error handling is non-standard:</strong> A GraphQL request can partially succeed: some fields resolve successfully while others fail. The response includes both data and errors simultaneously. Handling this gracefully requires more nuanced error handling logic than a simple HTTP status code.</p>
<h2 id="heading-websockets-when-http-is-not-enough">WebSockets: When HTTP Is Not Enough</h2>
<p>HTTP, in all its versions, is fundamentally request-response. The client speaks first. The server responds. The conversation ends. Even with HTTP/2's server push, the client initiates every new exchange.</p>
<p>But some applications genuinely need both sides to be able to speak at any moment, without waiting for the other to ask first. For example, a chat application where both parties send messages freely. A live collaborative document where every keystroke is broadcast to co-editors. An online game where the server pushes state updates as they happen and the client sends actions continuously.</p>
<p>For these cases, WebSockets provide a fundamentally different communication model.</p>
<h3 id="heading-the-websocket-handshake">The WebSocket Handshake</h3>
<p>A WebSocket connection starts as an HTTP request and then upgrades to a WebSocket connection. This upgrade mechanism means WebSockets work through existing HTTP infrastructure (firewalls, proxies, load balancers) without requiring special configuration.</p>
<p>The upgrade request:</p>
<pre><code class="language-plaintext">GET /chat HTTP/1.1
Host: api.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
</code></pre>
<p>The server confirms the upgrade:</p>
<pre><code class="language-plaintext">HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
</code></pre>
<p>Status code 101 means "Switching Protocols." From this point forward, the HTTP connection is replaced by a WebSocket connection. The protocol has changed. HTTP headers, status codes, and methods no longer apply.</p>
<h3 id="heading-full-duplex-persistent-communication">Full-Duplex, Persistent Communication</h3>
<p>The WebSocket connection is:</p>
<ul>
<li><p><strong>Full-duplex:</strong> both the client and server can send messages at any time, simultaneously, without waiting for the other to finish.</p>
</li>
<li><p><strong>Persistent:</strong> the connection stays open until explicitly closed by either party or until a network interruption occurs.</p>
</li>
<li><p><strong>Low overhead:</strong> once established, WebSocket messages have minimal framing overhead compared to HTTP. A small WebSocket message may have only 2 to 10 bytes of overhead, versus potentially hundreds of bytes of HTTP headers.</p>
</li>
</ul>
<pre><code class="language-plaintext">WebSocket connection open

Client: "Hello, I'm user 123"
Server: "Welcome, user 123"
Server: "User 456 just sent you a message: Hey!"
Client: "Thanks, here's my reply: Hi there!"
Server: "New notification: your payment was confirmed"
Client: "Great, show me my balance"
Server: "Your balance is NGN 500,000"
Server: "Another notification: transfer from user 789 received"

[Both sides communicate freely, at any time, simultaneously]
</code></pre>
<h3 id="heading-where-websockets-win">Where WebSockets Win</h3>
<p><strong>True real-time bidirectional communication</strong>: Applications where both client and server need to send messages at unpredictable times and at high frequency. For example, chat, live collaboration, multiplayer games, financial trading terminals.</p>
<p><strong>Low-latency messaging:</strong> Once the connection is established, message round-trip times can be in the single-digit milliseconds, limited only by network latency rather than connection setup overhead.</p>
<p><strong>Native browser support:</strong> The WebSocket API is built into every modern browser. No libraries are needed for the fundamental connection.</p>
<p><strong>Event-driven architecture on the client:</strong> WebSocket events (message, close, error) map naturally to event-driven client code.</p>
<h3 id="heading-where-websockets-struggle">Where WebSockets Struggle</h3>
<p><strong>Stateful connections:</strong> Each WebSocket connection must be maintained by a specific server instance. When scaling horizontally, a client connected to Server A can't receive messages from Server B without a shared pub/sub layer (like Redis) that all server instances publish to and subscribe from. This adds infrastructure complexity.</p>
<p><strong>No built-in request-response correlation:</strong> WebSockets are a message stream. If you send a message and expect a response, there's no built-in mechanism to correlate which response corresponds to which request. You have to build this yourself.</p>
<p><strong>No schema or contract:</strong> WebSockets send raw text or binary. The format of messages is defined entirely by the application. Two systems communicating over WebSockets must agree on message format out of band, in documentation, and there's nothing to enforce it at the connection level.</p>
<p><strong>Firewall and proxy complications:</strong> Some corporate networks and older proxies don't support the HTTP upgrade mechanism correctly, breaking WebSocket connections. This is less common than it was but still occurs in enterprise environments.</p>
<p><strong>Reconnection must be handled manually:</strong> WebSocket connections can drop due to network instability. Applications must implement reconnection logic, including managing state across reconnections.</p>
<h2 id="heading-server-sent-events-the-simpler-real-time-option">Server-Sent Events: The Simpler Real-Time Option</h2>
<p>Between REST's pure request-response and WebSocket's full bidirectional communication lies a middle option that most developers overlook: Server-Sent Events (SSE).</p>
<p>SSE establishes a one-directional persistent connection: the server pushes data to the client over a regular HTTP connection, and the client listens. The client can't send data back through the same connection.</p>
<h3 id="heading-how-sse-works">How SSE Works</h3>
<p>The client makes a standard HTTP GET request with an <code>Accept: text/event-stream</code> header:</p>
<pre><code class="language-plaintext">GET /notifications HTTP/1.1
Host: api.example.com
Accept: text/event-stream
Authorization: Bearer token123
</code></pre>
<p>The server responds with a 200 OK and keeps the connection open, periodically sending events:</p>
<pre><code class="language-plaintext">HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

data: {"type": "balance_update", "balance": 500000}

data: {"type": "transaction", "id": "txn_001", "amount": -5000}

event: notification
data: {"message": "Your transfer has been confirmed"}

id: 42
data: {"type": "order_status", "status": "shipped"}
</code></pre>
<p>Each event is separated by a blank line. Events can include a <code>data</code> field, an optional <code>event</code> type, and an optional <code>id</code> for resumability.</p>
<h3 id="heading-automatic-reconnection">Automatic Reconnection</h3>
<p>One of SSE's most practical features is automatic reconnection. If the connection drops, the browser automatically reconnects, sending the last received event ID in a <code>Last-Event-ID</code> header. The server can resume from that point, ensuring no events are missed.</p>
<h3 id="heading-where-sse-wins">Where SSE Wins</h3>
<p><strong>Simplicity:</strong> SSE works over plain HTTP. There's no protocol upgrade needed, and no special infrastructure. It works through every HTTP/2 connection, load balancer, and CDN that supports streaming.</p>
<p><strong>Native browser support:</strong> The <code>EventSource</code> API is built into every modern browser. Automatic reconnection is built in.</p>
<p><strong>Perfect for one-directional feeds:</strong> Live dashboards, notification streams, news feeds, real-time analytics, server logs: any scenario where the server pushes a continuous stream of updates and the client only reads.</p>
<p><strong>HTTP/2 multiplexing:</strong> Over HTTP/2, multiple SSE connections can share a single TCP connection. The browser connection limit that affected SSE over HTTP/1.1 doesn't apply.</p>
<p><strong>Natural fit for existing infrastructure:</strong> SSE responses are just HTTP responses. Existing load balancers, authentication middleware, and monitoring tools work without modification.</p>
<h3 id="heading-where-sse-struggles">Where SSE Struggles</h3>
<p><strong>One direction only:</strong> The client can't send data back through the SSE connection. For bidirectional scenarios, SSE isn't sufficient on its own.</p>
<p><strong>Text only (natively):</strong> SSE events are text. Binary data must be base64-encoded, adding overhead.</p>
<p><strong>No native support in all environments.</strong> SSE is a browser API. In other environments (mobile apps, server-to-server), it requires an HTTP client configured to handle streaming responses.</p>
<h3 id="heading-sse-vs-websockets-the-decision">SSE vs WebSockets: The Decision</h3>
<p>Choose SSE when the server pushes data and the client only reads: notifications, live feeds, dashboards, or streaming responses from an AI model. SSE is simpler, works over plain HTTP, and has automatic reconnection built in.</p>
<p>Choose WebSockets when both the client and server need to send messages freely and simultaneously: chat, collaborative editing, and games. The added complexity of WebSockets is justified when you genuinely need bidirectional communication.</p>
<h2 id="heading-protocol-buffers-a-new-language-for-data">Protocol Buffers: A New Language for Data</h2>
<p>Protocol Buffers (protobuf) is a binary serialization format developed by Google. Where JSON encodes data as human-readable text, protobuf encodes data as compact binary. This single difference has cascading implications for payload size, parsing speed, type safety, and schema enforcement.</p>
<h3 id="heading-the-schema-first-approach">The Schema-First Approach</h3>
<p>Unlike JSON, where you simply start writing key-value pairs, protobuf requires defining a schema first. You describe your data structures in a <code>.proto</code> file using Protocol Buffer Language, a language-agnostic schema definition language.</p>
<p>The schema definition:</p>
<pre><code class="language-plaintext">syntax = "proto3";

message User {
  string id = 1;
  string name = 2;
  string email = 3;
  double balance = 4;
  bool is_verified = 5;
  int32 kyc_level = 6;
}

message Order {
  string id = 1;
  string user_id = 2;
  double total = 3;
  string status = 4;
  int64 created_at = 5;
}
</code></pre>
<p>Each field has a name and a type, as in any structured data format. But it also has a field number: the small integer after the equals sign. This field number is the key to protobuf's efficiency.</p>
<h3 id="heading-binary-encoding-why-field-numbers-matter">Binary Encoding: Why Field Numbers Matter</h3>
<p>When protobuf encodes data to binary, field names don't appear in the output. Instead, only the field number and the encoded value are written. Field 1 (id) becomes a tag byte indicating "field 1, type string" followed by the string's length and bytes. Field 4 (balance) becomes a tag byte indicating "field 4, type 64-bit float" followed by eight bytes of IEEE 754 double-precision float.</p>
<p>No <code>"id":</code> string, <code>"balance":</code> string, quotation marks, colons, or braces. Just field tags and values in a compact binary stream.</p>
<p>The same user object that occupies approximately 100 bytes in JSON occupies approximately 35 bytes in protobuf. For a 1000-field enterprise API response called millions of times per day, this difference translates directly to reduced bandwidth consumption and infrastructure cost.</p>
<p>Parsing binary is also fundamentally faster than parsing text. A binary parser reads a fixed-length tag, determines the type and length of the following value, reads that value, and moves to the next field. A JSON parser must tokenize a text stream character by character, handle escape sequences, infer types from value format, and construct a dynamic object from parsed key-value pairs.</p>
<p>On constrained devices or in high-throughput server-to-server communication, this parsing speed difference is meaningful.</p>
<h3 id="heading-code-generation-the-contract-comes-alive">Code Generation: The Contract Comes Alive</h3>
<p>The <code>.proto</code> schema file is the input to the <code>protoc</code> compiler. This compiler generates data classes in any supported language from the same schema definition.</p>
<p>The same <code>user.proto</code> file generates:</p>
<ul>
<li><p>A <code>User</code> class in Go for the backend server</p>
</li>
<li><p>A <code>User</code> class in Dart for the Flutter client</p>
</li>
<li><p>A <code>User</code> class in Python for the data processing service</p>
</li>
<li><p>A <code>User</code> class in TypeScript for the web frontend</p>
</li>
</ul>
<p>Every generated class has typed fields, serialization/deserialization methods, and equality comparison. There's no manual JSON parsing, type casting, or risk of field name typos. The compiler guarantees that every language's representation of a <code>User</code> is identical.</p>
<p>When the schema changes — a new field is added or a field is removed, for example — every team regenerates their classes. If the change is breaking (a required field removed or a type changed in an incompatible way), the compiler reports errors in every affected codebase. The problem is caught before any code reaches production.</p>
<h3 id="heading-schema-evolution-rules">Schema Evolution Rules</h3>
<p>Protobuf's field number system enables backward-compatible schema evolution. Because fields are identified by number rather than name, the following changes are safe:</p>
<ul>
<li><p>Adding a new field with a new number is always safe. Existing clients ignore fields they don't recognize. New clients receive the new field.</p>
</li>
<li><p>Removing a field by marking it as reserved is safe. Existing encoded data that contains the removed field is simply ignored when decoded. The field number must be marked reserved to prevent its reuse.</p>
</li>
<li><p>Renaming a field is safe. Names aren't encoded. Only the number matters at the binary level.</p>
</li>
<li><p>Changing a field's type in incompatible ways is unsafe and breaks existing encoded data.</p>
</li>
</ul>
<p>This evolution model means protobuf schemas can grow over time without coordinated updates across all clients and servers.</p>
<h3 id="heading-trade-offs">Trade-offs</h3>
<p>Protobuf's efficiency comes with costs that make it inappropriate for all contexts.</p>
<p>Binary data isn't human-readable. You can't open a protobuf response in a browser's developer tools and see what it contains. Debugging requires either decoding the binary with the schema or using specialized tools.</p>
<p>Protobuf also requires tooling. Every consumer of a protobuf-encoded API needs the schema and a protobuf library to decode it. For public APIs consumed by unknown third parties, this is a significant barrier. JSON requires nothing: every programming environment can parse it with built-in libraries.</p>
<p>Schema changes require coordination. When a schema changes, every consumer must update. For internal systems where you control all consumers, this is manageable. For public APIs, it requires versioning and migration strategies.</p>
<h2 id="heading-grpc-remote-procedure-calls-at-scale">gRPC: Remote Procedure Calls at Scale</h2>
<p>gRPC combines Protocol Buffers with HTTP/2 and Remote Procedure Call semantics to produce a framework for service-to-service communication that is faster, more structured, and more powerful than REST for specific use cases.</p>
<h3 id="heading-remote-procedure-calls-the-core-concept">Remote Procedure Calls: The Core Concept</h3>
<p>A Remote Procedure Call (RPC) framework makes calling a function on a remote server feel like calling a local function. Instead of constructing an HTTP request, serializing a body, parsing a response, and handling status codes, you call a function with typed arguments and receive a typed return value. The network communication is abstracted away.</p>
<pre><code class="language-plaintext">// Without RPC (manual REST)
const response = await http.post('/users', headers: {...}, body: json.encode(data));
const user = User.fromJson(json.decode(response.body));

// With RPC (gRPC)
final user = await userService.createUser(CreateUserRequest(name: "John", email: "john@example.com"));
</code></pre>
<p>The second form is simpler, type-safe, and requires no knowledge of HTTP methods, endpoints, or serialization formats.</p>
<h3 id="heading-the-four-communication-patterns">The Four Communication Patterns</h3>
<p>gRPC's most significant advantage over REST is its support for four distinct communication patterns, all defined in the same <code>.proto</code> schema and accessible through the same generated client.</p>
<p><strong>Unary RPC</strong> is the familiar request-response pattern. One request and one response. It's equivalent to a REST API call.</p>
<pre><code class="language-plaintext">Client ——— LoginRequest ——→ Server
Client ←—— LoginResponse —— Server
</code></pre>
<p><strong>Server Streaming RPC</strong> sends one request and receives a continuous stream of responses. The server pushes messages as they become available without the client needing to request each one.</p>
<pre><code class="language-plaintext">Client ——— WatchBalanceRequest ——→ Server
Client ←— BalanceResponse ———————— Server (balance: 500,000)
Client ←— BalanceResponse ———————— Server (balance: 495,000)
Client ←— BalanceResponse ———————— Server (balance: 1,000,000)
[Stream stays open, server pushes on every change]
</code></pre>
<p><strong>Client Streaming RPC</strong> sends a stream of messages to the server and receives one response at the end. The server processes all received messages and responds once.</p>
<pre><code class="language-plaintext">Client ——— DocumentChunk 1 ——→ Server
Client ——— DocumentChunk 2 ——→ Server
Client ——— DocumentChunk 3 ——→ Server
Client ←————— UploadResponse —— Server (all chunks processed)
</code></pre>
<p><strong>Bidirectional Streaming RPC</strong> allows both client and server to send streams of messages simultaneously, in any order.</p>
<pre><code class="language-plaintext">Client ——— ChatMessage ——→ Server
Server ←— ChatMessage ——— Client
Client ——— ChatMessage ——→ Server
Server ←— ChatMessage ——— Client  (server-initiated)
[Both sides communicate freely and simultaneously]
</code></pre>
<h3 id="heading-why-http2-and-protobuf-make-grpc-efficient">Why HTTP/2 and Protobuf Make gRPC Efficient</h3>
<p>gRPC's efficiency comes from the combination of its two underlying technologies working together.</p>
<p>HTTP/2's multiplexed persistent connections mean many concurrent gRPC calls, including long-running streaming calls, share a single connection. There's no connection setup overhead per call. Multiple streams proceed in parallel without blocking each other.</p>
<p>Protocol Buffer's binary encoding means payloads are compact and parsing is fast. A high-frequency service-to-service call that would transmit 100 bytes of JSON transmits 35 bytes of protobuf. At thousands of calls per second between microservices, this difference is significant.</p>
<p>The generated clients eliminate all serialization and deserialization code. The schema enforces that client and server agree on the contract. Breaking changes are caught by the compiler.</p>
<h3 id="heading-the-organizational-contract">The Organizational Contract</h3>
<p>In organizations using gRPC at scale, <code>.proto</code> files live in a dedicated repository separate from any individual service. This repository is the single source of truth for every service contract.</p>
<p>When an engineer wants to add a new field to an API, they open a pull request in the proto repository. Engineers from every affected team review it. The change is discussed, refined, and approved before any implementation begins. When it merges, every team regenerates their clients. Changes that break existing behavior are caught in code review, not in production.</p>
<p>This governance model transforms API evolution from a coordination problem into a code review process.</p>
<h3 id="heading-grpcs-limitations">gRPC's Limitations</h3>
<p>gRPC doesn't work natively in web browsers. Browsers can't directly make HTTP/2 requests with the necessary control required for gRPC. A proxy layer (gRPC-Web) is required to translate between gRPC-Web's browser-compatible format and standard gRPC. This adds infrastructure complexity and limits gRPC's applicability for browser-based clients.</p>
<p>gRPC also requires HTTP/2. Environments that don't support HTTP/2 can't use gRPC.</p>
<p>Binary encoding makes debugging harder as well. Inspecting gRPC traffic requires specialized tools and access to the proto schema.</p>
<p>For public APIs consumed by third-party developers, gRPC's tooling requirements are a higher barrier than REST's universally accessible JSON over HTTP.</p>
<h2 id="heading-the-complete-comparison">The Complete Comparison</h2>
<table>
<thead>
<tr>
<th></th>
<th>HTTP/1.1</th>
<th>HTTP/2</th>
<th>REST</th>
<th>GraphQL</th>
<th>WebSockets</th>
<th>SSE</th>
<th>gRPC</th>
</tr>
</thead>
<tbody><tr>
<td>Protocol</td>
<td>HTTP/1.1</td>
<td>HTTP/2</td>
<td>HTTP/1.1 or 2</td>
<td>HTTP/1.1 or 2</td>
<td>WebSocket</td>
<td>HTTP</td>
<td>HTTP/2</td>
</tr>
<tr>
<td>Data format</td>
<td>Any</td>
<td>Any</td>
<td>JSON (typical)</td>
<td>JSON</td>
<td>Any</td>
<td>Text</td>
<td>Protobuf (binary)</td>
</tr>
<tr>
<td>Communication</td>
<td>Request-Response</td>
<td>Request-Response</td>
<td>Request-Response</td>
<td>Request-Response + Subscriptions</td>
<td>Bidirectional</td>
<td>Server to Client</td>
<td>All four patterns</td>
</tr>
<tr>
<td>Contract</td>
<td>None</td>
<td>None</td>
<td>Documentation</td>
<td>Schema (SDL)</td>
<td>None</td>
<td>None</td>
<td>.proto file</td>
</tr>
<tr>
<td>Code generation</td>
<td>No</td>
<td>No</td>
<td>Optional</td>
<td>Optional</td>
<td>No</td>
<td>No</td>
<td>Mandatory</td>
</tr>
<tr>
<td>Real-time</td>
<td>No</td>
<td>Limited (push)</td>
<td>No (polling)</td>
<td>Subscriptions</td>
<td>Yes</td>
<td>Yes (one-way)</td>
<td>Yes (built-in)</td>
</tr>
<tr>
<td>Browser native</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No (needs proxy)</td>
</tr>
<tr>
<td>Caching</td>
<td>Excellent</td>
<td>Excellent</td>
<td>Excellent</td>
<td>Difficult</td>
<td>Not applicable</td>
<td>Not applicable</td>
<td>Not applicable</td>
</tr>
<tr>
<td>Payload size</td>
<td>Medium</td>
<td>Medium</td>
<td>Medium (JSON)</td>
<td>Medium (JSON)</td>
<td>Low overhead</td>
<td>Low overhead</td>
<td>Small (binary)</td>
</tr>
<tr>
<td>Human readable</td>
<td>Yes</td>
<td>No (binary frames)</td>
<td>Yes</td>
<td>Yes</td>
<td>Depends</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Schema enforcement</td>
<td>None</td>
<td>None</td>
<td>None</td>
<td>Compile-time</td>
<td>None</td>
<td>None</td>
<td>Compile-time</td>
</tr>
</tbody></table>
<hr>
<h2 id="heading-how-to-choose-the-engineering-decision-framework">How to Choose: The Engineering Decision Framework</h2>
<p>No single communication approach is universally best. Each exists because it solves specific problems better than the alternatives. The engineering decision involves matching the tool to your requirements.</p>
<h3 id="heading-when-to-use-rest">When to Use REST</h3>
<p>Use REST when the API is public or consumed by third parties. REST's universal accessibility makes it the only reasonable choice for public APIs. Any developer in any language can call a REST API with standard HTTP tools. There are no schema files, generated clients, or special libraries.</p>
<p>REST is also a good fit when caching is a priority. REST GET responses can be cached at every layer: CDN, reverse proxy, and browser. For content that doesn't change frequently, REST with proper cache headers can serve millions of requests without hitting the origin server.</p>
<p>It's also solid when the operation is simple request-response. If you're building straightforward CRUD operations with no streaming requirements and no complex data relationships, REST is simpler to implement, document, and debug than any alternative.</p>
<p>And finally use REST when developer experience for the consumer matters. REST APIs are immediately accessible in a browser. They can be tested with <code>curl</code>. Every developer already understands them.</p>
<h3 id="heading-when-to-use-graphql">When to Use GraphQL</h3>
<p>Use GraphQL when multiple client types have significantly different data needs. A mobile app that needs minimal data for a list view and richer data for a detail view, alongside a desktop app that needs comprehensive data, are ideal GraphQL consumers. Each queries exactly what it needs.</p>
<p>GraphQL also works well for complex interconnected data with many relationships. Social graphs, product catalogs with deeply nested attributes, or content management systems with rich content relationships: GraphQL's ability to traverse relationships in a single query is a genuine advantage.</p>
<p>It's also a good choice for frontend teams that need to iterate quickly. When the frontend can evolve its data requirements without backend changes, development velocity increases. New screens, new data combinations, no new endpoints needed.</p>
<p>And finally, GraphQL works well if you're comfortable with the operational complexity. GraphQL requires query complexity protection, custom caching strategies, and more sophisticated error handling. These are worth the effort when the data fetching advantages are real.</p>
<h3 id="heading-when-to-use-websockets">When to Use WebSockets</h3>
<p>Use WebSockets when both the client and server need to send messages at any time. Genuine bidirectional real-time communication where either party can initiate a message at any moment.</p>
<p>WebSockets also work great for chat, collaboration, and games. Live chat applications, collaborative document editing, multiplayer real-time games are the canonical WebSocket use cases.</p>
<p>And WebSockets is a solid choice when low-latency messaging is critical. The minimal framing overhead and persistent connection make WebSockets the lowest-latency option for frequent message exchange.</p>
<h3 id="heading-when-to-use-server-sent-events">When to Use Server-Sent Events</h3>
<p>Use SSE when the server needs to push updates but the client only reads. Notification feeds, live dashboards, streaming AI responses, real-time analytics, or any scenario where the server has a continuous stream of data to deliver and the client only consumes.</p>
<p>SSE also works well when you value simplicity over full bidirectionality. SSE is significantly simpler to implement and operate than WebSockets for one-directional use cases. Automatic reconnection is built in. It works over plain HTTP.</p>
<h3 id="heading-when-to-use-grpc">When to Use gRPC</h3>
<p>Use gRPC when multiple internal services share the same contract. When several teams build services that call each other, a <code>.proto</code> schema enforced by the compiler prevents contract drift. Everyone generates their clients from the same source of truth.</p>
<p>gRPC also works well for high-frequency service-to-service communication. Two microservices exchanging thousands of calls per second benefit from protobuf's compact binary encoding and HTTP/2's persistent multiplexed connections.</p>
<p>It's also a solid choice for large payloads that are consumed by many internal systems. An internal enterprise API with hundreds of fields called by dozens of internal applications benefits enormously from protobuf's size reduction. Less bandwidth, less parsing overhead, and compiled contract enforcement.</p>
<p>gRPC also works great when low-bandwidth networks matter. For mobile applications in markets where network conditions are variable or constrained, protobuf's binary encoding reduces payload size by 3 to 10 times compared to JSON. The difference between a 15 kilobyte response and a 3 kilobyte response is the difference between a 3-second load and a sub-second load on a 2G connection.</p>
<p>And finally, use gRPC when streaming is a core requirement and you want one framework. gRPC's four communication patterns (unary, server streaming, client streaming, and bidirectional) cover every scenario without requiring separate WebSocket infrastructure alongside your API.</p>
<h3 id="heading-the-hybrid-reality">The Hybrid Reality</h3>
<p>Most sophisticated systems use multiple approaches, each where it genuinely wins:</p>
<pre><code class="language-plaintext">A Large Engineering Organization

Public REST API
  External developers, partners, open integrations
  JSON over HTTPS. OpenAPI documentation.
  CDN caching for frequently accessed resources.

Internal gRPC Network
  Service-to-service communication
  Auth service, payment service, notification service,
  fraud detection: all communicating with typed contracts
  over efficient binary protobuf on HTTP/2.

Real-Time Layer
  WebSockets for bidirectional features (live chat, collaboration)
  SSE for one-directional feeds (notifications, live dashboards)
  gRPC streaming for real-time data with typed contracts

Mobile API
  REST for standard operations (profile, settings, history)
  gRPC for high-frequency or large payload calls
  SSE for notification streaming
</code></pre>
<p>There's no architectural purity requirement. Each layer uses what fits its requirements. The discipline is in making these choices deliberately rather than by habit or default.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The history of how clients and servers communicate is the history of engineers discovering the limitations of existing tools and building better ones.</p>
<p>HTTP/1.1 gave us a universal request-response protocol that built the web. Its text-based format and sequential connection model worked well for the web of the 1990s and 2000s. As applications became more complex and performance expectations rose, its limitations became bottlenecks.</p>
<p>HTTP/2 rebuilt the transport layer with binary framing and multiplexing, eliminating head-of-line blocking at the HTTP level, compressing headers, and enabling server push. HTTP/3 took this further by replacing TCP with QUIC, addressing the remaining head-of-line blocking at the transport level and making connection establishment faster.</p>
<p>JSON became the dominant data format because of its human readability and universal support. Protocol Buffers emerged as an alternative for contexts where JSON's verbosity and lack of schema enforcement create real problems: internal services, high-frequency communication, constrained networks, and teams needing compile-time contract enforcement.</p>
<p>REST codified HTTP's architectural strengths into a style that made APIs universally accessible and HTTP-native. Its success wasn't purely technical: it aligned with what developers already understood and what the HTTP ecosystem already supported. Its limitations in data fetching efficiency and real-time communication opened the door for GraphQL and streaming alternatives.</p>
<p>GraphQL solved REST's overfetching and underfetching problems by inverting control: the client specifies exactly what it needs. WebSockets solved REST's inability to support genuine bidirectional real-time communication. Server-Sent Events provided a simpler real-time option for one-directional streaming. gRPC combined Protocol Buffers, HTTP/2, and RPC semantics into a framework that excels at typed service-to-service communication at scale.</p>
<p>Understanding all of these tools, along with why each was built, what problem it solves, and where it struggles, is what enables you to make deliberate architectural decisions rather than defaulting to whatever is most familiar.</p>
<p>The right communication approach is always the one that fits the specific requirements of the system you're building: the clients consuming it, the data being exchanged, the network conditions it operates in, the teams building and maintaining it, and the operational complexity you are prepared to manage.</p>
<p>That clarity of fit is what engineering judgment looks like in practice.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn HTTP Methods like GET, POST, and DELETE – a Handbook with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ When you interact with websites or apps, a lot happens behind the scenes. A key part of this process is how your browser or app talks to a server. HTTPS methods define what action needs to happen – it could be fetching data, sending information, or m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-http-methods-like-get-post-and-delete-a-handbook-with-code-examples/</link>
                <guid isPermaLink="false">66fd572dc6e14d69030944f7</guid>
                
                    <category>
                        <![CDATA[ httpmethods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 02 Oct 2024 14:22:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727797253693/e0d1ebfc-2071-4f2e-8e8b-d47c8f55844e.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you interact with websites or apps, a lot happens behind the scenes. A key part of this process is how your browser or app talks to a server. HTTPS methods define what action needs to happen – it could be fetching data, sending information, or making changes to existing content.</p>
<p>Each method serves a specific purpose to keep web communication clear, secure, and organized.</p>
<p>In this article, we will break down the most common HTTPS methods and explain how they function to make online interactions work smoothly.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-get-method">GET Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-post-method">POST Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-put-method">PUT Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-patch-method">PATCH Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-delete-method">DELETE Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-head-method">HEAD Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-options-method">OPTIONS Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-trace-method">TRACE Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-connect-method">CONNECT Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-get-method">GET Method</h2>
<p>The GET method is one of the most common HTTP methods and is used to request data from a server. Think of it as asking for information without changing anything.</p>
<p>When you visit a webpage, your browser sends a GET request to the server asking for the content of the page. The server then responds with the data (such as HTML, images, or other files) that the browser displays.</p>
<p>One important thing about GET is that it doesn't make any changes to the data. It simply "reads" or retrieves the information. For example, when you browse through social media or search for products online, the app or website uses GET to display data without altering it.</p>
<p>Another key point is that GET requests send parameters in the URL itself. This means any data you're asking for is visible in the browser's address bar. For example, if you're searching for a product on an online store, the search term is included in the URL.</p>
<h3 id="heading-example-of-a-get-request">Example of a GET Request</h3>
<p>Here’s a simple example of a GET request in JavaScript using the Fetch API:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/products?category=shoes'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the GET request is made to the URL <a target="_blank" href="https://api.example.com/products"><code>https://api.example.com/products</code></a> with a query parameter <code>category=shoes</code>, asking the server to return products in the shoes category.</p>
<h3 id="heading-use-cases-of-the-get-method">Use Cases of the GET Method</h3>
<p>GET is mainly used to fetch information, and there are many common scenarios where it's applied:</p>
<ol>
<li><p><strong>Loading a Webpage</strong>: Every time you type a URL into your browser or click a link, you're making a GET request. The browser asks the server for the webpage, and the server sends back the content to display.</p>
<ul>
<li>Example: <code>GET /index.html HTTP/1.1</code></li>
</ul>
</li>
<li><p><strong>Fetching Data from APIs</strong>: When developers build applications, they often use APIs (Application Programming Interfaces) to get data from external servers. For instance, a weather app uses a GET request to fetch the current temperature from a weather API.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    fetch(<span class="hljs-string">'https://api.weather.com/current?city=Lagos'</span>)
       .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
       .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
</code></pre>
<ol start="3">
<li><p><strong>Search Queries</strong>: When you search for something on Google or other search engines, a GET request is made. The search term you entered is included in the URL, and the server returns a list of matching results.</p>
<ul>
<li>Example: <code>GET /search?q=JavaScript</code></li>
</ul>
</li>
<li><p><strong>Retrieving Files</strong>: Whether you're downloading an image, viewing a PDF, or playing a video, GET is used to fetch those files from a server.</p>
<ul>
<li>Example: <code>GET /files/image.jpg</code></li>
</ul>
</li>
</ol>
<h3 id="heading-best-practices-for-get-requests">Best Practices for GET Requests</h3>
<p>To use GET requests effectively, it's important to follow some good practices to ensure smooth and secure data handling:</p>
<ol>
<li><p><strong>Use GET Only for Retrieving Data</strong>: GET requests are meant to fetch data, not to send sensitive information like passwords or personal data. Since the parameters in a GET request are included in the URL, anyone can see them. For example, if you're logging into a website, you shouldn't use GET to send your password, because it would show up in the URL.</p>
<ul>
<li>Example of what <strong>not</strong> to do:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    fetch(<span class="hljs-string">'https://example.com/login?username=john&amp;password=secret'</span>);
</code></pre>
<ol start="2">
<li><p><strong>Keep URLs Short and Clean</strong>: Since GET requests include data in the URL, long URLs can become problematic. There is also a limit to how much data can be included in a GET request URL (depending on the browser and server), so avoid putting too much information there. If you need to send a lot of data, consider using a POST request instead.</p>
</li>
<li><p><strong>Enable Caching for Performance</strong>: GET requests are often cached by browsers, meaning the browser can store the response and reuse it without contacting the server again. This improves performance, especially for static content that doesn’t change often, like images or style sheets. To take advantage of this, ensure your server sends proper cache-control headers, so frequently requested data can be loaded faster.</p>
<ul>
<li>Example of setting cache headers:</li>
</ul>
</li>
</ol>
<pre><code class="lang-http">    Cache-Control: max-age=3600
</code></pre>
<ol start="4">
<li><p><strong>Avoid Making GET Requests for Actions That Change Data</strong>: Since GET is a "safe" method, it should only be used for actions that don't modify data. If you want to create, update, or delete data, use methods like POST, PUT, or DELETE. For instance, if you accidentally use GET to delete a resource, someone could remove it just by clicking a link or refreshing the page, which is not safe.</p>
<ul>
<li>Example of <strong>not</strong> using GET for deletion:</li>
</ul>
</li>
</ol>
<pre><code class="lang-http">    GET /delete/user/123
</code></pre>
<ol start="5">
<li><strong>Be Cautious with Sensitive Data</strong>: Since GET requests are part of the URL, they can be logged or saved in a browser’s history. Avoid sending sensitive information like passwords, credit card details, or private data in a GET request. Always use methods like POST for handling such information, which keeps it hidden.</li>
</ol>
<h2 id="heading-post-method">POST Method</h2>
<p>The POST method is used to send data to a server. Unlike the GET method, which only retrieves data, POST allows you to submit information that the server can use to process or store. POST is commonly used in forms, where users input data such as usernames, passwords, or contact details.</p>
<p>When a POST request is made, the data is sent in the body of the request rather than in the URL. This makes POST ideal for sending larger or more sensitive information, such as passwords, because the data is hidden and doesn’t appear in the browser's address bar.</p>
<p>For example, when you sign up for a website or submit a comment on a blog, the POST method is used to send your information to the server, which processes it and stores it in a database.</p>
<h3 id="heading-example-of-a-post-request">Example of a POST Request</h3>
<p>Here’s an example of a POST request using the Fetch API to send form data to a server:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> formData = {
  <span class="hljs-attr">username</span>: <span class="hljs-string">'john_doe'</span>,
  <span class="hljs-attr">password</span>: <span class="hljs-string">'mypassword123'</span>
};

fetch(<span class="hljs-string">'https://example.com/login'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(formData)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Success:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the POST request sends <code>username</code> and <code>password</code> as JSON data in the body of the request, making it a secure way to handle sensitive information like passwords.</p>
<h3 id="heading-differences-between-get-and-post">Differences Between GET and POST</h3>
<p>Although GET and POST are used to communicate with a server, they serve different purposes and handle data in different ways:</p>
<h4 id="heading-data-transmission">Data Transmission:</h4>
<ul>
<li><p><strong>GET</strong>: Data is included in the URL, making it visible in the address bar. This limits how much data can be sent.</p>
</li>
<li><p><strong>POST</strong>: Data is sent in the body of the request, which allows for sending larger amounts of information. This also keeps sensitive information hidden from the URL.</p>
</li>
</ul>
<h4 id="heading-purpose">Purpose:</h4>
<ul>
<li><p><strong>GET</strong>: Used for retrieving data. It doesn’t change or modify anything on the server.</p>
</li>
<li><p><strong>POST</strong>: Used to send data that may change or add to the server's resources, such as adding a new user to a database or submitting a form.</p>
</li>
</ul>
<h4 id="heading-caching">Caching:</h4>
<ul>
<li><p><strong>GET</strong>: GET requests can be cached. This means that the browser may save the response, making future requests faster.</p>
</li>
<li><p><strong>POST</strong>: POST requests are not cached, as they often involve new or updated data that shouldn't be reused.</p>
</li>
</ul>
<h4 id="heading-idempotence">Idempotence:</h4>
<ul>
<li><p><strong>GET</strong>: Sending the same GET request multiple times doesn’t change the result. It will return the same data every time.</p>
</li>
<li><p><strong>POST</strong>: Sending the same POST request multiple times may result in different outcomes. For example, submitting a form twice could create duplicate entries.</p>
</li>
</ul>
<h3 id="heading-common-scenarios-for-using-post">Common Scenarios for Using POST</h3>
<p>POST is ideal in situations where you need to send data to the server, often for processing or storage. Here are some common use cases:</p>
<ol>
<li><p><strong>Submitting Forms</strong>: Whenever you fill out and submit a form online, such as signing up for a newsletter or entering your details in a registration form, the POST method is used to send that information to the server. The server then processes the data, stores it, or performs another action based on it.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"https://example.com/register"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<ol start="2">
<li><p><strong>User Authentication</strong>: When you log in to a website using a username and password, POST is often used to send your credentials securely to the server. The server checks the information and grants access to your account if the credentials match.</p>
</li>
<li><p><strong>Uploading Files</strong>: POST is also used for uploading files, such as images, documents, or videos. Since the POST method allows sending large amounts of data, it’s perfect for uploading files that need to be processed or stored on the server.</p>
<ul>
<li>Example using a form for file uploads:</li>
</ul>
</li>
</ol>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"https://example.com/upload"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">"multipart/form-data"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"file"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Upload File<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<ol start="4">
<li><p><strong>Creating New Resources</strong>: POST is often used in APIs to create new resources. For example, when you add a new product to an online store, the POST method is used to send the product details to the server, which adds the product to the store's database.</p>
<ul>
<li>Example of sending product data:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> product = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">'New Sneakers'</span>,
      <span class="hljs-attr">price</span>: <span class="hljs-number">59.99</span>,
      <span class="hljs-attr">category</span>: <span class="hljs-string">'Footwear'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/api/products'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(product)
    })
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Product added:'</span>, data));
</code></pre>
<ol start="5">
<li><p><strong>Sending Data to an API</strong>: POST is widely used in APIs when you need to send data that will be processed or stored. For example, an app that tracks your fitness progress may use POST to send your workout details to a server, where it’s stored and analyzed.</p>
</li>
<li><p><strong>Making Purchases Online</strong>: When you make an online purchase, POST is used to send the payment details to the server for processing. The server processes the transaction and updates the system with your order information.</p>
</li>
</ol>
<h2 id="heading-put-method">PUT Method</h2>
<p>The <strong>PUT</strong> method is used to update or replace an existing resource on the server. It sends data to the server and tells it to create a new resource if none exists or replace the current one if it does. The key idea with PUT is that you are telling the server exactly what the resource should look like.</p>
<p>For example, imagine a user profile on a website. If you use PUT to update your profile, the server will replace the entire profile with the new data you provide. Every part of the profile will match exactly what you send, so if some details are missing, they will be overwritten with the new data.</p>
<h3 id="heading-example-of-a-put-request">Example of a PUT Request</h3>
<p>Here’s an example of a PUT request using the Fetch API to update user data:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> updatedProfile = {
  <span class="hljs-attr">username</span>: <span class="hljs-string">'john_doe_updated'</span>,
  <span class="hljs-attr">email</span>: <span class="hljs-string">'john_updated@example.com'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedProfile)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Updated:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the PUT request updates the user profile with new data. The profile will be replaced with <code>username</code>, <code>email</code>, and <code>age</code> values. If any data is missing, such as <code>phoneNumber</code>, it will be removed from the profile.</p>
<h3 id="heading-when-to-use-put">When to Use PUT</h3>
<p>PUT is mainly used when you want to update or replace a resource with specific, complete data. Here are some common situations where PUT is appropriate:</p>
<ol>
<li><p><strong>Updating a Resource</strong>: When you need to make changes to an existing resource, PUT is used to send a new version of the entire resource. For example, updating a blog post, product details, or user information would require sending a complete replacement of the resource using PUT.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedPost = {
      <span class="hljs-attr">title</span>: <span class="hljs-string">'New Title for My Blog'</span>,
      <span class="hljs-attr">content</span>: <span class="hljs-string">'Updated blog content here...'</span>,
      <span class="hljs-attr">author</span>: <span class="hljs-string">'John Doe'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/blog/45'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedPost)
    });
</code></pre>
<ol start="2">
<li><p><strong>Creating a Resource if None Exists</strong>: If you send a PUT request to a specific URL that doesn't have a resource yet, the server will create one using the data you provide. This is useful when you're working with resources that need to be fully defined upfront.</p>
<ul>
<li>Example of creating a product if it doesn’t exist:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> newProduct = {
      <span class="hljs-attr">id</span>: <span class="hljs-number">101</span>,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'New Sneakers'</span>,
      <span class="hljs-attr">price</span>: <span class="hljs-number">59.99</span>,
      <span class="hljs-attr">category</span>: <span class="hljs-string">'Footwear'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/products/101'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(newProduct)
    });
</code></pre>
<ol start="3">
<li><p><strong>Working with APIs</strong>: When interacting with APIs, PUT is often used when you need to make updates to a resource like a user profile, product details, or any other structured data. For example, a to-do list app might allow you to use PUT to update an existing task with new information.</p>
<ul>
<li>Example of updating a task:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedTask = {
      <span class="hljs-attr">title</span>: <span class="hljs-string">'Updated Task Title'</span>,
      <span class="hljs-attr">completed</span>: <span class="hljs-literal">true</span>
    };

    fetch(<span class="hljs-string">'https://example.com/tasks/67'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedTask)
    });
</code></pre>
<h3 id="heading-put-vs-post-key-differences">PUT vs. POST: Key Differences</h3>
<p>Though both PUT and POST can send data to a server, they have different purposes and behaviors:</p>
<h4 id="heading-purpose-1">Purpose:</h4>
<ul>
<li><p><strong>PUT</strong>: Primarily used for updating or replacing an existing resource. If the resource doesn’t exist, PUT can also create it.</p>
</li>
<li><p><strong>POST</strong>: Mainly used to create new resources or submit data that needs to be processed. POST doesn’t replace existing resources but adds new ones.</p>
</li>
</ul>
<h4 id="heading-data-handling">Data Handling:</h4>
<ul>
<li><p><strong>PUT</strong>: Replaces the entire resource with the new data. If a part of the resource is missing in the request, that part gets removed or replaced.</p>
</li>
<li><p><strong>POST</strong>: Adds or updates resources without replacing the entire thing. For example, when submitting a form, POST adds new data to the server without deleting what’s already there.</p>
</li>
</ul>
<h4 id="heading-idempotence-1">Idempotence:</h4>
<ul>
<li><p><strong>PUT</strong>: Is idempotent, so sending the same PUT request multiple times will always result in the same outcome. No matter how many times you update a resource using PUT, the result will be the same.</p>
</li>
<li><p><strong>POST</strong>: Is not idempotent, so submitting the same POST request multiple times could create duplicate resources or have different results.</p>
</li>
</ul>
<h4 id="heading-use-cases">Use Cases:</h4>
<ul>
<li><p><strong>PUT</strong>: Best used for updates and full replacements of resources. For instance, if you’re updating product details in an online store, PUT ensures that all the details are replaced with the new ones you send.</p>
</li>
<li><p><strong>POST</strong>: Suited for creating new entries or sending data that requires processing. For example, submitting an online order or filling out a contact form uses POST.</p>
</li>
</ul>
<h2 id="heading-patch-method">PATCH Method</h2>
<p>The <strong>PATCH</strong> method is used to make partial updates to a resource on the server. Unlike the PUT method, which replaces the entire resource, PATCH allows you to update specific parts of a resource without sending the complete data again. This makes PATCH ideal for scenarios where you only want to tweak certain details without affecting other parts of the resource.</p>
<p>For example, if you have a user profile and want to update only the phone number, PATCH enables you to send just the new phone number while leaving the rest of the profile unchanged. This approach is more efficient and reduces the risk of unintended data loss.</p>
<h3 id="heading-partial-updates-with-patch">Partial Updates with PATCH</h3>
<p>PATCH is designed for making targeted changes to a resource. Here’s how it works:</p>
<ul>
<li><p><strong>Targeted Changes</strong>: When you use PATCH, you specify only the fields you want to update. For instance, if a user updates their email address, you send a PATCH request containing just the new email, and everything else stays the same on the server.</p>
</li>
<li><p><strong>Efficiency</strong>: PATCH is more efficient than PUT because it allows you to send only the data that’s being changed. This can reduce bandwidth usage, especially when updating large resources where only a small part needs modification.</p>
</li>
<li><p><strong>Does Not Overwrite</strong>: Unlike PUT, PATCH does not replace the entire resource. It only updates the fields that are provided in the request, ensuring that other fields remain intact.</p>
</li>
</ul>
<h3 id="heading-example-of-a-patch-request">Example of a PATCH Request</h3>
<p>Here’s a basic example of how you might use the PATCH method to update a specific field, such as changing a user's email address:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> updatedEmail = {
  <span class="hljs-attr">email</span>: <span class="hljs-string">'new_email@example.com'</span>
};

fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedEmail)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Email updated:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, only the <code>email</code> field is being updated. The rest of the user profile, such as the username or address, remains unchanged.</p>
<h3 id="heading-when-to-use-patch-instead-of-put">When to Use PATCH Instead of PUT</h3>
<p>There are specific scenarios where PATCH is more appropriate than PUT:</p>
<ol>
<li><p><strong>Updating Specific Fields</strong>: If you need to update only a part of a resource, like changing a user’s email, adding a tag to a blog post, or modifying a single attribute, PATCH is a better choice. It allows you to send only the fields that need updating, making the request more efficient.</p>
<ul>
<li>Example: Updating a user's phone number.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedPhone = { <span class="hljs-attr">phoneNumber</span>: <span class="hljs-string">'123-456-7890'</span> };

    fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedPhone)
    });
</code></pre>
<ol start="2">
<li><p><strong>Avoiding Unintended Data Loss</strong>: When using PUT, leaving out any fields could result in the server removing or overwriting those fields. PATCH avoids this risk by only updating the specific fields provided, ensuring no accidental data loss.</p>
<ul>
<li>Example: If you only want to update a user’s username but don’t want to overwrite other fields like their address or preferences, PATCH ensures only the username is updated.</li>
</ul>
</li>
<li><p><strong>Performance Considerations</strong>: PATCH is more efficient for large resources. For instance, if you're managing a database with extensive records and need to change a small portion, PATCH reduces the data sent to the server, improving performance and speeding up the process.</p>
<ul>
<li>Example: Updating the status of a large order without modifying the entire order details.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedStatus = { <span class="hljs-attr">status</span>: <span class="hljs-string">'shipped'</span> };

    fetch(<span class="hljs-string">'https://example.com/orders/987'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedStatus)
    });
</code></pre>
<ol start="4">
<li><p><strong>Frequent Updates</strong>: In applications where data changes frequently, PATCH makes it easier to update specific parts of a resource without affecting the entire structure. For instance, in an e-commerce platform, users might regularly update their shipping address or payment method, and PATCH can handle those frequent changes without requiring the entire user profile to be re-sent.</p>
<ul>
<li>Example: Updating the delivery address for an order.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedAddress = {
      <span class="hljs-attr">shippingAddress</span>: <span class="hljs-string">'123 New Street, New City, Country'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/orders/987'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedAddress)
    });
</code></pre>
<h3 id="heading-key-differences-between-put-and-patch">Key Differences Between PUT and PATCH</h3>
<p>Here’s a quick comparison of PATCH and PUT to clarify when each method is more appropriate:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>PUT</td><td>PATCH</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Purpose</strong></td><td>Replaces the entire resource.</td><td>Partially updates a resource.</td></tr>
<tr>
<td><strong>Data Handling</strong></td><td>Requires the entire resource to be sent.</td><td>Sends only the fields that need to be updated.</td></tr>
<tr>
<td><strong>Efficiency</strong></td><td>Less efficient for large resources.</td><td>More efficient for small, specific updates.</td></tr>
<tr>
<td><strong>Idempotence</strong></td><td>Idempotent (same result if repeated).</td><td>Not necessarily idempotent (depends on the request).</td></tr>
<tr>
<td><strong>Risk of Data Loss</strong></td><td>Can overwrite fields if data is missing.</td><td>Does not overwrite existing fields unless specified.</td></tr>
</tbody>
</table>
</div><p><strong>PATCH</strong> is particularly valuable when you want to make partial updates, avoid overwriting other data, and improve the efficiency of your requests.</p>
<h2 id="heading-delete-method">DELETE Method</h2>
<p>The DELETE method is used to remove a resource from the server. When a DELETE request is made, the server deletes the specified resource, meaning it’s no longer accessible or available. This method is used for tasks like deleting a user account, removing a product from an online store, or clearing old data from a database.</p>
<p>Unlike GET or POST, DELETE doesn’t require sending a body in the request—just the URL of the resource you want to remove is enough. For example, to delete a specific blog post, a DELETE request is sent to the URL of that post, and the server takes care of removing it.</p>
<h3 id="heading-how-delete-works">How DELETE Works</h3>
<p>To delete a resource, you typically only need to provide the URL of the resource you want to remove. Unlike POST or PUT requests, DELETE requests generally don’t require a body.</p>
<h4 id="heading-example">Example:</h4>
<p>If you want to delete a specific blog post, you can send a DELETE request to its URL:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://example.com/posts/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Resource deleted:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>This tells the server to remove the blog post with ID <code>123</code>.</p>
<h3 id="heading-safely-using-delete">Safely Using DELETE</h3>
<p>DELETE requests can have a significant impact, so it’s important to use them carefully to avoid accidentally removing valuable data. Below are some key considerations for safely handling DELETE requests:</p>
<ul>
<li><p><strong>Permanent Action</strong>: Once a DELETE request is processed, the resource is typically gone. In some cases, systems might implement "soft delete" functionality, where the resource is hidden but not completely removed. However, most use a "hard delete," where the resource is fully erased. Soft deletes can be useful for recovery purposes, allowing data to be restored if needed.</p>
</li>
<li><p><strong>Authentication</strong>: DELETE requests should be restricted to authorized users. Before performing a DELETE action, the server should validate that the user has permission to delete the resource. For example, only the owner of a user account should be able to delete it, not another user.</p>
</li>
<li><p><strong>Confirmation</strong>: Many applications prompt users to confirm their intention before processing a DELETE action. This extra step ensures users don't accidentally delete important data, especially for irreversible actions like account deletion.</p>
</li>
</ul>
<h4 id="heading-example-of-a-confirmation-step">Example of a Confirmation Step:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (confirm(<span class="hljs-string">"Are you sure you want to delete this post?"</span>)) {
  fetch(<span class="hljs-string">'https://example.com/posts/123'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>
  })
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Post deleted'</span>))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
}
</code></pre>
<ul>
<li><strong>Reversibility (Soft Delete)</strong>: For important data, it’s often useful to implement a <strong>soft delete</strong>, which doesn’t completely remove the data but marks it as deleted in the database. This allows the data to be restored later if needed. For example, many email systems keep deleted messages in a "Trash" folder until they are permanently removed.</li>
</ul>
<h3 id="heading-best-practices-for-handling-delete-requests">Best Practices for Handling DELETE Requests</h3>
<ol>
<li><p><strong>Require Authentication</strong>: Only authenticated users should be able to perform DELETE actions. This prevents unauthorized users from deleting resources they don't own. For example, users should only be allowed to delete their own data, not that of others.</p>
<ul>
<li><strong>Example</strong>: In a content management system (CMS), ensure that only the author of a post or an admin can delete it.</li>
</ul>
</li>
<li><p><strong>Use Confirmation Steps</strong>: For critical actions, confirm the user’s intent before proceeding. This is especially important for actions that cannot be undone, such as deleting an account or permanently removing a file.</p>
<ul>
<li><strong>Example</strong>: Show a prompt that says, "Are you sure you want to delete your account? This action cannot be undone."</li>
</ul>
</li>
<li><p><strong>Log Deletions</strong>: Keep a record of DELETE requests, including who initiated the request and when it occurred. Logging is important for accountability, troubleshooting, and data recovery in case of accidental deletions.</p>
<ul>
<li><strong>Example</strong>: In an e-commerce system, log details when a product is removed from the catalog, such as the user who initiated the request and the time of deletion.</li>
</ul>
</li>
<li><p><strong>Soft Delete for Critical Data</strong>: Implement a soft delete mechanism for data that may need to be restored later. This is particularly useful in scenarios like user accounts, where a user might want to recover their data after deletion.</p>
<ul>
<li><strong>Example</strong>: When a user "deletes" their account, it’s marked as inactive or hidden, rather than fully erased, allowing the user to recover it later.</li>
</ul>
</li>
<li><p><strong>Handle Errors Gracefully</strong>: If a DELETE request fails, the server should return an appropriate error message. For example, if the resource doesn’t exist or the user isn’t authorized to delete it, the server should respond with a message like "Resource not found" or "Unauthorized action."</p>
<ul>
<li><strong>Example</strong>: A DELETE request for a non-existent user could return a <code>404 Not Found</code> response.</li>
</ul>
</li>
<li><p><strong>Double-Check URL Targeting</strong>: Before sending a DELETE request, ensure the URL points to the correct resource. Accidentally targeting the wrong resource could result in unintended data loss.</p>
<ul>
<li><strong>Example</strong>: If you are managing a to-do list and want to delete a single task, ensure the URL points specifically to that task and not to the entire list.</li>
</ul>
</li>
<li><p><strong>Communicate Results to the User</strong>: After a successful DELETE request, inform the user that the resource has been deleted. This can be done through a message or notification confirming the action.</p>
<ul>
<li><strong>Example</strong>: Show a message like "Item successfully deleted" after a product or post has been removed from the system.</li>
</ul>
</li>
</ol>
<h3 id="heading-delete-response">DELETE Response</h3>
<p>Typically, a successful DELETE request returns one of the following status codes:</p>
<ul>
<li><p><strong>200 OK</strong>: Indicates that the deletion was successful and includes a response body (for example, a message confirming the deletion).</p>
</li>
<li><p><strong>204 No Content</strong>: The request was successful, but no content is returned in the response body. This is common when the resource is deleted, and there’s nothing to send back.</p>
</li>
<li><p><strong>404 Not Found</strong>: Indicates that the resource to be deleted does not exist.</p>
</li>
</ul>
<h3 id="heading-example-of-a-delete-request-response">Example of a DELETE Request Response</h3>
<p>If the DELETE request is successful and the resource is removed, a server might respond with a <code>204 No Content</code> status:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">204</span> No Content
</code></pre>
<p>This response tells the client that the resource was successfully deleted but doesn’t return any additional data.</p>
<h2 id="heading-head-method">HEAD Method</h2>
<p>The HEAD method is similar to the GET method but with a key difference: it only retrieves the headers of a resource, not the actual content.</p>
<p>When you send a HEAD request, the server responds with the same headers as a GET request, but without sending the body of the resource (like text, images, or files). This makes HEAD useful for checking information about a resource, such as its size or last modified date, without downloading the entire content.</p>
<p>For example, if you're managing a large file and want to check its size before downloading, you can use a HEAD request to get this information from the server without actually fetching the file itself.</p>
<h3 id="heading-how-head-compares-to-get">How HEAD Compares to GET</h3>
<ul>
<li><p><strong>Same Headers, No Content</strong>: The HEAD request provides the same headers you’d receive with a GET request, such as <code>Content-Type</code>, <code>Content-Length</code>, <code>Last-Modified</code>, and so on. However, the response contains no body—just the metadata.</p>
</li>
<li><p><strong>Faster Requests</strong>: Because no body is included, HEAD requests are faster and consume less bandwidth than GET requests. This is helpful when you're only interested in details about the resource, not the content itself.</p>
</li>
</ul>
<h3 id="heading-use-cases-for-head">Use Cases for HEAD</h3>
<ol>
<li><p><strong>Checking Resource Availability</strong>: You can use a HEAD request to check whether a resource (such as a webpage or file) exists without fetching the content. For example, if a URL returns a status code like <code>200 OK</code>, you know the resource is there. A <code>404 Not Found</code> status code would indicate that it’s not available.</p>
</li>
<li><p><strong>Testing Links</strong>: If you manage a website with numerous external links, a HEAD request can test whether those links are still valid, saving you from loading the entire page. If a HEAD request returns an error code, you know the link is broken.</p>
</li>
<li><p><strong>Fetching File Metadata</strong>: If you’re dealing with large files, you might want to check their size before downloading. A HEAD request allows you to gather metadata like the file size (<code>Content-Length</code>) and type (<code>Content-Type</code>) without retrieving the entire file.</p>
</li>
<li><p><strong>Optimizing Caching</strong>: Browsers and applications can use HEAD requests to check if a resource has been updated since it was cached. The server returns headers like <code>Last-Modified</code> or <code>ETag</code>, and if these values haven’t changed, the cached version can be used, saving bandwidth and time.</p>
</li>
<li><p><strong>API Efficiency</strong>: HEAD requests can be useful in APIs when a client needs to verify that data exists without downloading the entire response. For example, a request could check whether a record exists in a database without fetching the full details.</p>
</li>
<li><p><strong>Server Health Monitoring</strong>: HEAD requests can be used to measure server performance. By testing the speed of a response without downloading content, developers can monitor server response times, check for issues, or determine if the server is up.</p>
</li>
</ol>
<h3 id="heading-best-practices-for-using-head">Best Practices for Using HEAD</h3>
<ul>
<li><p><strong>Efficient Testing</strong>: HEAD is ideal for validating resources or testing API endpoints without downloading unnecessary data.</p>
</li>
<li><p><strong>Caching</strong>: HEAD requests help with cache validation, ensuring that a resource is up-to-date without consuming bandwidth.</p>
</li>
<li><p><strong>No Side Effects</strong>: Like GET, HEAD should be safe and idempotent, meaning it should not alter the state of the resource. It’s used purely for retrieving information.</p>
</li>
</ul>
<h2 id="heading-options-method">OPTIONS Method</h2>
<p>The OPTIONS method is used to find out what actions are allowed on a specific resource. It allows a client (like a browser or an API) to ask the server, "What operations can I perform on this resource?" In response, the server lists the HTTP methods it supports for that resource, such as GET, POST, PUT, DELETE, and so on.</p>
<p>OPTIONS doesn’t perform any operation on the resource itself. Instead, it provides information about what the client can do. This makes it useful when you want to check what actions are allowed before actually making a request that changes or retrieves data.</p>
<p>For example, if you’re working with an API and want to see if it supports a DELETE method on a particular endpoint, you can send an OPTIONS request to get that information without affecting the resource.</p>
<h3 id="heading-retrieving-supported-methods">Retrieving Supported Methods</h3>
<ol>
<li><p><strong>Sending an OPTIONS Request</strong>: The client sends an OPTIONS request to a server, typically targeting a specific URL. This request serves as an inquiry about what actions are permitted on the resource at that endpoint.</p>
</li>
<li><p><strong>Server’s Response</strong>: The server responds with an <code>Allow</code> header that lists the available HTTP methods for the resource. For example, it might return <code>Allow: GET, POST, DELETE</code>, meaning those methods can be used.</p>
</li>
<li><p><strong>Testing for Methods</strong>: If you're unsure whether a particular method (like PATCH or DELETE) is supported by a server, you can send an OPTIONS request first to check. This avoids attempting methods that the server doesn’t support, which could result in errors.</p>
</li>
</ol>
<h4 id="heading-example-1">Example:</h4>
<pre><code class="lang-http"><span class="hljs-keyword">OPTIONS</span> <span class="hljs-string">/api/resource</span> HTTP/1.1
<span class="hljs-attribute">Host</span>: example.com
</code></pre>
<p>Server Response:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">200</span> OK
<span class="hljs-attribute">Allow</span>: GET, POST, DELETE
</code></pre>
<h3 id="heading-how-options-is-used-in-cross-origin-resource-sharing-cors">How OPTIONS is Used in Cross-Origin Resource Sharing (CORS)</h3>
<p>One of the most common uses of the OPTIONS method is in handling <strong>Cross-Origin Resource Sharing (CORS)</strong>. CORS is a security feature that ensures resources on one domain aren’t accessed improperly by web pages from another domain.</p>
<h4 id="heading-cors-and-preflight-requests">CORS and Preflight Requests</h4>
<p>When a browser needs to make a cross-origin request (for example, a request from <a target="_blank" href="http://domainA.com"><code>domainA.com</code></a> to <a target="_blank" href="http://api.domainB.com"><code>api.domainB.com</code></a>), the browser first sends an <strong>OPTIONS request</strong>, known as a <strong>preflight request</strong>, to the target server. The preflight request checks whether the actual request is allowed under the server’s CORS policy.</p>
<ol>
<li><p><strong>Preflight Request</strong>: The browser sends an OPTIONS request before the actual request (such as a POST or PUT). This request asks the server which methods are allowed, which domains can access the resource, and whether specific headers or credentials are permitted.</p>
</li>
<li><p><strong>Server’s Response</strong>: The server responds with CORS headers, such as <code>Access-Control-Allow-Methods</code>, <code>Access-Control-Allow-Origin</code>, and <code>Access-Control-Allow-Headers</code>. This tells the browser whether the request can proceed and what methods or domains are allowed.</p>
<p> Example Response:</p>
<pre><code class="lang-http"> HTTP/1.1 204 No Content
 Access-Control-Allow-Origin: https://domainA.com
 Access-Control-Allow-Methods: GET, POST
 Access-Control-Allow-Headers: Content-Type
</code></pre>
</li>
<li><p><strong>Ensuring Security</strong>: CORS and the preflight OPTIONS request ensure that cross-origin requests are only allowed when the server permits it. Without this security step, websites could make unauthorized requests to other domains.</p>
</li>
<li><p><strong>Handling Complex Requests</strong>: If a request includes custom headers, uses HTTP methods other than simple ones like GET or POST, or sends credentials like cookies, the browser automatically sends an OPTIONS preflight request. If the server denies the request (that is, returns headers disallowing the action), the browser blocks the request.</p>
</li>
</ol>
<h4 id="heading-simplified-workflow">Simplified Workflow:</h4>
<ul>
<li><p><strong>Browser</strong>: "Can I make this request to <a target="_blank" href="http://api.domainB.com"><code>api.domainB.com</code></a>?"</p>
</li>
<li><p><strong>Server</strong>: "Yes, you can use <code>GET</code> and <code>POST</code>, but only from <a target="_blank" href="http://domainA.com"><code>domainA.com</code></a> and with these headers."</p>
</li>
<li><p><strong>Browser</strong>: Proceeds with the actual request if the response permits.</p>
</li>
</ul>
<h3 id="heading-use-cases-for-the-options-method">Use Cases for the OPTIONS Method</h3>
<ul>
<li><p><strong>Discovering Available Methods</strong>: Useful for developers to check which HTTP methods a resource supports before performing an operation.</p>
</li>
<li><p><strong>CORS Preflight</strong>: Critical in web security to ensure that cross-origin requests are properly authorized.</p>
</li>
<li><p><strong>Improving API Efficiency</strong>: APIs can expose the supported methods for a resource via OPTIONS, making it easier for clients to understand what operations can be performed.</p>
</li>
</ul>
<p>The OPTIONS method is thus essential in web applications for managing request permissions and improving security, particularly in cross-domain scenarios.</p>
<h2 id="heading-trace-method">TRACE Method</h2>
<p>The TRACE method is used to debug web applications and test how requests pass through networks. When you send a TRACE request, it triggers a loopback, where the server sends back the exact request it received, without any changes. This helps developers see if anything is modified as the request travels through different systems, like firewalls or proxies, before reaching the server.</p>
<p>In simple terms, TRACE allows you to trace the path your request takes from your client (like a browser or API tool) to the server and back. This method can be useful for identifying issues during the transmission of a request.</p>
<h3 id="heading-understanding-loopback-diagnostics">Understanding Loopback Diagnostics</h3>
<p>Loopback diagnostics refers to the process of seeing how data is handled as it moves across networks, using TRACE to check if the original request remains intact. Here’s how it works:</p>
<ol>
<li><p><strong>Sending a TRACE Request</strong>: You send a TRACE request to a server. This request is usually small, containing basic information like the method, URL, and headers. It doesn't carry any extra data or payload like POST or PUT methods.</p>
</li>
<li><p><strong>Server’s Response</strong>: Instead of responding with a resource, the server sends back the exact request it received. This includes the HTTP method, the URL, headers, and anything else in the original request. The server doesn’t modify or process the request—it just returns it exactly as it was received.</p>
</li>
<li><p><strong>Tracing the Path</strong>: When the TRACE response comes back, it allows you to see the entire path the request took, including any changes made to the request headers or content. This is useful for diagnosing issues such as:</p>
<ul>
<li><p><strong>Proxy Servers</strong>: If your request passes through one or more proxy servers before reaching the destination, TRACE can show if those proxies have altered the request headers or content.</p>
</li>
<li><p><strong>Network Firewalls</strong>: Some network firewalls might add or modify headers as your request passes through them. TRACE helps reveal these modifications.</p>
</li>
<li><p><strong>Error Tracking</strong>: If a request fails to behave as expected, TRACE can help track where something went wrong in the transmission.</p>
</li>
</ul>
</li>
<li><p><strong>Effective Debugging</strong>: TRACE is especially helpful when debugging web applications or APIs. If your application is experiencing errors due to routing, proxies, or server configurations, TRACE lets you see the unaltered request, making it easier to pinpoint the issue.</p>
</li>
</ol>
<h3 id="heading-security-concerns-with-trace">Security Concerns with TRACE</h3>
<p>Although TRACE can be useful for debugging, it is generally considered a security risk and is often disabled on most servers for several reasons:</p>
<ol>
<li><p><strong>XSS Attacks (Cross-Site Scripting)</strong>: TRACE can expose sensitive information such as cookies or authentication tokens in the headers. Malicious actors could exploit TRACE to capture these details, leading to security breaches, especially if a vulnerability like cross-site scripting (XSS) is present. This makes TRACE a potential target for attackers trying to steal user data.</p>
</li>
<li><p><strong>Request Modification Exposure</strong>: Since TRACE shows all modifications made to a request, it can also reveal how internal proxies and firewalls handle requests. This could give attackers insight into the internal workings of a network, making it easier for them to plan further attacks.</p>
</li>
<li><p><strong>Disabling TRACE for Safety</strong>: For these reasons, TRACE is often disabled on most web servers to prevent abuse. In many modern web applications, more secure methods exist for debugging requests and tracing network paths, so TRACE is rarely necessary in everyday use.</p>
</li>
<li><p><strong>Safer Alternatives</strong>: Developers can use safer diagnostic tools and logging features built into modern web frameworks and APIs. These alternatives provide similar insights without exposing security risks associated with TRACE.</p>
</li>
</ol>
<h2 id="heading-connect-method">CONNECT Method</h2>
<p>The CONNECT method is mainly used to establish a tunnel between a client and a server through an intermediary, usually a proxy server. When the client sends a CONNECT request, the server creates a tunnel that allows encrypted data to flow between the client and the destination server. This method is crucial for securing connections, especially when dealing with HTTPS.</p>
<p>CONNECT does not handle any actual data on its own. Instead, it sets up a path for secure communication, allowing encrypted information to pass through proxies without being modified or inspected.</p>
<h3 id="heading-how-connect-works">How CONNECT Works</h3>
<ol>
<li><p><strong>Sending a CONNECT Request</strong>: A client, such as a web browser, sends a CONNECT request to the proxy server. This request includes the target server's hostname and port, typically the standard HTTPS port (443). For example, when accessing <a target="_blank" href="https://example.com"><code>https://example.com</code></a>, the browser sends a CONNECT request to the proxy server asking it to connect to that domain on port 443.</p>
</li>
<li><p><strong>Establishing the Tunnel</strong>: The proxy server, upon receiving the CONNECT request, establishes a tunnel to the destination server. This tunnel allows encrypted communication to pass through without interference. The proxy simply forwards traffic between the client and the destination, acting as a relay.</p>
</li>
<li><p><strong>Encrypted Communication</strong>: Once the tunnel is set up, the client and the destination server can communicate directly using a secure encryption protocol, such as TLS (used by HTTPS). The proxy cannot decrypt or modify the data passing through because it’s encrypted between the client and the server.</p>
</li>
<li><p><strong>Secure Data Transfer</strong>: With the CONNECT method, sensitive data—such as login credentials, personal information, or financial transactions—can be transmitted securely between the client and the server, even when passing through proxies. The encrypted tunnel ensures that the data remains confidential and intact.</p>
</li>
</ol>
<h3 id="heading-example-of-a-connect-request-and-response">Example of a CONNECT Request and Response</h3>
<ul>
<li><p><strong>CONNECT Request</strong>:</p>
<pre><code class="lang-http">  CONNECT example.com:443 HTTP/1.1
  Host: example.com
</code></pre>
</li>
<li><p><strong>Proxy Response</strong> (if the tunnel is successfully established):</p>
<pre><code class="lang-http">  HTTP/1.1 200 Connection Established
</code></pre>
</li>
</ul>
<h3 id="heading-tunneling-with-connect">Tunneling with CONNECT</h3>
<p>The term <strong>tunneling</strong> in this context refers to creating a direct, secure link between the client and the destination server via a proxy. The proxy acts as a middleman but does not interfere with or access the encrypted data being transmitted through the tunnel.</p>
<h4 id="heading-steps-of-the-tunneling-process">Steps of the Tunneling Process:</h4>
<ul>
<li><p><strong>Sending the CONNECT Request</strong>: The client sends a CONNECT request to the proxy, specifying the destination server and port (for example, port 443 for HTTPS).</p>
</li>
<li><p><strong>Proxy Sets Up the Tunnel</strong>: The proxy server establishes a secure tunnel between the client and the destination server, forwarding traffic between the two endpoints.</p>
</li>
<li><p><strong>Encrypted Communication Begins</strong>: The client and the destination server communicate directly through the encrypted tunnel using HTTPS or another encryption protocol. The proxy forwards the encrypted traffic but cannot access or modify it.</p>
</li>
</ul>
<h3 id="heading-typical-use-cases-of-the-connect-method">Typical Use Cases of the CONNECT Method</h3>
<ol>
<li><p><strong>HTTPS Through Proxies</strong>: One of the most common uses of the CONNECT method is enabling <strong>HTTPS traffic through proxies</strong>. In many corporate or network environments, internet traffic must pass through a proxy server. For secure websites using HTTPS, the CONNECT method allows the proxy server to establish a tunnel, forwarding encrypted traffic between the client and the destination server without inspecting the data.</p>
<ul>
<li><strong>Example</strong>: When you visit a secure banking website from a corporate network, your browser may need to pass through a corporate proxy. The CONNECT method is used to establish an encrypted tunnel between your browser and the bank's website, allowing sensitive data (such as login credentials) to pass through the proxy securely.</li>
</ul>
</li>
<li><p><strong>VPNs and Secure Channels</strong>: <strong>VPN (Virtual Private Network)</strong> services also rely on similar tunneling techniques to encrypt and route internet traffic securely. Some VPN services use CONNECT to create secure tunnels, ensuring that all data transmitted between the user and the internet is encrypted and safe from eavesdropping.</p>
</li>
<li><p><strong>Accessing Blocked Content</strong>: In environments where certain websites are blocked (for example, schools or offices), CONNECT can sometimes be used to bypass restrictions by establishing a tunnel through a proxy. Although this practice may violate network policies, it illustrates how CONNECT can be used to establish secure, unmonitored access to otherwise blocked resources.</p>
</li>
<li><p><strong>Custom Proxies</strong>: Developers may set up <strong>custom proxies</strong> to route application traffic for performance or security reasons. In these cases, CONNECT allows HTTPS or other secure traffic to pass through the proxy while maintaining privacy and security, as the proxy server cannot access the encrypted data inside the tunnel.</p>
</li>
</ol>
<h3 id="heading-security-considerations">Security Considerations</h3>
<p>While CONNECT is essential for secure communications, it also presents some security challenges:</p>
<ul>
<li><p><strong>Bypassing Content Filters</strong>: Since CONNECT creates an encrypted tunnel that proxies cannot inspect, it can be used to bypass content filtering systems. This allows users to access restricted websites or services, which may violate organizational policies.</p>
</li>
<li><p><strong>Tunneling Malicious Traffic</strong>: CONNECT can be exploited by malicious actors to tunnel harmful or unauthorized traffic through a proxy. Because the traffic is encrypted, firewalls and security systems may not detect malicious activity.</p>
</li>
<li><p><strong>Mitigation</strong>: Many organizations address these risks by closely monitoring and restricting the use of the CONNECT method. Some proxies perform <strong>SSL interception</strong> to decrypt and inspect HTTPS traffic, though this introduces privacy concerns and may compromise user security.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>HTTP methods are essential in enabling communication between web applications and servers. Each method, from GET to CONNECT, is designed for a specific task, such as sending data, retrieving information, updating resources, or setting up secure connections. Choosing the correct method for the job improves the efficiency and security of your application.</p>
<p>GET is ideal for retrieving data, POST and PUT help with creating and updating, PATCH handles partial updates, and DELETE removes resources. HEAD checks response headers without retrieving content, OPTIONS shows supported methods, and TRACE and CONNECT assist with debugging and secure communication.</p>
<p>Using the appropriate HTTP methods ensures your application runs efficiently and securely, offering a smooth experience for users.</p>
<p>If you have any questions or suggestions, feel free to reach out on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Send HTTP Requests Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Nowadays, the interaction between web applications relies on HTTP. For instance, let's say you have an online shop application and you want to create a new product. You have to fill in all the necessary information and probably click on a button that... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-send-http-requests-using-javascript/</link>
                <guid isPermaLink="false">66bb8a946b3bd8d6bf25ae44</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eric Hu ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jul 2024 17:06:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/js-http.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Nowadays, the interaction between web applications relies on <a target="_blank" href="https://www.freecodecamp.org/news/what-is-http/">HTTP</a>. For instance, let's say you have an online shop application and you want to create a new product. You have to fill in all the necessary information and probably click on a button that says "Create".</p>
<p>This action will send an HTTP request to the backend, along with all the necessary data, and the backend application will use that data to make changes to the database. After the action is complete, whether successful or not, an HTTP response will be sent back to the frontend, which will act accordingly based on the status of that response.</p>
<p>When these requests and responses are transferred back and forth, they need to follow a certain format so that both ends can understand each other. HTTP was created for this purpose. It is a standard network protocol that enables web applications to understand and communicate with each other.</p>
<h2 id="heading-what-are-the-http-request-methods">What Are the HTTP Request Methods?</h2>
<p>There are several methods you can use to send an HTTP request, and each of them serves a different purpose, as shown below:</p>
<h3 id="heading-the-get-method">The <code>GET</code> Method</h3>
<p>The <code>GET</code> method is used to request data and resources from the server. When you send a <code>GET</code> request, the query parameters are embedded in the URL in name/value pairs like this:</p>
<pre><code class="lang-text">http://example.com/index.html?name1=value1&amp;name2=value2
</code></pre>
<p>Note that the question mark (<code>?</code>) denotes the beginning of a list of parameters. Each parameter forms a key/value pair (<code>name=value</code>), and the ampersand (<code>&amp;</code>) is used to divide two different parameters.</p>
<h3 id="heading-the-post-method">The <code>POST</code> Method</h3>
<p>The <code>POST</code> method is used to send data to the server, either adding a new resource or updating an existing resource. The parameters are stored in the body of the HTTP request.</p>
<pre><code class="lang-text">POST /index.html HTTP/1.1
Host: example.com
name1=value1&amp;name2=value2
</code></pre>
<h3 id="heading-the-delete-method">The <code>DELETE</code> Method</h3>
<p>This method removes a resource from the server.</p>
<h3 id="heading-the-head-method">The <code>HEAD</code> Method</h3>
<p>The <code>HEAD</code> method works just like <code>GET</code> except that the HTTP response sent from the server will only contain the head but not the body. This means that if the server is "OK" with the request, it will give you a <code>200 OK</code> response but not the resource you requested. You can only retrieve the resource with the <code>GET</code> method.</p>
<p>This is very useful when you are testing whether the server works. Sometimes, the resource may take a long time to be transmitted, and for testing purposes, you only need a <code>200 OK</code> response to know that everything works properly.</p>
<h3 id="heading-the-put-method">The <code>PUT</code> Method</h3>
<p>The <code>PUT</code> method is used to update existing resources, and it is similar to the <code>POST</code> method with one small difference.</p>
<p>When you <code>PUT</code> a resource that already exists, the old resource will be overwritten. And making multiple identical <code>PUT</code> requests will have the same effect as making it once.</p>
<p>When you <code>POST</code> identical resources, that resource will be duplicated every time the request is made.</p>
<h2 id="heading-what-is-the-fetch-api">What is the Fetch API?</h2>
<p>For a long time, the JavaScript community lacked a standard way to send HTTP requests. Some people used <code>XMLHttpRequest</code>, aka AJAX, while others prefered external libraries such as Axios or jQuery.</p>
<p>The fetch API was introduced in 2015 as the modern, simplified, and standard way of making HTTP requests using JavaScript. It is natively supported, so there is no need to install any third-party libraries.</p>
<h2 id="heading-how-to-send-a-get-request-using-javascript">How to Send a GET Request Using JavaScript</h2>
<p>The fetch API is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise-based</a>, which means that it offers a clean and concise syntax for writing asynchronous operations. For example, this is how you can send a <code>GET</code> request using the fetch API.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-comment">// If the response is not 2xx, throw an error</span>
    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Network response was not ok"</span>);
    }

    <span class="hljs-comment">// If the response is 200 OK, return the response in JSON format.</span>
    <span class="hljs-keyword">return</span> response.json();
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data)) <span class="hljs-comment">// You can continue to do something to the response.</span>
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Fetch error:"</span>, error)); <span class="hljs-comment">// In case of an error, it will be captured and logged.</span>
</code></pre>
<p>You can also include custom options with the request, such as custom headers, authorization tokens, and so on.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, {
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
    <span class="hljs-string">"Authorization"</span>: <span class="hljs-string">"your-token-here"</span>,
  },
  <span class="hljs-attr">credentials</span>: <span class="hljs-string">"same-origin"</span>,
})
  .then(. . .);
</code></pre>
<h2 id="heading-how-to-send-a-post-request-using-javascript">How to Send a POST Request Using JavaScript</h2>
<p>When sending a <code>POST</code> request, things get a bit more complex because you need to send data to the server with the request body. This could get complicated depending on the kind of data you're sending and your specific use case.</p>
<p>For example, the following code sends JSON data to the backend:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">"johndoe@example.com"</span>,
  }),
});
</code></pre>
<p>There are a few things you must pay attention here. First of all, you must explicitly specify the request method. If you leave this out, the default <code>GET</code> method will be used.</p>
<p>Also, the request body only accepts string data, so you must use the <code>stringify()</code> method to convert JSON into a string before assigning it to the request body.</p>
<p>This is also why it is important to include the <code>Content-Type</code> header, which lets whoever is on the receiving end know how to parse the request body.</p>
<p>However, things are usually more complex in practice. For example, when working with web forms, instead of JSON, you are likely using the <code>x-www-form-urlencoded</code> form encoding, in which case the request can be sent like this.</p>
<p>The following example assumes you understand what <a target="_blank" href="https://www.freecodecamp.org/news/dom-events-and-javascript-event-listeners/">event handlers</a> are.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"DOMContentLoaded"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"form"</span>);
  <span class="hljs-keyword">const</span> usernameInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"username"</span>);
  <span class="hljs-keyword">const</span> emailInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"email"</span>);

  <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> URLSearchParams();

  usernameInput.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    formData.set(<span class="hljs-string">"username"</span>, usernameInput.value);
  });

  emailInput.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    formData.set(<span class="hljs-string">"email"</span>, emailInput.value);
  });

  form.addEventListener(<span class="hljs-string">"submit"</span>, <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
    event.preventDefault(); <span class="hljs-comment">// Prevent the default form submission action</span>

    <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
      <span class="hljs-attr">body</span>: formData.toString(),
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/x-www-form-urlencoded"</span>,
      },
    });
  });
});
</code></pre>
<p>If you need to upload files to the backend, you'll need the <code>multipart/form-data</code> form encoding instead.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"DOMContentLoaded"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myForm"</span>);
  <span class="hljs-keyword">const</span> usernameInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"username"</span>);
  <span class="hljs-keyword">const</span> emailInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"email"</span>);
  <span class="hljs-keyword">const</span> pictureInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"picture"</span>);

  <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();

  usernameInput.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    formData.set(<span class="hljs-string">"username"</span>, usernameInput.value);
  });

  emailInput.addEventListener(<span class="hljs-string">"input"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    formData.set(<span class="hljs-string">"email"</span>, emailInput.value);
  });

  pictureInput.addEventListener(<span class="hljs-string">"change"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    formData.set(<span class="hljs-string">"picture"</span>, pictureInput.files[<span class="hljs-number">0</span>]);
  });

  form.addEventListener(<span class="hljs-string">"submit"</span>, <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
    event.preventDefault(); <span class="hljs-comment">// Prevent the default form submission</span>

    <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
      <span class="hljs-attr">body</span>: formData,
    });
  });
});
</code></pre>
<p>Note that when using the <code>FormData()</code> to construct the request body, the <code>Content-Type</code> will be locked into <code>multipart/form-data</code>. In this case, it is not necessary to set a custom <code>Content-Type</code> header.</p>
<h2 id="heading-how-to-send-a-put-request-using-javascript">How to Send a PUT Request Using JavaScript</h2>
<p>The <code>PUT</code> request works similarly to <code>POST</code>, but you must remember to set <code>method</code> to <code>PUT</code>.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"PUT"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">id</span>: <span class="hljs-string">"123"</span>
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">"johndoe@example.com"</span>,
  }),
});
</code></pre>
<p>Realistically, you'll have to provide an <code>id</code>, or any other key that enables you to locate the record to be updated in the backend.</p>
<h2 id="heading-how-to-send-a-delete-request-using-javascript">How to Send a DELETE Request Using JavaScript</h2>
<p>The <code>DELETE</code> request works similarly to <code>PUT</code>, but remember to set <code>method</code> to <code>DELETE</code>.</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/users/123"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"DELETE"</span>,
});
</code></pre>
<p>And similarly, remember to provide an <code>id</code> so that the backend application knows which record to delete.</p>
<h2 id="heading-how-to-send-a-request-using-xmlhttprequest-ajax">How to Send a Request Using XMLHttpRequest (AJAX)</h2>
<p>Besides <code>fetch()</code>, it is also possible to make an HTTP request using <code>XMLHttpRequest</code>. The following example demonstrates how to make a <code>GET</code> request to the endpoint <code>https://jsonplaceholder.typicode.com</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.open(<span class="hljs-string">"GET"</span>, <span class="hljs-string">"https://jsonplaceholder.typicode.com/users"</span>, <span class="hljs-literal">true</span>);
xhr.onload = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (xhr.status &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.status &lt; <span class="hljs-number">300</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(xhr.responseText));
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, xhr.statusText);
  }
};
xhr.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Request failed"</span>);
};
xhr.send();
</code></pre>
<p>The syntax is a bit more complex, as <code>XMLHttpRequest</code> relies on callback functions to work with asynchronous operations, which means it is easy to lead to what is known as the callback hell, where you have layers upon layers of callback functions, making your code base difficult to read and maintain.</p>
<p>However, <code>XMLHttpRequest</code> does have some advantages. Due to the fact that <code>XMLHttpRequest</code> is much older compared to <code>fetch()</code>, it is more widely supported. You should consider using <code>XMLHttpRequest</code> when your web app needs to be compatible with older browsers.</p>
<h2 id="heading-how-to-send-a-request-using-external-libraries">How to Send a Request Using External Libraries</h2>
<p>Aside from the built-in methods, you can also send HTTP requests using third-party libraries. For instance, this is how you can send a <code>GET</code> request using jQuery:</p>
<pre><code class="lang-javascript">$.get(<span class="hljs-string">"https://api.example.com/data"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
  <span class="hljs-built_in">console</span>.log(data);
}).fail(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error);
});
</code></pre>
<p><a target="_blank" href="https://jquery.com/">jQuery</a> is one of the most popular JavaScript libraries. It aims to fix the part of JavaScript that is difficult to use, and it has been pretty successful at that.</p>
<p>In recent years, jQuery has lost some popularity as vanilla JavaScript has improved over the years and the problems that used to bother people have been fixed. It is no longer the go-to choice for creating JavaScript applications, especially for newer developers.</p>
<p>Alternatively, you could go with Axios, which is a promise-based HTTP client just like <code>fetch()</code>, and it has been people's favorite for a very long time before <code>fetch()</code> came.</p>
<pre><code class="lang-javascript">axios
  .get(<span class="hljs-string">"https://api.example.com/data"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios error:"</span>, error));
</code></pre>
<p><a target="_blank" href="https://axios-http.com/docs/intro">Axios</a> and <code>fetch()</code> have very similar syntax as they are both promise-based. The main difference between them is that <code>fetch()</code> is built-in, while Axios requires you to install an external library. However, Axios is much more feature-rich, as it comes with request/response interceptors, automatic JSON handling, and built-in timeouts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We introduced four different ways you could send HTTP requests using JavaScript in this tutorial. It is up to you to decide which is best for your project.</p>
<p>The fetch API is the modern and standard way of making HTTP requests using JavaScript. It has a relatively simple syntax, which makes your project easier to maintain.</p>
<p><code>XMLHttpRequest</code> is the legacy method of sending HTTP requests. It is generally not recommended for use in new projects, but if your project needs to be compatible with legacy browsers, <code>XMLHttpRequest</code> might still come in handy.</p>
<p>jQuery is an external package that can do a lot of things, including sending HTTP requests. Although the significance of jQuery has been fading in recent years, it is still used in many older projects, and you might encounter it in your work as a JavaScript developer.</p>
<p>Axios is a third-party library used to send HTTP requests. It has a very similar syntax to the fetch API but comes with a lot more advanced features. It is up to you to decide if you need these features. If not, it is generally recommended to use <code>fetch()</code> instead.</p>
<p>To learn more about JavaScript and web development, visit <a target="_blank" href="https://www.thedevspace.io">thedevspace.io</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Idempotence in HTTP Methods – Explained with CRUD Examples ]]>
                </title>
                <description>
                    <![CDATA[ Idempotence refers to a program's ability to maintain a particular result even after repeated actions.  For example, let's say you have a button that only opens a door when pressed. This button does not have the ability to close the door, so it stays... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/idempotency-in-http-methods/</link>
                <guid isPermaLink="false">66c3742fad70110156766fe2</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Yemi Ojedapo ]]>
                </dc:creator>
                <pubDate>Fri, 22 Dec 2023 21:19:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/pexels-robert-lens-10382808.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Idempotence refers to a program's ability to maintain a particular result even after repeated actions. </p>
<p>For example, let's say you have a button that only opens a door when pressed. This button does not have the ability to close the door, so it stays open even when it's pressed repeatedly. It simply remains in the state it was changed to by the first press.</p>
<p>This same logic applies to HTTP methods that are idempotent. Operating on idempotent HTTP methods repeatedly won't have any additional effect beyond the initial execution. </p>
<p>Understanding idempotence is important for maintaining the consistency of HTTP methods and API design. Idempotence has a significant impact on API design, as it influences how API endpoints should behave when processing requests from clients. </p>
<p>In this tutorial, I'll explain the concept of idempotence and the role it plays in building robust and functional APIs. You'll also learn about what safe methods are, how they relate to idempotence, and how to implement idempotency in non-idempotent methods. </p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before understanding and implementing idempotence in API design, it's essential to have a solid foundation in the following areas:</p>
<ul>
<li>RESTful Principles</li>
<li>Fundamentals of HTTP methods</li>
<li>API Development </li>
<li>HTTP Status codes</li>
<li>Basics of Web development.</li>
</ul>
<h2 id="heading-idempotence-example">Idempotence Example</h2>
<p>Let's start off with an example of idempotence in action. We'll create a function that uses the DELETE method to delete data from a web page:</p>
<pre><code class="lang-python">
<span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, jsonify, abort

app = Flask(__name__)

web_page_data = [
   {<span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Row 1 data"</span>},
   {<span class="hljs-string">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Row 2 data"</span>},
   <span class="hljs-comment"># Add more rows as needed</span>
]

<span class="hljs-meta">@app.route('/delete_row/&lt;int:row_id&gt;', methods=['DELETE'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete_row</span>(<span class="hljs-params">row_id</span>):</span>
   <span class="hljs-comment"># Find the row to delete</span>
   row_to_delete = next((row <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> web_page_data <span class="hljs-keyword">if</span> row[<span class="hljs-string">"id"</span>] == row_id), <span class="hljs-literal">None</span>)

   <span class="hljs-keyword">if</span> row_to_delete:
       <span class="hljs-comment"># Simulate deletion</span>
       web_page_data.remove(row_to_delete)
       <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">"message"</span>: <span class="hljs-string">f"Row <span class="hljs-subst">{row_id}</span> deleted successfully."</span>}), <span class="hljs-number">200</span>
   <span class="hljs-keyword">else</span>:
       abort(<span class="hljs-number">404</span>, description=<span class="hljs-string">f"Row <span class="hljs-subst">{row_id}</span> not found."</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
   app.run(debug=<span class="hljs-literal">True</span>)
</code></pre>
<p>This function is expected to delete the rows chosen by the user. Now because of the idempotent nature of the DELETE method, the data will be deleted once, even when called repeatedly. But subsequent calls will return a 404 error since the data has already been deleted by the first call.  </p>
<p>Let’s look at another example with the GET method. The GET method is used to retrieve data from a resource. Let’s create a function that uses the GET method to retrieve a username:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_username</span>():</span>
    url = <span class="hljs-string">'https://api.example.com/get_username'</span>
    <span class="hljs-keyword">try</span>:
        response = requests.get(url)
        <span class="hljs-keyword">if</span> response.status_code == <span class="hljs-number">200</span>:
            <span class="hljs-keyword">return</span> response.json()[<span class="hljs-string">'username'</span>]
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
    <span class="hljs-keyword">except</span> requests.RequestException <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error occurred: <span class="hljs-subst">{e}</span>"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

<span class="hljs-comment"># Usage</span>
username = get_username()
<span class="hljs-keyword">if</span> username:
    print(<span class="hljs-string">f"The username is: <span class="hljs-subst">{username}</span>"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Failed to retrieve the username."</span>)
</code></pre>
<p>In this example, we define the <code>get_username()</code> function, which sends a GET request to the API endpoint to retrieve the username. If the request is successful, we extract the username from the JSON response and return it. But if any error occurs during the request, we handle it and return <code>None</code>.</p>
<p>Now the idempotent nature of the GET method ensures that even if you call <code>get_username()</code> multiple times, the same username will be fetched from the API each time. The result will always be the same which is to fetch the username from the resource.</p>
<h3 id="heading-idempotent-vs-non-idempotent-http-methods">Idempotent vs. Non-Idempotent HTTP Methods:</h3>
<p>HTTP methods play crucial roles in determining how data is fetched, modified, or created when interacting with APIs. And Idempotency is one of the important concepts that influences data consistency and reliability in the methods used . </p>
<p>Here's a breakdown of the different methods based on their idempotency.</p>
<h4 id="heading-idempotent-methods">Idempotent methods:</h4>
<ul>
<li>GET</li>
<li>HEAD</li>
<li>PUT</li>
<li>DELETE</li>
<li>OPTIONS</li>
<li>TRACE</li>
</ul>
<h4 id="heading-non-idempotent-methods">Non-idempotent methods:</h4>
<ul>
<li>POST</li>
<li>PATCH</li>
<li>CONNECT</li>
</ul>
<h2 id="heading-safe-methods">Safe Methods</h2>
<p>In our previous example, we used the GET method to retrieve a username and this had no side effect on the server. This is because it is a safe method. </p>
<p>A safe method is a type of method that doesn’t modify the server’s state or the resource being accessed. In other words, they perform read-only operations used to retrieve data or for resource representation.</p>
<p>When you make a request using a safe method, the server does not perform any operations that modify the resource's state. Like in our previous example, we retrieved the username from the webpage which is the resource without changing anything in the server. </p>
<p>All safe methods are automatically idempotent, but not all idempotent methods are safe. This is because while idempotent methods produce consistent results when called repeatedly, some of them may still modify the server's state or the resource being accessed.</p>
<p>Like in our first example, the DELETE method is idempotent, because deleting a resource multiple times will have the same effect. But it's not safe, as it changes the server's state by removing the resource.</p>
<p>Here’s a classification of HTTP methods based on their safe status:</p>
<h4 id="heading-safe-methods-1">Safe methods:</h4>
<ul>
<li>GET</li>
<li>OPTIONS</li>
<li>HEAD</li>
</ul>
<h4 id="heading-unsafe-methods">Unsafe methods:</h4>
<ul>
<li>DELETE</li>
<li>POST</li>
<li>PUT</li>
<li>PATCH</li>
</ul>
<h3 id="heading-why-is-post-not-idempotent">Why is POST not idempotent?</h3>
<p>POST is an HTTP method that sends information to a server. When you make a POST request, you typically submit data to create a new resource or trigger a server-side action. Therefore, making the same request multiple times can result in different outcomes and side effects on the server. This can lead to duplicated data, starting server resources, and reducing performance because of the repeated action.</p>
<p>Unlike idempotent methods like GET, PUT, and DELETE, which have consistent results regardless of repetition, POST requests can cause changes to the server's state with each invocation. </p>
<p>POST requests often create new resources on the server. Repeating the same POST request will generate multiple identical resources, potentially leading to duplication.</p>
<p>This is similar to DELETE which is an idempotent method but not a safe method. Deleting the last entry in a collection using a single DELETE request would be considered idempotent. But if a developer creates a function that deletes the last entry, that would trigger DELETE multiple times. Subsequent DELETE calls would have different effects, as each one removes a unique entry. This would be considered non-idempotent.</p>
<h2 id="heading-how-to-achieve-idempotency-with-non-idempotent-methods">How to Achieve Idempotency with Non-Idempotent Methods</h2>
<p>Idempotency isn't only a property inherent to certain methods – it can also be implemented as a feature of a non-idempotent method.  </p>
<p>Here are some techniques to achieve idempotency even with non-idempotent methods.</p>
<h3 id="heading-unique-identifiers">Unique Identifiers</h3>
<p>Adding unique identifiers to every request is one of the most common techniques used to implement idempotency. It works by tracking whether the operation has already been performed or not. If it's a duplicate (a repeat request), the server knows it's already dealt with that request and simply ignores it, ensuring that no side effects occur. </p>
<p>Here's an example of how it works:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> uuid <span class="hljs-keyword">import</span> uuid4

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_order</span>(<span class="hljs-params">unique_id, order_data</span>):</span>
    <span class="hljs-keyword">if</span> Order.objects.filter(unique_id=unique_id).exists():
        <span class="hljs-keyword">return</span> HttpResponse(status=<span class="hljs-number">409</span>)  <span class="hljs-comment"># Conflict</span>
    order = Order.objects.create(unique_id=unique_id, **order_data)
    <span class="hljs-keyword">return</span> HttpResponse(status=<span class="hljs-number">201</span>, content_type=<span class="hljs-string">"application/json"</span>)

<span class="hljs-comment"># Example usage</span>
post_data = {<span class="hljs-string">"products"</span>: [...]}
headers = {<span class="hljs-string">"X-Unique-ID"</span>: str(uuid4())}
requests.post(<span class="hljs-string">"https://api.example.com/orders"</span>, data=post_data, headers=headers)
</code></pre>
<p>In this code snippet, we define a function called <code>process_order</code> that creates orders in an API, using unique identifiers to implement idempotency. </p>
<p>Here's a breakdown of the code:</p>
<h4 id="heading-importing-the-unique-identifier-generator">Importing the Unique Identifier Generator:</h4>
<p><code>from uuid import uuid4</code>: The code snippet starts by importing the <code>uuid4</code> function from the <code>uuid</code> module. This function generates unique identifiers, which are used to achieve idempotency in this code.</p>
<h4 id="heading-defining-the-processorder-function">Defining the <code>process_order</code> Function:</h4>
<p><code>def process_order(unique_id, order_data)</code>: This line defines a function named process_order that takes two arguments:</p>
<ul>
<li><code>unique_id</code>: This is a string representing a unique identifier for the request. This ensures no duplicate orders are created with the same identifier.</li>
<li><code>order_data</code>: This is a dictionary containing the actual order data, like product information and customer details.</li>
</ul>
<h4 id="heading-checking-for-existing-orders">Checking for Existing Orders:</h4>
<p><code>if Order.objects.filter(unique_id=unique_id).exists()</code>: This line checks if an order with the same unique_id already exists in the database.</p>
<p><code>Order.objects.filter(unique_id=unique_id).exists()</code> queries the Order model for orders with the matching unique_id and checks if any orders were found in the query result. If an order is found, it means the same request was already processed.</p>
<h4 id="heading-handling-existing-orders">Handling existing orders:</h4>
<p><code>return HttpResponse(status=409)</code>: If an order with the same unique_id already exists, the function immediately returns an HTTP response with status code 409 indicating a conflict. This prevents duplicate orders from being created.</p>
<h4 id="heading-creating-a-new-order-if-unique">Creating a new order (if unique):</h4>
<p><code>order = Order.objects.create(unique_id=unique_id, **order_data )</code>: This line only runs if no existing order is found.</p>
<p><code>Order.objects.create:</code> creates a new object in the Order model.</p>
<p><code>unique_id=unique_id</code> sets the unique_id attribute of the new order to the provided unique_id.</p>
<p><code>order_data</code>: spreads the dictionary order_data as keyword arguments to the order model's constructor, setting other relevant attributes like products and customer information.</p>
<h4 id="heading-sending-a-success-response">Sending a success response:</h4>
<p><code>return HttpResponse(status=201, content_type="application/json")</code>: If the order creation is successful, the function will return an HTTP response with status code 201 which shows a successful creation. It also specifies the response content type as JSON, assuming the order data might be returned in JSON format.</p>
<p><code>post_data = {"products": [...]}</code>: an example request, defines a dictionary containing the actual order data, like a list of products.</p>
<p><code>headers = {"X-Unique-ID": str(uuid4())}</code>: This line creates a dictionary containing a custom header named X-Unique-ID. It generates a unique identifier string using uuid4() and adds it to the header.</p>
<p><code>requests.post("https://api.example.com/orders", data=post_data, headers=headers</code>): This line sends a POST request to the API endpoint <code>https://api.example.com/orders</code>  with the provided <code>post_data</code> and headers.</p>
<h4 id="heading-how-does-this-implement-idempotence">How does this implement idempotence?</h4>
<p>It does so by using a unique identifier <code>(unique_id)</code> for each order. </p>
<p>It checks if an order with the same identifier already exists in the database. If it returns true, it returns a 409 Conflict status. Otherwise, it creates a new order and responds with a 201 Created status. The unique identifier prevents duplicate orders, making the system idempotent.</p>
<h3 id="heading-token-based-authorization">Token-based Authorization</h3>
<p>Token-based authorization is a form of authorization that assigns temporary tokens for each non-idempotent action. Once the action is completed, the token is invalidated. If the same request comes again with the same token, the server recognizes it as invalid and refuses the request, thereby preventing duplicate actions.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Generate a unique token for this action</span>
<span class="hljs-keyword">const</span> token = generateToken();

fetch(<span class="hljs-string">"https://api.example.com/create-user"</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ username, password }),
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-attr">Authorization</span>: <span class="hljs-string">`Bearer <span class="hljs-subst">${token}</span>`</span>,
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
    },
})
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
        <span class="hljs-comment">// Handle successful response</span>
        <span class="hljs-keyword">if</span> (response.ok) {
            <span class="hljs-comment">// Do something with the successful response</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// Handle non-successful response</span>
        }
    })
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
        <span class="hljs-comment">// Handle error</span>
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error occurred:"</span>, error);
    })
    .finally(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-comment">// Invalidate token after successful action or in case of an error</span>
        invalidateToken(token);
    });

<span class="hljs-comment">// Simple implementation for generating a token</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateToken</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.random().toString(<span class="hljs-number">36</span>).substr(<span class="hljs-number">2</span>);
}

<span class="hljs-comment">// Simple implementation for invalidating a token</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">invalidateToken</span>(<span class="hljs-params">token</span>) </span>{
    <span class="hljs-comment">// Add your logic to invalidate the token, e.g., remove it from storage</span>
}
</code></pre>
<p>Here's a breakdown of the code:</p>
<h4 id="heading-generating-a-unique-token">Generating a unique token:</h4>
<p><code>const token = generateToken()</code>: This line calls a function named <code>generateToken()</code> (which is assumed to be defined elsewhere) that generates a unique token string. This token will be used for authorization and idempotency.</p>
<h4 id="heading-sending-the-post-request">Sending the <code>POST</code> request:</h4>
<p><code>fetch("https://api.example.com/create-user", { ... })</code>: This line uses the fetch API to send a POST request to the API endpoint <code>https://api.example.com/create-user</code>. </p>
<p><code>method: "POST"</code>: This specifies the HTTP method as POST, indicating the intention to create a new user.</p>
<p><code>body: JSON.stringify({ username, password })</code>: This defines the request body with user details like username and password. The data is converted to JSON format before sending.</p>
<p><code>headers: { Authorization:Bearer ${token}}</code>: This sets the Authorization header in the request. The header value includes the generated token prefixed with "Bearer ".</p>
<h4 id="heading-handling-the-response">Handling the Response:</h4>
<p><code>.then(response =&gt; { ... })</code>: This block defines the code to execute if the request is successful. You would handle things like storing user information or redirecting the user upon successful user creation.</p>
<p><code>.catch(error =&gt; { ... }):</code> This block defines the code to execute if the request encounters an error. You would handle any error messages or handle specific error scenarios here.</p>
<h4 id="heading-invalidating-the-token">Invalidating the Token:</h4>
<p><code>invalidateToken(token)</code>: This line calls a function named <code>invalidateToken(token)</code> ( which is assumed to be defined elsewhere) which would likely mark the used token as invalid. This ensures the same token cannot be used for subsequent requests, adding to the idempotency guarantee.</p>
<h4 id="heading-how-does-this-implement-idempotence-1">How does this implement Idempotence?</h4>
<p>This code snippet uses token-based authorization to implement idempotency in a POST request to create a user on an API. If a user creation request is accidentally sent multiple times, a new unique token is generated each time and used in the Authorization header.</p>
<p>The API server can recognize and verify the unique token, and since the user creation action has already been performed (assuming it's successful the first time), it won't create duplicate users due to subsequent identical requests.</p>
<h3 id="heading-etag-header">ETag Header:</h3>
<p>An ETag header (Entity Tag) is an HTTP header used for web cache validation and conditional requests. It is mainly used for  PUT requests, that only update resources if they haven't changed since the last check.</p>
<p>When you want to update a resource, the server sends you its ETag which is then included in your PUT request along with the updated data. If the ETag hasn't changed (meaning the resource remains the same), the server accepts the update. But if the ETag has changed, the server rejects the update, preventing it from overwriting someone else's changes.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_article</span>(<span class="hljs-params">article_id, content</span>):</span>
    <span class="hljs-comment"># Get existing article and its ETag</span>
    article = Article.objects.get(pk=article_id)
    etag = article.etag

    <span class="hljs-comment"># Check if ETag matches with request header</span>
    <span class="hljs-keyword">if</span> request.headers.get(<span class="hljs-string">"If-Match"</span>) != etag:
        <span class="hljs-keyword">return</span> HttpResponse(status=<span class="hljs-number">409</span>)  <span class="hljs-comment"># Conflict</span>

    <span class="hljs-comment"># Update article content and generate new ETag</span>
    article.content = content
    article.save()
    new_etag = article.etag

    <span class="hljs-comment"># Return success response with updated ETag</span>
    <span class="hljs-keyword">return</span> HttpResponse(status=<span class="hljs-number">200</span>, content_type=<span class="hljs-string">"text/plain"</span>, content=new_etag)
</code></pre>
<p>In this code snippet, we define a function called <code>update_article</code> that allows you to update the content of an existing article based on its ID and new content. It implements idempotency using the ETag header technique.</p>
<p>Here's a step-by-step explanation of how it works;</p>
<h4 id="heading-getting-the-existing-article-and-its-etag">Getting the Existing Article and its ETag:</h4>
<p><code>article = Article.objects.get(pk=article_id):</code> This line fetches the article with the provided article_id from the database using the Article model.</p>
<p><code>etag = article.etag:</code> This line extracts the ETag value from the retrieved article object. The ETag serves as a unique identifier for the article's current state.</p>
<h4 id="heading-checking-for-a-match">Checking for a Match:</h4>
<p><code>if request.headers.get("If-Match") != etag:</code> This line checks if the ETag header provided in the request matches the ETag of the retrieved article.</p>
<p><code>return HttpResponse(status=409)</code>: If the ETag doesn't match, it indicates that the article might have been updated by another request since the client retrieved its information. The function returns a 409 Conflict response, which prevents accidental data corruption.</p>
<h4 id="heading-updating-the-article-content-and-generating-a-new-etag">Updating the Article Content and generating a new ETag:</h4>
<p><code>article.content = content:</code> This line updates the article's content with the new content received in the request.</p>
<p><code>article.save():</code> This line saves the updated article back to the database.</p>
<p><code>new_etag = article.etag:</code> This line retrieves the new ETag generated for the updated article after saving it.</p>
<h4 id="heading-returning-the-success-response-with-the-new-etag">Returning the Success Response with the new ETag:</h4>
<p><code>return HttpResponse(status=200, content_type="text/plain", content=new_etag)</code>: returns a successful 200 OK response, including the content type ("text/plain") and the updated ETag of the article in the response body.</p>
<h4 id="heading-how-does-this-implement-idempotence-2">How does this implement idempotence?</h4>
<p>This code ensures that if the same update request is sent multiple times with the same ETag, the update will only be performed once, preventing duplicate updates and maintaining data consistency. The new ETag is then provided in the response to help the client keep track of the article's state for future interactions.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we highlighted the difference between safe methods like GET, which retrieves data without side effects, and non-idempotent methods like POST, which can have different outcomes with each repetition. </p>
<p>We also explored techniques you can apply to achieve idempotence in non-idempotent methods, emphasizing the importance of designing APIs that prioritize consistency and reliability.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Call vs Put vs Post – HTTP Request Methods Explained ]]>
                </title>
                <description>
                    <![CDATA[ The HTTP (Hypertext Transfer Protocol) is the foundation of communication between clients (such as web browsers) and servers (such as web servers) on the World Wide Web. One crucial aspect of HTTP is the request method, which indicates the type of op... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/call-vs-put-vs-post-http-request-methods-explained/</link>
                <guid isPermaLink="false">66d45f67ffe6b1f641b5f9f9</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 13 Apr 2023 14:59:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/cover-template--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The HTTP (Hypertext Transfer Protocol) is the foundation of communication between clients (such as web browsers) and servers (such as web servers) on the World Wide Web.</p>
<p>One crucial aspect of HTTP is the request method, which indicates the type of operation the client wants to perform on a resource.</p>
<p>This article will explore three common HTTP request methods — Call, Put, and Post — and their applications in JavaScript web development.</p>
<h2 id="heading-how-http-works">How HTTP Works</h2>
<p>HTTP (Hypertext Transfer Protocol) is the foundation of communication on the World Wide Web. It is a protocol that governs how data is transmitted and received between clients (web browsers) and servers (web servers) over the internet.</p>
<p>When you enter a URL (Uniform Resource Locator) in your web browser and hit enter, your browser sends an HTTP request to the server hosting the website associated with that URL. The server then processes the request and sends back an HTTP response containing the requested data, such as a webpage, an image, or other resources.</p>
<p>HTTP uses a client-server model, where the client (typically a web browser) sends requests to the server, and the server responds with the requested data. One important aspect of HTTP is the concept of request methods, also known as HTTP verbs or methods.</p>
<p>Request methods are used to indicate the type of operation the client wants to perform on a resource on the server. HTTP defines several request methods, including Call, Put, Post, Delete, and more, each with its specific purpose and behavior.</p>
<p>These request methods are used to communicate the client's intention to the server and determine how the server should handle the request. Let's focus on three common request methods: Call, Put, and Post.</p>
<h2 id="heading-how-to-use-the-call-method">How to Use the Call Method</h2>
<p>In the context of an HTTP Request, the call method is called the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-get-request-tutorial/">GET method</a>. It is used to retrieve data from a resource on the server. When you make a Call request, you ask the server to provide you with the data of a particular resource.</p>
<p>The Call method is considered "safe" and "idempotent." This means it should not have any side effects on the server and can be repeated multiple times without changing the outcome. In other words, making the same Call request multiple times should not result in any changes on the server.</p>
<p>In JavaScript web development, you often use the Call method to fetch data from APIs or retrieve resources from the server.</p>
<p>For example, you may use the Fetch API in JavaScript to request a Call to an API and retrieve data in JSON format:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts?_limit=5"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Call request is made to the URL ‘https://jsonplaceholder.typicode.com/posts’ to fetch data from the server (<code>?_limit=5</code> is added to reduce the data fetched from 100 to 5). The response from the server is then parsed as JSON, and the retrieved data is logged to the console. You can now make use of the data within your application.</p>
<h2 id="heading-how-to-use-the-put-method">How to Use the Put Method</h2>
<p>The Put method is used to update data on the server or create a new resource if it does not already exist.</p>
<p>When you make a Put request, you ask the server to update the data of a particular resource or create a new resource with the provided data.</p>
<p>The Put method is considered "idempotent" but not "safe." This means that making the same Put request multiple times will not result in different outcomes but may have side effects on the server.</p>
<p>In JavaScript, you can use the Put method to send data to the server to update resources. For example, you may use the Fetch API to make a Put request with updated data to update a user's profile information on the server:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dataToUpdate = {
  <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>
};

fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"PUT"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(dataToUpdate)
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Put request is made to the URL ‘https://jsonplaceholder.typicode.com/posts/1’ with the updated data in the request body. The server will then update the resource's data with ID 1 based on the provided data in the request body.</p>
<p>The response from the server, containing the updated data, is then parsed as JSON and logged to the console.</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"title"</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-string">"body"</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-string">"userId"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<p><strong>Note:</strong> The PUT method is used to update data. The post of id 1 was updated.</p>
<h2 id="heading-how-to-use-the-post-method">How to Use the Post Method</h2>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-post-request-how-to-send-an-http-post-request-in-js/">POST method</a> is used to submit data to the server to create a new resource.</p>
<p>When you make a Post request, you ask the server to create a new resource with the data provided in the request body. The Post method is not considered "idempotent" or "safe," as making the same Post request multiple times may create multiple resources with different outcomes.</p>
<p>In JavaScript, you can use the Post method to send data to the server to create new resources. For example, you may use the Fetch API to make a Post request with new data to create a new user account on the server:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> newData = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>
};

fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(newData)
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>In this example, the Post request is made to the URL ‘https://jsonplaceholder.typicode.com/posts’ with the new data in the request body. The server will then create a new resource with the provided data, and the response from the server, containing the newly created resource data, is parsed as JSON and logged to the console.</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"title"</span>: <span class="hljs-string">"Hello freeCodeCamp"</span>,
  <span class="hljs-string">"body"</span>: <span class="hljs-string">"Welcome to freeCodeCamp"</span>,
  <span class="hljs-string">"userId"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"id"</span>: <span class="hljs-number">101</span>
}
</code></pre>
<p><strong>Note:</strong> A new <code>id</code> of 101 is created because this is new data that does not exist before, so a unique ID is assigned to it.</p>
<h2 id="heading-best-practices-and-considerations">Best Practices and Considerations</h2>
<ol>
<li><p><strong>Use appropriate request methods:</strong> It's important to choose the appropriate one based on the intended operation on the server-side resource. Use Call for custom actions or functions, Put for updating existing resources, and Post for creating new ones.</p>
</li>
<li><p><strong>Follow RESTful principles:</strong> If you're building a RESTful API, it's important to follow the principles of Representational State Transfer (REST), which includes using standard HTTP request methods for CRUD operations. Use Get for retrieving resource data, Put for updating, Post for creating new resources, and Delete for deleting resources.</p>
</li>
<li><p><strong>Consider idempotency and safety:</strong> Put requests are idempotent, meaning making the same request multiple times will have the same outcome as making it once. Post requests are not idempotent, and making the same request multiple times may create multiple resources with different outcomes. Consider your operation's idempotency and safety requirements when choosing the appropriate request method.</p>
</li>
</ol>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>HTTP is a crucial protocol that governs how data is transmitted and received between clients and servers on the World Wide Web. Request methods in HTTP, such as Call, Put, and Post, indicate the type of operation the client wants to perform on a resource on the server.</p>
<p>Understanding how these request methods work is essential in web development, as they determine how the server will handle the requests and what actions will be taken on the resources.</p>
<p>By utilizing the appropriate request methods in your web applications, you can effectively communicate with servers and manage resources reliably and efficiently.</p>
<p>Have fun coding!</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Search 'request' for a deep dive into POST, GET, and making HTTP requests with React and JavaScript. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is HTTP? Protocol Overview for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Without HTTP (Hypertext Transfer Protocol), the World Wide Web as we know it today would not exist. HTTP is the protocol that enables the transfer of data over the internet, allowing users to access websites and other online resources.   There are va... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-http/</link>
                <guid isPermaLink="false">66c17cd08c83c36e8b078726</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rufai Mustapha ]]>
                </dc:creator>
                <pubDate>Thu, 06 Apr 2023 16:53:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/http--5-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Without HTTP (Hypertext Transfer Protocol), the World Wide Web as we know it today would not exist. HTTP is the protocol that enables the transfer of data over the internet, allowing users to access websites and other online resources.  </p>
<p>There are various ways to design web applications, including GraphQL, SOAP, Falcor, gRPC, WebSockets, and Serverless Functions, with REST being the most popular (according to the <a target="_blank" href="https://www.postman.com/state-of-api/2021/">2021 State-of-API</a> survey by Postman). And at the heart of all these architectures is HTTP.</p>
<h2 id="heading-what-to-learn-along-with-http">What to Learn Along with HTTP</h2>
<p>To understand HTTP, it is helpful to have a basic understanding of the following concepts:</p>
<ol>
<li>Networking: Knowledge of how computers communicate with each other over networks is essential for understanding HTTP. This includes concepts such as IP addresses, DNS, and routing.</li>
<li>Web architecture: HTTP is a key part of web architecture, so understanding how web applications and websites are built can help you understand HTTP better. This includes concepts such as HTML, CSS, and JavaScript.</li>
<li>Server-side programming: HTTP is used to communicate between web browsers and servers, so understanding how servers work and how to build server-side applications can help you understand how HTTP works.</li>
<li>Client-side programming: HTTP is also used to communicate between web browsers and client-side applications, so understanding how to build client-side applications using JavaScript can also be helpful.</li>
</ol>
<h3 id="heading-what-to-expect-in-this-article">What to Expect in This Article</h3>
<ul>
<li>How the HTTP protocol works.</li>
<li>How to make network requests with Chrome and Postman.</li>
<li>How to upload data with the HTTP POST method in Postman.</li>
</ul>
<p>By the end of the article, readers should have a basic understanding of HTTP, as well as the tools and resources available for testing and troubleshooting applications.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-http">Introduction to HTTP</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-http-request-response-cycle">What is the HTTP Request-Response Cycle?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-http-requests">How to Create HTTP Requests</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-http-request-url">What is an HTTP Request URL?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-http-request-methods">What Are HTTP Request Methods?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-http-request-headers">What Are HTTP Request Headers?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-http-request-body">What is an HTTP Request Body?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-http-response">What is an HTTP Response?</a></li>
</ul>
<h2 id="heading-introduction-to-http">Introduction to HTTP</h2>
<p>HTTP (Hypertext Transfer Protocol) is a protocol used for exchanging information over the internet. HTTP is like the delivery system for information on the internet. It makes sure information goes from one place to another, like how ships carry goods across the ocean. It's the foundation of the World Wide Web.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/http-client-server.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>HTTP is what makes the internet work. It's a way for web browsers and servers to talk to each other and send things like web pages back and forth. It's important for people who build websites and web applications to know how it works.  </p>
<p>Without HTTP, it would be difficult to imagine how the internet would work. There would be no web pages, no URLs, and no hyperlinks. Instead, users would need to know the exact IP address of the server hosting the information they want to access, and they would need to use a low-level protocol like TCP/IP to transfer data.</p>
<h2 id="heading-what-is-the-http-request-response-cycle">What is the HTTP Request-Response Cycle?</h2>
<p>Communication in HTTP centers around a concept called the Request-Response Cycle. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/http-client-server-RR.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The request-response cycle is the process by which a client (such as a web browser or a mobile app) communicates with a server to retrieve resources or perform actions. The cycle involves several steps:</p>
<ol>
<li>The client initiates a request to the server by sending an HTTP request message, which contains information such as the requested resource and any additional parameters.</li>
<li>The server receives the request message and processes it, using its resources to generate a response message.</li>
<li>The server sends the response message back to the client, which typically contains the requested resource (such as a web page) and any additional information or metadata.</li>
<li>The client receives the response message and processes it, usually by rendering the content in a web browser or displaying it in an app.</li>
<li>The client may initiate additional requests to the server, repeating the cycle as needed.</li>
</ol>
<h2 id="heading-how-to-create-http-requests">How to Create HTTP Requests</h2>
<p>To create a valid HTTP request, you need the following:</p>
<ul>
<li>A URL.</li>
<li>The HTTP method.</li>
<li>A list of headers (request headers).</li>
<li>The request body.</li>
</ul>
<p>Here's an example of an HTTP request header, with three lines:</p>
<pre><code class="lang-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/watch?v=8PoQpnlBXD0</span> HTTP/1.1
<span class="hljs-attribute">Host</span>: www.youtube.com
<span class="hljs-attribute">Cookie</span>: GPS=1; VISITOR_INFO1_LIVE=kOe2UTUyPmw; YSC=Jt6s9YVWMd4
</code></pre>
<ol>
<li>The first line specifies the HTTP method, path, and protocol version. In this case, it is a <code>GET</code> request for the video located at the path <code>/watch?v=8PoQpnlBXD0</code> using the HTTP/1.1 protocol.</li>
<li>The second line specifies the host of the website, which is <a target="_blank" href="http://www.youtube.com/"><code>www.youtube.com</code></a>.</li>
<li>The third line contains a cookie header, which is used for sending and storing small pieces of data on the client side. In this case, the cookie header contains three values: <code>GPS=1, VISITOR_INFO1_LIVE=kOe2UTUyPmw</code>, and <code>YSC=Jt6s9YVWMd4</code>. These values can be used by YouTube to track and personalize the user's experience.</li>
</ol>
<h2 id="heading-what-is-an-http-request-url">What is an HTTP Request URL?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/url.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>When a web browser attempts to access an image on the internet, it sends a request to the server using a URL. This URL is <em>unique</em> and points to a specific <em>resource</em> on the server.  </p>
<p>A resource can be anything that has a name and can be accessed with a unique identifier like a user, product, article, document, or image. You can think of resources as <em>nouns</em>.</p>
<h2 id="heading-what-are-http-request-methods">What Are HTTP Request Methods?</h2>
<p>The request method tells the server what kind of action the client wants the server to take. The most common methods are:</p>
<table>
<thead>
<tr>
<th>HTTP Methods</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td>HEAD</td>
<td>Asks the server for status (size, availability)  of a resource.</td>
</tr>
<tr>
<td>GET</td>
<td>Asks the server to retrieve a resource.</td>
</tr>
<tr>
<td>POST</td>
<td>Asks the server to create a new resource.</td>
</tr>
<tr>
<td>PUT</td>
<td>Asks the server to edit/update an existing resource.</td>
</tr>
<tr>
<td>DELETE</td>
<td>Asks the server to delete a resource.</td>
</tr>
</tbody>
</table>

<h2 id="heading-what-are-http-request-headers">What Are HTTP Request Headers?</h2>
<p>HTTP request headers are additional pieces of information that are sent by the client as part of an HTTP request. They have a name/value format. That is:</p>
<pre><code class="lang-txt">Name: Value
</code></pre>
<p>These headers provide context and additional instructions to the server, which can be used to process the request or customize the response.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/hqQR1O2H_ck" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Here's an example of an HTTP request header:</p>
<pre><code class="lang-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/api/data</span> HTTP/1.1
<span class="hljs-attribute">Host</span>: example.com
<span class="hljs-attribute">User-Agent</span>: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36
<span class="hljs-attribute">Accept</span>: application/json
<span class="hljs-attribute">Accept-Language</span>: en-US,en;q=0.5
<span class="hljs-attribute">Authorization</span>: Token abc123
<span class="hljs-attribute">Cache-Control</span>: no-cache
<span class="hljs-attribute">Connection</span>: keep-alive
<span class="hljs-attribute">Referer</span>: https://www.google.com/
<span class="hljs-attribute">Pragma</span>: no-cache
</code></pre>
<p>In this example, the <code>GET</code> method is used to send a request to the <code>/api/data</code> endpoint on the <code>example.com</code> server using HTTP/1.1 protocol. The request includes ten headers:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Headers</td><td>Definition</td></tr>
</thead>
<tbody>
<tr>
<td>Host</td><td>This header specifies the hostname of the server that the client is trying to connect to.</td></tr>
<tr>
<td>User-Agent</td><td>This header provides information about the client that is making the request (in this case, a version of the Chrome browser).</td></tr>
<tr>
<td>Accept</td><td>This header specifies the MIME types of data that the client is willing to accept in the response.</td></tr>
<tr>
<td>Accept-Language</td><td>This header specifies the preferred language(s) for the response.</td></tr>
<tr>
<td>Authorization</td><td>This header provides an access token (in this case, Token abc123) for authentication purposes.</td></tr>
<tr>
<td>Cache-Control</td><td>This header specifies caching directives for both requests and responses.</td></tr>
<tr>
<td>Connection</td><td>This header specifies options for the connection handling between client and server.</td></tr>
<tr>
<td>Referer</td><td>This header specifies the URL of the page that linked to the current page.</td></tr>
<tr>
<td>Pragma</td><td>This header specifies implementation-specific directives that might apply to any agent along the request-response chain.</td></tr>
<tr>
<td>Content-Type</td><td>This header specifies the MIME type of the data that is being sent in the body of the request, but it is not used in this example because this is a GET request without a request body.</td></tr>
</tbody>
</table>
</div><div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Pjok-1Q6MOs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-what-is-an-http-request-body">What is an HTTP Request Body?</h2>
<p>In HTTP, the request body is the data that is sent from the client to the server as part of an HTTP request. The example below shows how to upload an image to the <a target="_blank" href="https://documenter.getpostman.com/view/5578104/RWgqUxxh#5a07d324-155b-487e-80a5-b1b9c1775339">Cat API Server</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/zAVCD0nLnjg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>And here's what the request looks like:</p>
<pre><code class="lang-http"><span class="hljs-keyword">POST</span> <span class="hljs-string">/v1/images/upload</span> HTTP/1.1
<span class="hljs-attribute">Host</span>: api.thecatapi.com
<span class="hljs-attribute">x-api-key</span>: API_KEY
<span class="hljs-attribute">Content-Length</span>: 232
<span class="hljs-attribute">Content-Type</span>: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

<span class="solidity"><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW
Content<span class="hljs-operator">-</span>Disposition: form<span class="hljs-operator">-</span>data; name<span class="hljs-operator">=</span><span class="hljs-string">"file"</span>; filename<span class="hljs-operator">=</span><span class="hljs-string">"/C:/Users/USER/Downloads/cat1.jpg"</span>
Content<span class="hljs-operator">-</span>Type: image<span class="hljs-operator">/</span>jpeg

(data)
<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW<span class="hljs-operator">-</span><span class="hljs-operator">-</span></span>
</code></pre>
<p>The request includes these headers:</p>
<ol>
<li><code>Host</code>: This header specifies the hostname of the server that the client is trying to connect to.</li>
<li><code>Content-Type</code>: The request is uploading an image file named <code>cat1.jpg</code> using a type of data called <code>multipart/form-data</code>. The image is in JPEG format and its content is included in the request body.</li>
<li><code>x-api-key</code>: This header provides an API key for authentication purposes.</li>
<li><code>Content-Length</code>: This header specifies the length of the request body in bytes. The value of this field is 232.</li>
</ol>
<p>When the server receives this request, it will parse the request body and use it to create a new entry in the Cat API database. The server will then return a response that includes information about the new entry, such as the image URL and the database ID.</p>
<h2 id="heading-what-is-an-http-response">What is an HTTP Response?</h2>
<p>An HTTP response is the message that a server sends back to a client in response to an HTTP request. It usually consists of a status line, headers, and a message body:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">200</span> OK
<span class="hljs-attribute">Date</span>: Sun, 28 Mar 2023 10:15:00 GMT
<span class="hljs-attribute">Content-Type</span>: application/json
<span class="hljs-attribute">Server</span>: Apache/2.4.39 (Unix) OpenSSL/1.1.1c PHP/7.3.6
<span class="hljs-attribute">Content-Length</span>: 1024

<span class="json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"johndoe@example.com"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-attr">"address"</span>: {
        <span class="hljs-attr">"street"</span>: <span class="hljs-string">"123 Main St"</span>,
        <span class="hljs-attr">"city"</span>: <span class="hljs-string">"Anytown"</span>,
        <span class="hljs-attr">"state"</span>: <span class="hljs-string">"CA"</span>,
        <span class="hljs-attr">"zip"</span>: <span class="hljs-string">"12345"</span>
    }
}</span>
</code></pre>
<p>The status line contains the HTTP version, a status code indicating the outcome of the request, and a corresponding message.</p>
<p>The headers provide additional information about the response, such as the content type of the message body or the date and time that the response was sent.</p>
<p>The message body contains the actual response data, such as HTML, JSON, or XML content.</p>
<p>Some common HTTP status codes include:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Code</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td>100</td><td>Continue</td></tr>
<tr>
<td>101</td><td>Switching Protocols</td></tr>
<tr>
<td>200</td><td>OK</td></tr>
<tr>
<td>201</td><td>Created</td></tr>
<tr>
<td>202</td><td>Accepted</td></tr>
<tr>
<td>203</td><td>Non-Authoritative Information</td></tr>
<tr>
<td>404</td><td>Not Found : The requested resource was not found on the server.</td></tr>
<tr>
<td>500</td><td>Internal Server Error : The server encountered an error while processing the request.</td></tr>
<tr>
<td>301</td><td>Moved Permanently: The requested resource has been permanently moved to a new URL.</td></tr>
</tbody>
</table>
</div><p>Here's an example of a JSON response from the Cat API:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"id"</span>: <span class="hljs-string">"ErDd1JRRT"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://cdn2.thecatapi.com/images/ErDd1JRRT.jpg"</span>,
    <span class="hljs-attr">"width"</span>: <span class="hljs-number">4282</span>,
    <span class="hljs-attr">"height"</span>: <span class="hljs-number">6424</span>,
    <span class="hljs-attr">"original_filename"</span>: <span class="hljs-string">"cat1.jpg"</span>,
    <span class="hljs-attr">"pending"</span>: <span class="hljs-number">0</span>,
    <span class="hljs-attr">"approved"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<p>This is a JSON response from a Cat API request that appears to provide metadata about an image that has been uploaded or retrieved from the API. Here's what each field means:</p>
<ul>
<li><code>id</code>: A unique identifier for the image.</li>
<li><code>url</code>: The URL where the image can be accessed.</li>
<li><code>width</code>: The width of the image in pixels.</li>
<li><code>height</code>: The height of the image in pixels.</li>
<li><code>original_filename</code>: The original name of the file that was uploaded.</li>
<li><code>pending</code>: A flag indicating whether the image is still being processed by the API.</li>
<li><code>approved</code>: A flag indicating whether the image has been approved for public use by the API.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>HTTP (Hypertext Transfer Protocol) is a protocol used for exchanging information over the internet. It forms the foundation of the World Wide Web and allows communication between web browsers and servers.   </p>
<p>This article is a short introduction to HTTP. If you are interested in learning more, check out these textbook recommendations:</p>
<ul>
<li>"HTTP: The Definitive Guide" by David Gourley and Brian Totty - This book is widely regarded as the authoritative guide to HTTP. It covers the protocol in-depth and provides detailed information on its features and implementation.</li>
<li>"HTTP Pocket Reference" by Clinton Wong - This book provides a concise and portable reference to the HTTP protocol. It covers the essentials of the protocol and is a great resource for developers who need quick access to HTTP information.</li>
<li>"Web Performance Daybook Volume 2: Techniques and Tips for Optimizing Web Site Performance" edited by Stoyan Stefanov - This book is a collection of essays and articles on web performance, including a section on HTTP optimization. It provides practical advice on how to optimize HTTP for faster and more efficient web performance.</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTTP Networking in JavaScript – Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ HTTP is the backbone of the modern internet. In this text-based course, you'll learn how the HTTP protocol works and how it's used in real-world web development. All the code samples for this course are in JavaScript, but the networking concepts you'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/http-full-course/</link>
                <guid isPermaLink="false">66b9e9ec39e4436f19005afa</guid>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Lane Wagner ]]>
                </dc:creator>
                <pubDate>Tue, 14 Feb 2023 00:42:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738338854008/9272a213-f1ed-40d0-8d33-f57a11b3756c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTTP is the backbone of the modern internet. In this text-based course, you'll learn how the HTTP protocol works and how it's used in real-world web development.</p>
<p>All the code samples for this course are in JavaScript, but the networking concepts you'll learn here apply generally to all coding languages. <em>If you're not familiar with JavaScript yet, you can check out</em> <a target="_blank" href="https://boot.dev/learn/learn-javascript"><em>my JS course here</em></a><em>.</em></p>
<p>I've included all the learning material you'll need here in this article, but if you would like a more hands-on experience, you can take the <a target="_blank" href="https://boot.dev/learn/learn-http">interactive version of this course with coding challenges on Boot.dev here.</a></p>
<p>I've also published a free video version of this course on the freeCodeCamp YouTube channel:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2JYT5f2isg4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>If you like this video, you can check out my other tutorials on my <a target="_blank" href="https://youtube.com/@bootdotdev">Boot.dev YouTube channel here</a>.</p>
<p>All that said, let's jump into learning about HTTP!</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-why-http">Why HTTP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#What-is-dns">What is DNS?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-uris">What Are URIs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-4-async-await">Async/Await</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling">Error Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-http-headers">HTTP Headers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-json">What is JSON?</a></p>
</li>
<li><p><a class="post-section-overview" href="#chapter-8-http-methods">HTTP Methods</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-url-paths-and-parameters">URL Paths and Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-https">What is HTTPs?</a></p>
</li>
</ol>
<h2 id="heading-why-http">Why HTTP?</h2>
<h3 id="heading-communicating-on-the-web">Communicating on the web</h3>
<p>Instagram would be pretty terrible if you had to manually copy your photos to your friend's phone when you wanted to share them. Modern applications need to be able to communicate information <em>between devices</em> over the internet.</p>
<ul>
<li><p>Gmail doesn't just store your emails in variables on your computer, it stores them on computers in their data centers.</p>
</li>
<li><p>You don't lose your Slack messages if you drop your computer in a lake – those messages exist on Slack's <a target="_blank" href="https://en.wikipedia.org/wiki/Web_server">servers</a>.</p>
</li>
</ul>
<h3 id="heading-how-does-web-communication-work">How does web communication work?</h3>
<p>When two computers communicate with each other, they need to use the same rules. An English speaker can't communicate verbally with a Japanese speaker, and similarly, two computers need to speak the same language to communicate.</p>
<p>This "language" that computers use is called a <a target="_blank" href="https://en.wikipedia.org/wiki/Communication_protocol">protocol</a>. The most popular protocol for web communication is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview">HTTP</a>, which stands for Hypertext Transfer Protocol.</p>
<h3 id="heading-interacting-with-a-server">Interacting with a server</h3>
<p>In this course, a lot of the code samples will interact with the <a target="_blank" href="https://pokeapi.co/">PokeAPI</a>. It serves data about Pokémon.</p>
<p>Here's some code that retrieves a list of Pokémon from the PokeAPI:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pokemonResp = <span class="hljs-keyword">await</span> getItemData()

logPokemons(pokemonResp.results)

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getItemData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    }
  })
  <span class="hljs-keyword">return</span> response.json()
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logPokemons</span>(<span class="hljs-params">pokemons</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pokemon <span class="hljs-keyword">of</span> pokemons) {
    <span class="hljs-built_in">console</span>.log(pokemon.name)
  } 
}
</code></pre>
<p>When you run this code, you'll notice that none of the data that is logged to the console was generated within our code! That's because the data we retrieved is being sent over the internet from our servers via HTTP. Don't worry, we'll explain more about that later.</p>
<h3 id="heading-http-requests-and-responses">HTTP Requests and Responses</h3>
<p>At the heart of HTTP is a simple request-response system. The "requesting" computer, also known as the "<a target="_blank" href="https://en.wikipedia.org/wiki/Client_\(computing\)">client</a>", asks another computer for some information. That computer, the "<a target="_blank" href="https://en.wikipedia.org/wiki/Server_\(computing\)">server</a>" sends back a response with the information that was requested.</p>
<p><img src="https://i.imgur.com/ReFw6nN.png" alt="Image" width="925" height="297" loading="lazy"></p>
<p>We'll talk about the specifics of how the "requests" and "responses" are formatted later. For now, just think of it as a simple question-and-answer system.</p>
<ul>
<li><p>Request: "What are the items in the Fantasy Quest game?"</p>
</li>
<li><p>Response: A list of the items in the Fantasy Quest game</p>
</li>
</ul>
<h3 id="heading-http-powers-websites">HTTP powers websites</h3>
<p>As we discussed, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview">HTTP</a>, or Hypertext Transfer Protocol, is a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Protocol">protocol</a> designed to transfer information between computers.</p>
<p>There are other protocols for communicating over the internet, but HTTP is the most popular and is <em>particularly great for websites and web applications</em>.</p>
<p>Each time you visit a website, your browser is making an HTTP request to that website's server. The server responds with all the text, images, and styling information that your browser needs to render its pretty website.</p>
<p><img src="https://i.imgur.com/EflKJzq.jpg" alt="Image" width="1080" height="1080" loading="lazy"></p>
<h3 id="heading-http-urls">HTTP URLs</h3>
<p>A URL, or <a target="_blank" href="https://www.freecodecamp.org/news/url-definition/">Uniform Resource Locator</a>, is essentially the address of another computer, or "server" on the internet. Part of the URL specifies how to reach the server, and part of it tells the server what information we want - but more on that later.</p>
<p>For now, it's important to understand that a URL represents a piece of information on another computer that we want access to. We can get access to it by making a <em>request</em>, and reading the <em>response</em> that the server replies with.</p>
<h3 id="heading-how-to-use-urls-in-http">How to Use URLs in HTTP</h3>
<p>The <code>http://</code> at the beginning of a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL">website URL</a> specifies that the <code>http</code> protocol will be used for communication.</p>
<p><img src="https://i.imgur.com/6jiaXBn.png" alt="Image" width="368" height="137" loading="lazy"></p>
<p>Other communication protocols use URLs as well, (hence "Uniform Resource Locator"). That's why we need to be specific when we're making HTTP requests by prefixing the URL with <code>http://</code></p>
<h3 id="heading-requests-and-responses-review">Requests and Responses Review</h3>
<ul>
<li><p>A "client" is a computer making an HTTP request</p>
</li>
<li><p>A "server" is a computer responding to an HTTP request</p>
</li>
<li><p>A computer can be a client, a server, both, or neither. "Client" and "server" are just words we use to describe what computers are doing within a communication system.</p>
</li>
<li><p>Clients send requests and receive responses</p>
</li>
<li><p>Servers receive requests and send responses</p>
</li>
</ul>
<h2 id="heading-javascripts-fetch-api">JavaScript's Fetch API</h2>
<p>In this course, we'll be using JavaScript's built-in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch API</a> to make HTTP requests.</p>
<p>The <code>fetch()</code> function is made available to us by the JavaScript language running in the browser. All we have to do is provide it with the parameters it requires.</p>
<h3 id="heading-how-to-use-fetch"><strong>How to Use Fetch</strong></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, settings)
<span class="hljs-keyword">const</span> responseData = <span class="hljs-keyword">await</span> response.json()
</code></pre>
<p>We'll go in-depth on the various things happening in this standard <code>fetch</code> call later, but let's cover some basics for now.</p>
<ul>
<li><p><code>response</code> is the data that comes back from the server</p>
</li>
<li><p><code>url</code> is the URL we are making a request to</p>
</li>
<li><p><code>settings</code> is an object containing some request-specific settings</p>
</li>
<li><p>The <code>await</code> keyword tells JavaScript to wait until the request comes back from the server before continuing</p>
</li>
<li><p><code>response.json()</code> converts the response data from the server into a JavaScript object</p>
</li>
</ul>
<p>See if you can spot the issue with this code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pokemonResp = getItemData()

logPokemons(pokemonResp.results)

<span class="hljs-comment">// the bug is above this line</span>

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getItemData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://pokeapi.co/api/v2/pokemon/'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
    }
  })
  <span class="hljs-keyword">return</span> response.json()
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logPokemons</span>(<span class="hljs-params">pokemons</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pokemon <span class="hljs-keyword">of</span> pokemons) {
    <span class="hljs-built_in">console</span>.log(pokemon.name)
  } 
}
</code></pre>
<p>Hint: We're not waiting for the data to be sent back across the network.</p>
<h3 id="heading-web-clients">Web Clients</h3>
<p>A web client is a device making requests to a web server. A client can be any type of device but is often something users physically interact with. For example:</p>
<ul>
<li><p>A desktop computer</p>
</li>
<li><p>A mobile phone</p>
</li>
<li><p>A tablet</p>
</li>
</ul>
<p>In a website or web application, we call the user's device the "front-end".<br>A front-end client makes requests to a back-end server.</p>
<p><img src="https://i.imgur.com/zldXGet.jpg" alt="Image" width="1920" height="1080" loading="lazy"></p>
<h3 id="heading-web-servers">Web Servers</h3>
<p>Up to this point, most of the data you have worked with in your code has simply been generated and stored locally in variables.</p>
<p>While you'll always use variables to store and manipulate data while your program is running, most websites and apps use a web server to store, sort, and serve that data so that it sticks around for longer than a single session, and can be accessed by multiple devices.</p>
<h3 id="heading-listening-and-serving-data"><strong>Listening and serving data</strong></h3>
<p>Similar to how a server at a restaurant brings your food to the table, a <a target="_blank" href="https://en.wikipedia.org/wiki/Web_server">web server</a>) serves web resources, such as web pages, images, and other data. The server is turned on and "listening" for inbound requests constantly so that the second it receives a new request, it can send an appropriate response.</p>
<h3 id="heading-the-server-is-the-back-end">The server is the back-end</h3>
<p>While the "front-end" of a website or web application is the device the user interacts with, the "back-end" is the server that keeps all the data housed in a central location. If you're still confused, <a target="_blank" href="https://blog.boot.dev/backend/frontend-vs-backend-meaning/">check out this article comparing front-end and back-end development</a>.</p>
<h3 id="heading-a-server-is-just-a-computer">A server is just a computer</h3>
<p>"Server" is just the name we give to a computer that is taking on the role of serving data across a network connection.</p>
<p>A good server is turned on and available 24 hours a day, 7 days a week. While your laptop <em>can</em> be used as a server, it makes more sense to use a computer in a data center that's designed to be up and running constantly.</p>
<h2 id="heading-what-is-dns">What is DNS?</h2>
<h3 id="heading-web-addresses">Web Addresses</h3>
<p>In the real world, we use addresses to help us find where a friend lives, where a business is located, or where a party is being thrown.</p>
<p>In computing, web clients find other computers over the internet using <a target="_blank" href="https://en.wikipedia.org/wiki/Internet_Protocol">Internet Protocol or IP</a> addresses.</p>
<p>An IP address is a numerical label that serves two main functions:</p>
<ol>
<li><p>Location Addressing</p>
</li>
<li><p>Network Identification</p>
</li>
</ol>
<h3 id="heading-domain-names-and-ip-addresses">Domain names and IP Addresses</h3>
<p>Each device connected to the internet has a unique IP address. When we browse the internet, the domains we navigate to are all associated with a particular IP address.</p>
<p>For example, this Wikipedia URL points to a page about miniature pigs: <code>https://en.wikipedia.org/wiki/Miniature_pig</code><br>The <a target="_blank" href="https://en.wikipedia.org/wiki/Domain_Name_System">domain</a> portion of the URL is <code>en.wikipedia.org</code>. <code>en.wikipedia.org</code> converts to a specific IP address, and that IP address tells your computer exactly where to communicate with that Wikipedia page.</p>
<p>Cloudflare is a tech company that provides a cool public HTTP server that we can use to look up the IP address of any domain. Take a look at this sample code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchIPAddress</span>(<span class="hljs-params">domain</span>) </span>{
  <span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://cloudflare-dns.com/dns-query?name=<span class="hljs-subst">${domain}</span>&amp;type=A`</span>, {
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'accept'</span>: <span class="hljs-string">'application/dns-json'</span>
    }
  })
  <span class="hljs-keyword">const</span> respObject = <span class="hljs-keyword">await</span> resp.json()
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> record <span class="hljs-keyword">of</span> respObject.Answer) {
    <span class="hljs-keyword">return</span> record.data
  }
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}

<span class="hljs-keyword">const</span> domain = <span class="hljs-string">'api.boot.dev'</span>
<span class="hljs-keyword">const</span> ipAddress = <span class="hljs-keyword">await</span> fetchIPAddress(domain)
<span class="hljs-keyword">if</span> (!ipAddress) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'something went wrong in fetchIPAddress'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`found IP address for domain <span class="hljs-subst">${domain}</span>: <span class="hljs-subst">${ipAddress}</span>`</span>)
}
</code></pre>
<p>To recap, a "domain name" is part of a URL. It's the part that tells the computer <em>where the server is located on the internet</em> by being converted into a numerical IP address.</p>
<p>We'll cover exactly how an IP address is used by your computer to find a path to the server in a later networking course. For now, it's just important to understand that an IP address is what your computer is using at a lower level to communicate on a network.</p>
<p>Deploying a real website to the internet is actually quite simple. It involves only a couple of steps:</p>
<ol>
<li><p>Create a server that hosts your website files and connect it to the internet</p>
</li>
<li><p>Acquire a domain name</p>
</li>
<li><p>Connect the domain name to the IP address of your server</p>
</li>
<li><p>Your server is accessible via the internet!</p>
</li>
</ol>
<p><img src="https://i.imgur.com/vjjPt2a.png" alt="Image" width="310" height="163" loading="lazy"></p>
<p>As we discussed, the "domain name" or "hostname" is part of a URL. We'll get to the other parts of a URL later.</p>
<p>For example, the URL <code>https://example.com/path</code> has a hostname of <code>example.com</code>. The <code>https://</code> and <code>/path</code> portions are not part of the <code>domain name -&gt; IP address</code> mapping that we've been learning about.</p>
<h3 id="heading-using-the-url-api-in-javascript">Using the URL API in JavaScript</h3>
<p>The <code>URL</code> API is built into JavaScript. You can create a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL">new URL object</a> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> urlObj = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">'https://example.com/example-path'</span>)
</code></pre>
<p>And then you can <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL">extract just the hostname</a>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> urlObj.hostname
</code></pre>
<h3 id="heading-dns-review">DNS Review</h3>
<p>So we've talked about domain names and what their purpose is, but we haven't talked about the system that's used to do that conversion.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-dns/">DNS</a>, or the "Domain Name System", is the phonebook of the internet. Humans connect to websites through <a target="_blank" href="https://en.wikipedia.org/wiki/Domain_name">domain names</a>, like <a target="_blank" href="https://boot.dev">Boot.dev</a>.</p>
<p>DNS "resolves" these domain names to find the associated <a target="_blank" href="https://en.wikipedia.org/wiki/Internet_Protocol">IP addresses</a> so that web clients can load the resources for the specific address.</p>
<p><img src="https://i.imgur.com/yvfSbVL.png" alt="Image" width="1024" height="512" loading="lazy"></p>
<h3 id="heading-how-does-dns-work">How does DNS Work?</h3>
<p>We'll go into more detail on DNS in a future course, but to give you a simplified idea of how it works, let's introduce ICANN. <a target="_blank" href="https://www.icann.org/">ICANN</a> is a not-for-profit organization that manages DNS for the entire internet.</p>
<p>Whenever your computer attempts to resolve a domain name, it contacts one of ICANN's "<a target="_blank" href="https://en.wikipedia.org/wiki/Root_name_server">root nameservers</a>" whose address is included in your computer's networking configuration.</p>
<p>From there, that nameserver can gather the domain records for a specific domain name from their distributed DNS database.</p>
<p>If you think of DNS as a phonebook, ICANN is the publisher that keeps the phonebook in print and available.</p>
<h3 id="heading-subdomains">Subdomains</h3>
<p>We learned about how a domain name resolves to an IP address, which is just a computer on a network - often the internet.</p>
<p>A subdomain prefixes a domain name, allowing a domain to route network traffic to many different servers and resources.</p>
<p>For example, the <a target="_blank" href="https://boot.dev">Boot.dev</a> website is hosted on a different computer than our blog. Our blog, found at <a target="_blank" href="https://blog.boot.dev">blog.boot.dev</a> is hosted on our "blog" subdomain.</p>
<h2 id="heading-what-are-uris">What are URIs?</h2>
<p>We briefly touched on URLs earlier, but now let's dive a little deeper into the subject.</p>
<p>A <a target="_blank" href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier">URI</a>, or Uniform Resource <em>Identifier</em>, is a unique character sequence that identifies a resource that is (almost always) accessed via the internet.</p>
<p>Just like JavaScript has syntax rules, so do URIs. These rules help ensure uniformity so that any program can interpret the meaning of the URI in the same way.</p>
<p>URIs come in two main types:</p>
<ul>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/URL">URLs</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Uniform_Resource_Name">URNs</a></p>
</li>
</ul>
<p>We will focus specifically on URLs in this course, but it's important to know that URLs are only one kind of URI.</p>
<p><img src="https://i.imgur.com/VzqzckC.png" alt="Image" width="500" height="394" loading="lazy"></p>
<p>URLs have quite a few sections, some of which are required, others not.<br>Let's use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/URL/URL">URL API</a> to parse a URL and print all the different parts. We'll learn more about each part later, for now, let's just split and print a URL.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printURLParts</span>(<span class="hljs-params">urlString</span>) </span>{
  <span class="hljs-keyword">const</span> urlObj = <span class="hljs-keyword">new</span> URL(urlString)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`protocol: <span class="hljs-subst">${urlObj.protocol}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`username: <span class="hljs-subst">${urlObj.username}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`password: <span class="hljs-subst">${urlObj.password}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`hostname: <span class="hljs-subst">${urlObj.hostname}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`port: <span class="hljs-subst">${urlObj.port}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`pathname: <span class="hljs-subst">${urlObj.pathname}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`search: <span class="hljs-subst">${urlObj.search}</span>`</span>)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`hash: <span class="hljs-subst">${urlObj.hash}</span>`</span>)
}

<span class="hljs-keyword">const</span> fantasyQuestURL = <span class="hljs-string">'http://dragonslayer:pwn3d@fantasyquest.com:8080/maps?sort=rank#id'</span>
printURLParts(fantasyQuestURL)
</code></pre>
<h3 id="heading-further-dissecting-a-url">Further dissecting a URL</h3>
<p>There are 8 main parts to a URL, though not all the sections are always present. Each piece plays a specific role in helping clients locate the specified resource.<br>The 8 sections are:</p>
<p><img src="https://i.imgur.com/iI3sUVh.png" alt="Image" width="1280" height="720" loading="lazy"></p>
<ul>
<li><p>The protocol is required</p>
</li>
<li><p>Usernames and passwords are optional</p>
</li>
<li><p>A domain is required</p>
</li>
<li><p>The default port for a given protocol is used if one is not provided</p>
</li>
<li><p>The default ( <code>/</code> ) path is used if one isn't provided</p>
</li>
<li><p>A query is optional</p>
</li>
<li><p>A fragment is optional</p>
</li>
</ul>
<h3 id="heading-dont-get-too-hung-up-on-memorizing-this-stuff">Don't get too hung up on memorizing this stuff</h3>
<p>Because names for the different sections are often used interchangeably, and because not all the parts of the URL are always present, it can be hard to keep things straight.</p>
<p>Don't worry about memorizing this stuff! Try to just get familiar with these URL concepts from a high level. Like any good developer, you can just look it up again the next time you need to know more.</p>
<h3 id="heading-the-protocol">The Protocol</h3>
<p>The "protocol", also referred to as the "scheme", is the first component of a URL. Its purpose is to define the rules by which the data being communicated is displayed, encoded, or formatted.</p>
<p>Some examples of different URL protocols:</p>
<ul>
<li><p>http</p>
</li>
<li><p>ftp</p>
</li>
<li><p>mailto</p>
</li>
<li><p>https</p>
</li>
</ul>
<p>For example:</p>
<ul>
<li><p><code>http://example.com</code></p>
</li>
<li><p><code>mailto:noreply@fantasyquest.app</code></p>
</li>
</ul>
<h3 id="heading-not-all-schemes-require-a">Not all schemes require a "//"</h3>
<p>The "http" in a URL is always followed by <code>://</code>. All URLs have the colon, but the <code>//</code> part is only included for schemes that have an <a target="_blank" href="https://www.rfc-editor.org/rfc/rfc3986#section-3.2">authority component</a>.</p>
<p>As you can see above, the <code>mailto</code> scheme doesn't use an authority component, so it doesn't need the slashes.</p>
<h3 id="heading-url-ports">URL Ports</h3>
<p>The port in a URL is a virtual point where network connections are made. Ports are managed by a computer's operating system and are numbered from <code>0</code> to <code>65,535</code>.</p>
<p>Whenever you connect to another computer over a network, you're connecting to a specific port on that computer, which is being listened to by a specific piece of software on that computer. A port can only be used by one program at a time, which is why there are so many possible ports.</p>
<p>The port component of a URL is often not visible when browsing normal sites on the internet, because 99% of the time you're using the default ports for the HTTP and HTTPS schemes: <code>80</code> and <code>443</code>, respectively.</p>
<p>Whenever you aren't using a default port, you need to specify it in the URL. For example, port <code>8080</code> is often used by web developers when they're running their server in "test mode" so that they don't use the "production" port "80".</p>
<p><img src="https://i.imgur.com/h3kBsRC.png" alt="Image" width="625" height="129" loading="lazy"></p>
<h3 id="heading-url-paths">URL Paths</h3>
<p>In the early days of the internet, a URL's path often was a reflection of the file path on the server to the resource the client was requesting.</p>
<p>For example, if the website <code>https://exampleblog.com</code> had a web server running within its <code>/home</code> directory, then a request to the <code>https://exampleblog.com/site/index.html</code> URL might expect the <code>index.html</code> file from within the <code>/home/site</code> directory to be returned.</p>
<p>Websites used to be very simple. They were just a collection of text documents stored on a server. A simple piece of server software could handle incoming HTTP requests and respond with the documents according to the path component of the URLs.</p>
<h3 id="heading-these-days-its-not-always-about-the-filesystem">These days, it's not always about the filesystem</h3>
<p>On many modern web servers, a URL's path isn't a reflection of the server's filesystem hierarchy. Paths in URLs are essentially just another type of parameter that can be passed to the server when making a request.</p>
<p>Conventionally, two different URL paths should denote different resources. For example, different pages on a website, or maybe different data types from a game server.</p>
<h3 id="heading-query-parameters">Query parameters</h3>
<p>Query parameters in a URL are <em>not</em> always present. In the context of websites, query parameters are often used for marketing analytics or for changing a variable on the web page. With website URLs, query parameters <em>rarely</em> change <em>which</em> page you're viewing, though they often will change the page's <em>contents</em>.</p>
<p>That said, query parameters can be used for anything the server chooses to use them for, just like the URL's path.</p>
<h3 id="heading-how-google-uses-query-parameters">How Google uses query parameters</h3>
<ol>
<li><p>Open a new tab and go to <a target="_blank" href="https://google.com">google.com</a></p>
</li>
<li><p>Search for "hello world"</p>
</li>
<li><p>Take a look at your current URL. It should start with <code>https://www.google.com/search?q=hello+world</code></p>
</li>
<li><p>Change the URL to say <code>https://www.google.com/search?q=hello+universe</code></p>
</li>
<li><p>Press "enter"</p>
</li>
</ol>
<p>You should see new search results for the query "hello universe". Google chose to use query parameters to represent the value of your search query. It makes sense - each search result page is <em>essentially</em> the same page as far as structure and formatting are concerned - it's just showing you different results based on the search query.</p>
<h2 id="heading-asyncawait">Async/Await</h2>
<p>You're probably already familiar with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Synchronous">synchronous</a> code, which means code that <em>runs in sequence</em>. Each line of code executes in order, one after the next.</p>
<p><img src="https://i.imgur.com/03FFGu0.png" alt="Image" width="587" height="335" loading="lazy"></p>
<p>Example of synchronous code:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print first"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print second"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print third"</span>);
</code></pre>
<p>Asynchronous or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous">async</a> code runs in <em>parallel</em>. That means code further down runs <em>at the same time that</em> a previous line of code is still running. A good way to visualize this is with the JavaScript function <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeout()</a>.</p>
<p><code>setTimeout</code> accepts a function and a number of milliseconds as inputs. It waits until the number of milliseconds has elapsed, and then it executes the function it was given.</p>
<p>Example of asynchronous code:</p>
<pre><code class="lang-js">jsconsole.log(<span class="hljs-string">"I print first"</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print third because I'm waiting 100 milliseconds"</span>), <span class="hljs-number">100</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I print second"</span>);
</code></pre>
<p>Try altering the waiting times in the async code below to get the messages to print in the proper order:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> craftingCompleteWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> combiningMaterialsWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> smeltingIronBarsWait = <span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> shapingIronWait = <span class="hljs-number">0</span>

<span class="hljs-comment">// Don't touch below this line</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Iron Longsword Complete!'</span>), craftingCompleteWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Combining Materials...'</span>), combiningMaterialsWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Smelting Iron Bars...'</span>), smeltingIronBarsWait)
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Shaping Iron...'</span>), shapingIronWait)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Firing up the forge...'</span>)

<span class="hljs-keyword">await</span> sleep(<span class="hljs-number">2500</span>)
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">ms</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, ms))
}
</code></pre>
<p>Expected order:</p>
<ol>
<li><p>Firing up the forge..</p>
</li>
<li><p>Smelting Iron Bars...</p>
</li>
<li><p>Combining Materials...</p>
</li>
<li><p>Shaping Iron...</p>
</li>
<li><p>Iron Longsword Complete!</p>
</li>
</ol>
<h3 id="heading-why-do-we-want-async-code">Why do we want async code?</h3>
<p>We try to keep most of our code synchronous because it's easier to understand, and therefore often has fewer bugs. But sometimes we <em>need</em> our code to be asynchronous.</p>
<p>For example, whenever you update your user settings on a website, your browser will need to communicate those new settings to the server. The time it takes your HTTP request to physically travel across all the wiring of the internet is usually around 100 milliseconds. It would be a very poor experience if your webpage were to freeze while waiting for the network request to finish. You wouldn't even be able to move the mouse while waiting!</p>
<p>By making network requests <em>asynchronously</em>, we let the webpage execute other code while waiting for the HTTP response to come back. This keeps the user experience snappy and user-friendly.</p>
<p>As a general rule, we should only use async code when we need to for performance reasons. Synchronous code is simpler.</p>
<p><img src="https://i.imgur.com/03FFGu0.png" alt="Image" width="587" height="335" loading="lazy"></p>
<h3 id="heading-promises-in-javascript">Promises in JavaScript</h3>
<p>A Promise in JavaScript is very similar to making a promise in the real world. When we make a promise, we are making a commitment to something.</p>
<p>For example, <em>I promise to explain JavaScript promises to you</em>. My promise to you has 2 potential outcomes: it is either fulfilled, meaning I eventually explained promises to you, or it is rejected, meaning I failed to keep my promise and didn't explain promises.</p>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise Object</a> represents the eventual fulfillment or rejection of our promise and holds the resulting values. In the meantime, while we're waiting for the promise to be fulfilled, our code continues executing.</p>
<p>Promises are the most popular modern way to write asynchronous code in JavaScript.</p>
<h3 id="heading-how-to-declare-a-promise">How to Declare a Promise</h3>
<p>Here is an example of a promise that will resolve and return the string "resolved!" or reject and return the string "rejected!" after 1 second.</p>
<pre><code class="lang-plaintext">const promise = new Promise((resolve, reject) =&gt; {
  setTimeout(() =&gt; {
    if (getRandomBool()) {
      resolve("resolved!")
    } else {
      reject("rejected!")
    }
  }, 1000)
})

function getRandomBool(){
  return Math.random() &lt; .5
}
</code></pre>
<h3 id="heading-how-to-use-a-promise">How to Use a Promise</h3>
<p>Now that we've created a promise, how do we use it?</p>
<p>The <code>Promise</code> object has <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">.then</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch">.catch</a> that make it easy to work with. Think of <code>.then</code> as the <em>expected</em> follow-up to a promise, and <code>.catch</code> as the "something went wrong" follow-up.</p>
<p>If a promise <em>resolves</em>, its <code>.then</code> function will execute. If the promise rejects, its <code>.catch</code> method will execute.</p>
<p>Here's an example of using <code>.then</code> and <code>.catch</code> with the promise we made above:</p>
<pre><code class="lang-js">promise.then(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The promise finally <span class="hljs-subst">${message}</span>`</span>)
}).catch(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The promise finally <span class="hljs-subst">${message}</span>`</span>)
})

<span class="hljs-comment">// prints:</span>
<span class="hljs-comment">// The promise finally resolved!</span>
<span class="hljs-comment">// or</span>
<span class="hljs-comment">// the promise finally rejected!</span>
</code></pre>
<h3 id="heading-why-are-promises-useful">Why are Promises useful?</h3>
<p>Promises are the cleanest (but not the only) way to handle the common scenario where we need to make requests to a server, which is typically done via an HTTP request. In fact, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch()</a> function we were using earlier in the course returns a promise!</p>
<h3 id="heading-io-or-inputoutput">I/O, or "input/output"</h3>
<p>Almost every time you use a promise in JavaScript it will be to handle some form of I/O. I/O, or input/output, refers to when our code needs to interact with systems outside of the (relatively) simple world of local variables and functions.<br>Common examples of I/O include:</p>
<ul>
<li><p>HTTP requests</p>
</li>
<li><p>Reading files from the hard drive</p>
</li>
<li><p>Interacting with a Bluetooth device</p>
</li>
</ul>
<p>Promises help us perform I/O without forcing our entire program to freeze up while we wait for a response.</p>
<h3 id="heading-promises-and-the-await-keyword">Promises and the "await" keyword</h3>
<p>We have used the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a> keyword a few times in this course, so it's time we finally understand what's going on under the hood.</p>
<p>The <code>await</code> keyword is used to <em>wait</em> for a promise to resolve. Once it has been resolved, the <code>await</code> expression returns the value of the resolved <code>Promise</code>.</p>
<h3 id="heading-example-with-then-callback">Example with .then callback</h3>
<pre><code class="lang-js">promise.then(<span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Resolved with <span class="hljs-subst">${message}</span>`</span>)
}).
</code></pre>
<h3 id="heading-example-of-awaiting-a-promise">Example of awaiting a promise</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> message = <span class="hljs-keyword">await</span> promise
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Resolved with <span class="hljs-subst">${message}</span>`</span>)
</code></pre>
<h3 id="heading-the-async-keyword">The async keyword</h3>
<p>While the <code>await</code> keyword can be used in place of <code>.then()</code> to <em>resolve</em> a promise, the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a> keyword can be used in place of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">new promise()</a> to <em>create</em> a new promise.</p>
<p>When a function is prefixed with the <code>async</code> keyword, it will <em>automatically</em> return a promise. That promise resolves with the value that your code returns from the function. You can think of <code>async</code> as "wrapping" your function within a promise.</p>
<p>These are equivalent:</p>
<h3 id="heading-new-promise">New Promise()</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromiseForUserData</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    fetchDataFromServerAsync().then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
      resolve(user)
    })
  })
}

<span class="hljs-keyword">const</span> promise = getPromiseForUserData()
</code></pre>
<h3 id="heading-async">Async</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromiseForUserData</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchDataFromServer()
  <span class="hljs-keyword">return</span> user
}

<span class="hljs-keyword">const</span> promise = getPromiseForUserData()
</code></pre>
<h3 id="heading-then-vs-await">.then() vs await</h3>
<p>In the early days of web browsers, promises and the <code>await</code> keyword didn't exist, so the only way to do something asynchronously was to use callbacks.</p>
<p>A "callback function" is a function that you hand to another function. That function then calls your callback later on. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeout</a> function we've used in the past is a good example.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"calling back now!"</span>)
}
<span class="hljs-keyword">const</span> milliseconds = <span class="hljs-number">1000</span>
<span class="hljs-built_in">setTimeout</span>(callbackFunction, milliseconds)
</code></pre>
<p>While even the <code>.then()</code> syntax is generally easier to use than callbacks without the <code>Promise</code> API, the <code>await</code> syntax makes them even easier to use. You should use <code>async</code> and <code>await</code> over <code>.then</code> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise">new Promise()</a> as a general rule.</p>
<p>To demonstrate, which of these is easier to understand?</p>
<pre><code class="lang-js">fetchUser.then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
  <span class="hljs-keyword">return</span> fetchLocationForUser(user)
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">location</span>)</span>{
  <span class="hljs-keyword">return</span> fetchServerForLocation(location)
}).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">server</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The server is <span class="hljs-subst">${server}</span>`</span>)
});
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser()
<span class="hljs-keyword">const</span> location = <span class="hljs-keyword">await</span> fetchLocationForUser(user)
<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">await</span> fetchServerForLocation(location)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The server is <span class="hljs-subst">${server}</span>`</span>)
</code></pre>
<p>They both do the same thing, but the second example is so much easier to understand! The <code>async</code> and <code>await</code> keywords weren't released until <em>after</em> the <code>.then</code> API, which is why there is still a lot of legacy <code>.then()</code> code out there.</p>
<h2 id="heading-error-handling">Error Handling</h2>
<p>When something goes wrong while a program is running, JavaScript uses the <code>try/catch</code> paradigm for handling those errors. Try/catch is fairly common, and <a target="_blank" href="https://boot.dev/learn/learn-python">Python</a> uses a similar mechanism.</p>
<h3 id="heading-first-an-error-is-thrown">First, an error is thrown</h3>
<p>For example, let's say we try to access a property on an undefined variable. JavaScript will automatically "throw" an error.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> speed = car.speed
<span class="hljs-comment">// The code crashes with the following error:</span>
<span class="hljs-comment">// "ReferenceError: car is not defined"</span>
</code></pre>
<h3 id="heading-trying-and-catching-errors">Trying and catching errors</h3>
<p>By wrapping that code in a try/catch block, we can handle the case where <code>car</code> is not yet defined.</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> speed = car.speed
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`An error was thrown: <span class="hljs-subst">${err}</span>`</span>)
  <span class="hljs-comment">// the code cleanly logs:</span>
  <span class="hljs-comment">// "An error was thrown: ReferenceError: car is not defined"</span>
}
</code></pre>
<h3 id="heading-bugs-vs-errors">Bugs vs Errors</h3>
<p>Error handling via try/catch is not the same as debugging. Likewise, errors are not the same as bugs.</p>
<ul>
<li><p>Good code with no bugs can still produce errors that are gracefully handled</p>
</li>
<li><p>Bugs are, by definition, bits of code that aren't working as intended</p>
</li>
</ul>
<h3 id="heading-what-is-debugging">What is Debugging?</h3>
<p>"Debugging" a program is the process of going through your code to find where it is not behaving as expected. Debugging is a manual process performed by the developer.</p>
<p>Examples of debugging:</p>
<ul>
<li><p>Adding a missing parameter to a function call</p>
</li>
<li><p>Updating a broken URL that an HTTP call was trying to reach</p>
</li>
<li><p>Fixing a date-picker component in an app that wasn't displaying properly</p>
</li>
</ul>
<h3 id="heading-what-is-error-handling">What is Error Handling?</h3>
<p>"Error handling" is code that can handle <em>expected</em> edge cases in your program. Error handling is an automated process that we design into our production code to protect it from things like weak internet connections, bad user input, or bugs in other people's code that we have to interface with.</p>
<p>Examples of error handling:</p>
<ul>
<li><p>Using a try/catch block to detect an issue with user input</p>
</li>
<li><p>Using a try/catch block to gracefully fail when no internet connection is available</p>
</li>
</ul>
<h3 id="heading-in-short-dont-use-trycatch-to-try-to-handle-bugs">In short, don't use try/catch to try to handle bugs</h3>
<p>If your code has a <a target="_blank" href="https://en.wikipedia.org/wiki/Software_bug">bug</a>, try/catch won't help you. You need to just go find the bug and fix it.</p>
<p>If something out of your control can produce issues in your code, you should use try/catch or other error-handling logic to deal with it.</p>
<p>For example, there could be a prompt in a game for users to type in a new character name, but we don't want them to use punctuation. Validating their input and displaying an error message if something is wrong with it would be a form of "error handling".</p>
<h3 id="heading-asyncawait-makes-error-handling-easier">async/await makes error handling easier</h3>
<p><code>try</code> and <code>catch</code> are the standard way to handle errors in JavaScript, the trouble is, the original Promise API with <code>.then</code> didn't allow us to make use of <code>try</code> and <code>catch</code> blocks.</p>
<p>Luckily, the <code>async</code> and <code>await</code> keywords <em>do</em> allow it - yet another reason to prefer the newer syntax.</p>
<h3 id="heading-catch-callback-on-promises">.catch() callback on promises</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch">.catch()</a> method works similarly to the .then() method, but it fires when a promise is <em>rejected</em> instead of resolved.</p>
<h3 id="heading-example-with-then-and-catch-callbacks">Example with .then and .catch callbacks</h3>
<pre><code class="lang-js">fetchUser().then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user fetched: <span class="hljs-subst">${user}</span>`</span>)
}).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`an error was thrown: <span class="hljs-subst">${err}</span>`</span>)
});
</code></pre>
<h3 id="heading-example-of-awaiting-a-promise-1">Example of awaiting a promise</h3>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser()
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user fetched: <span class="hljs-subst">${user}</span>`</span>)
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`an error was thrown: <span class="hljs-subst">${err}</span>`</span>)
}
</code></pre>
<p>As you can see, the <code>async/await</code> version looks just like normal <code>try/catch</code> JavaScript.</p>
<h2 id="heading-http-headers">HTTP Headers</h2>
<p>An <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/HTTP_header">HTTP header</a> allows clients and servers to pass <em>additional</em> information with each request or response. Headers are just case-insensitive <a target="_blank" href="https://en.wikipedia.org/wiki/Name%E2%80%93value_pair">key-value pairs</a> that pass additional <a target="_blank" href="https://en.wikipedia.org/wiki/Metadata">metadata</a> about the request or response.</p>
<p>HTTP requests from a web browser carry with them many headers, including but not limited to:</p>
<ul>
<li><p>The type of client (for example Google Chrome)</p>
</li>
<li><p>The Operating system (for example Windows)</p>
</li>
<li><p>The preferred language (for example US English)</p>
</li>
</ul>
<p>As developers, we can also define custom headers in each request.</p>
<h3 id="heading-headers-api">Headers API</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Headers">Headers</a> API allows us to perform various actions on our request and response headers such as retrieving, setting, and removing them. We can access the headers object through the <code>Request.headers</code> and <code>Response.headers</code> properties.</p>
<h3 id="heading-how-to-use-the-browsers-developer-tools">How to Use the Browser's Developer Tools</h3>
<p>Modern web browsers offer developers a powerful set of <em>developer tools</em>. The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools">Developer Tools</a> are a front-end web developer's best friend. For example, using the dev tools you can:</p>
<ul>
<li><p>View the web page's JavaScript console output</p>
</li>
<li><p>Inspect the page's HTML, CSS, and JavaScript code</p>
</li>
<li><p>View network requests and responses, along with their headers</p>
</li>
</ul>
<p>The method for accessing dev tools varies from browser to browser. If you're on Chrome, you can just right-click anywhere within a web page and click the "inspect" option. Follow this link for more info on <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools#:~:text=How%20do%20you%20pull%20it%20up%3F%20Three%20ways%3A">how to access dev tools</a>.</p>
<h3 id="heading-the-network-tab">The network tab</h3>
<p>While all of the tabs within the dev tools are very useful, we will be focusing specifically on the <em>Network tab</em> in this chapter so we can play with HTTP headers.</p>
<p>The Network tab monitors your browser's network activity and records all of the requests and responses the browser is making, including how long each of those requests and responses takes to fully process.</p>
<p>If you navigate to the Network tab and don't see any requests appear, try refreshing the page.</p>
<p><img src="https://i.imgur.com/STKdceG.png" alt="Image" width="580" height="372" loading="lazy"></p>
<h3 id="heading-why-are-headers-useful">Why are headers useful?</h3>
<p>Headers are useful for several reasons, from design to security. But most often headers are used as <a target="_blank" href="https://en.wikipedia.org/wiki/Metadata">metadata</a> or data <em>about</em> the request.</p>
<p>So, for example, let's say we wanted to ask for a player's level from a game's server. We need to send that player's ID to the server so it knows which player to send back the information for. That ID <em>is my request</em>, it's not information <em>about my request</em>.</p>
<p>A good example of a use case for headers is <a target="_blank" href="https://auth0.com/intro-to-iam/what-is-authentication/">authentication</a>. Often times a user's credentials are included in request headers. Credentials don't have much to do with the request <em>itself</em>, but simply authorize the requester to be allowed to make the request in question.</p>
<h2 id="heading-what-is-json">What is JSON?</h2>
<p>JavaScript Object Notation, or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON">JSON</a>, is a standard for representing <em>structured</em> data based on JavaScript's object syntax.</p>
<p>JSON is commonly used to transmit data in web apps using HTTP. The HTTP <code>fetch()</code> requests we have been using in this course have been returning data as JSON data.</p>
<h3 id="heading-json-syntax">JSON Syntax</h3>
<p>Because we already understand what JavaScript objects look like, understanding JSON is easy. JSON is just a stringified JavaScript object. The following is valid JSON data:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"movies"</span>: [
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Iron Man"</span>,
            <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Jon Favreau"</span>
        },
        {
            <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
            <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
            <span class="hljs-attr">"title"</span>: <span class="hljs-string">"The Avengers"</span>,
            <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Joss Whedon"</span>
        }
    ]
}
</code></pre>
<h3 id="heading-how-to-parse-http-responses-as-json">How to Parse HTTP Responses as JSON</h3>
<p>JavaScript provides us with some easy tools to help us work with JSON. After making an HTTP request with the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch() API</a>, we get a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response object</a>. That response object offers us some methods that help us interact with the response.</p>
<p>One such method is the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Response/json">.json()</a> method. The <code>.json()</code> method takes the response stream returned by a fetch request and returns a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves into a JavaScript object parsed from the JSON body of the HTTP response.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> resp = <span class="hljs-keyword">await</span> fetch(...)
<span class="hljs-keyword">const</span> javascriptObjectResponse = <span class="hljs-keyword">await</span> resp.json()
</code></pre>
<p>It's important to note that the result of the <code>.json()</code> method is <em>NOT</em> JSON. It is the result of taking JSON data from the HTTP response body and parsing that input into a JavaScript Object.</p>
<h3 id="heading-json-review">JSON Review</h3>
<p>JSON is a <em>stringified representation</em> of a JavaScript object, which makes it perfect for saving to a file or sending in an HTTP request.</p>
<p>Remember, an actual JavaScript object is something that exists only within your program's variables. If we want to send an object outside our program, for example, across the internet in an HTTP request, we need to convert it to JSON first.</p>
<h3 id="heading-its-not-just-used-in-javascript">It's not just used in JavaScript</h3>
<p>Just because JSON is called <em>JavaScript</em> Object Notation doesn't mean it's only used by JavaScript! JSON is a common standard that is recognized and supported by every major programming language.</p>
<p>For example, even though Boot.dev's backend API is written in <a target="_blank" href="https://boot.dev/learn/learn-golang">Go</a>, we still use <a target="_blank" href="https://blog.boot.dev/golang/json-golang/">JSON</a> as the communication format between the front-end and backend.</p>
<p>By the way, this course has been about interacting with back-end servers from a front-end perspective. But if you're curious about how you can become a back-end engineer, <a target="_blank" href="https://blog.boot.dev/backend/become-backend-developer/">check out this guide</a> I've put together. For reference, it takes most people <a target="_blank" href="https://blog.boot.dev/backend/how-long-to-become-backend-dev/">between 6-18 months</a> to learn enough to get their first <a target="_blank" href="https://blog.boot.dev/backend/backend-job-description/">back-end job</a>.</p>
<h3 id="heading-common-json-use-cases">Common JSON use-cases</h3>
<ul>
<li><p>In HTTP request and response bodies</p>
</li>
<li><p>As formats for text files. <code>.json</code> files are often used as configuration files.</p>
</li>
<li><p>In NoSQL databases like MongoDB, ElasticSearch, and Firestore</p>
</li>
</ul>
<h3 id="heading-how-to-pronounce-json">How to Pronounce JSON</h3>
<p>I pronounce it "Jay-sawn", but I've also heard people pronounce it "Jason", like the name.</p>
<h3 id="heading-how-to-send-json">How to Send JSON</h3>
<p>JSON isn't just something we get from the server, we can also <em>send</em> JSON data.<br>In JavaScript, two of the main methods we have access to are <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse()</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a>.</p>
<h4 id="heading-jsonstringify"><code>JSON.stringify()</code></h4>
<p><code>JSON.stringify()</code> is particularly useful for <em>sending</em> JSON.</p>
<p>As you may expect, the JSON <code>stringify()</code> method does the opposite of parse. It takes a JavaScript object or value as input and converts it into a string. This is useful when we need to serialize the objects into strings to send them to our server or store them in a database.</p>
<p>Here's a snippet of code that sends a JSON payload to a remote server:</p>
<pre><code class="lang-plaintext">async function sendPayload(data, headers) {
  const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    headers: headers,
    body: JSON.stringify(data)
  })
  return response.json()
}
</code></pre>
<h3 id="heading-how-to-parse-json">How to Parse JSON</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse()</a> method takes a JSON string as input and constructs the JavaScript value/object described by the string. This allows us to work with the JSON as a normal JavaScript object.</p>
<p>Seeing as JSON objects have a tree-like structure, it can be helpful to know how to <a target="_blank" href="https://blog.boot.dev/javascript/how-to-recursively-traverse-objects/">traverse them recursively</a> if needs be.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> json = <span class="hljs-string">'{"title": "Avengers Endgame", "Rating":4.7, "inTheaters":false}'</span>;
<span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">JSON</span>.parse(json)

<span class="hljs-built_in">console</span>.log(obj.title)
<span class="hljs-comment">// Avengers Endgame</span>
</code></pre>
<h3 id="heading-xml">XML</h3>
<p>We can't talk about JSON without mentioning <a target="_blank" href="https://en.wikipedia.org/wiki/XML#:~:text=Extensible%20Markup%20Language%20\(XML\)%20is,%2Dreadable%20and%20machine%2Dreadable.">XML</a>. Extensible Markup Language, or <code>XML</code> is a text-based format for representing structured information, just like JSON - it just looks a bit different.</p>
<p>XML is a markup language like <a target="_blank" href="https://en.wikipedia.org/wiki/HTML">HTML</a>, but it's more generalized in that it does <em>not</em> use predefined tags. Just like how in a JSON object keys can be called anything, XML tags can also have any name.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">root</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">id</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">id</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">genre</span>&gt;</span>Action<span class="hljs-tag">&lt;/<span class="hljs-name">genre</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Iron Man<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">director</span>&gt;</span>Jon Favreau<span class="hljs-tag">&lt;/<span class="hljs-name">director</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">root</span>&gt;</span>
</code></pre>
<p>The same data in JSON form:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"id"</span>: <span class="hljs-string">"1"</span>,
  <span class="hljs-attr">"genre"</span>: <span class="hljs-string">"Action"</span>,
  <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Iron Man"</span>,
  <span class="hljs-attr">"director"</span>: <span class="hljs-string">"Jon Favreau"</span>
}
</code></pre>
<h3 id="heading-why-use-xml">Why use XML?</h3>
<p>XML and JSON both accomplish similar tasks, so which should you use?</p>
<p>XML used to be used for the same things that today JSON is used for. Configuration files, HTTP bodies, and other data-transfer use cases can work just fine using JSON or XML. Here's my advice: generally speaking, if JSON works, you should favor it over XML these days. JSON is lighter-weight, easier to read, and has better support in most modern programming languages.</p>
<p>There are some cases where XML might still be the better, or maybe even the necessary choice, but those cases will be rare.</p>
<h2 id="heading-http-methods">HTTP Methods</h2>
<p>HTTP defines a set of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">methods</a> that we use every time we make a request. We have used some of these methods in previous exercises, but it's time we dive into them and understand the differences and use cases behind the different methods.</p>
<h3 id="heading-the-get-method">The GET method</h3>
<p>The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-get-request-tutorial/">GET method</a> is used to "get" a representation of a specified resource. You are not taking the data away from the server, but rather getting a representation, or copy, of the resource in its current state.</p>
<p>A get request is considered a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP">safe</a> method to call multiple times because it doesn't alter the state of the server.</p>
<h3 id="heading-how-to-make-a-get-request-using-the-fetch-api">How to Make a GET Request using the Fetch API</h3>
<p>The fetch() method accepts an optional <code>init</code> object parameter as its second argument that we can use to define things like:</p>
<ul>
<li><p><code>method</code>: The HTTP method of the request, like <code>GET</code>.</p>
</li>
<li><p><code>headers</code>: The headers to send.</p>
</li>
<li><p><code>mode</code>: Used for security, we'll talk about this in future courses</p>
</li>
<li><p><code>body</code>: The body of the request. Often encoded as JSON.</p>
</li>
</ul>
<p>Example <code>GET</code> request using fetch:</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'sec-ch-ua-platform'</span>: <span class="hljs-string">'macOS'</span>
  }
})
</code></pre>
<h3 id="heading-why-do-we-use-http-methods">Why do we use HTTP methods?</h3>
<p>As we touched on before, the primary purpose of HTTP methods is to indicate to the server what we want to do with the resource we're trying to interact with.</p>
<p>At the end of the day, an HTTP method is just a string, like <code>GET</code>, <code>POST</code>, <code>PUT</code>, or <code>DELETE</code>. But by <em>convention</em>, backend developers almost always write their server code so that the methods correspond with different "CRUD" actions.</p>
<p>The "CRUD" actions are:</p>
<ul>
<li><p>Create</p>
</li>
<li><p>Read</p>
</li>
<li><p>Update</p>
</li>
<li><p>Delete</p>
</li>
</ul>
<p>The bulk of the logic in most web applications is "CRUD" logic. The web interface allows users to create, read, update and delete various resources.</p>
<p>Think of a social media site - users are basically creating, reading, updating and deleting their social posts. They are also creating, reading, updating and deleting their user accounts. It's CRUD all the way down!</p>
<p>As it happens, the 4 most common HTTP methods map nicely to the CRUD actions:</p>
<ul>
<li><p><code>POST</code> = create</p>
</li>
<li><p><code>GET</code> = read</p>
</li>
<li><p><code>PUT</code> = update</p>
</li>
<li><p><code>DELETE</code> = delete</p>
</li>
</ul>
<h3 id="heading-post-requests">POST Requests</h3>
<p>An <a target="_blank" href="https://www.freecodecamp.org/news/javascript-post-request-how-to-send-an-http-post-request-in-js/">HTTP POST request</a> sends data to a server, typically to create a new resource. The <code>body</code> of the request is the <em>payload</em> that is being sent to the server with the request. Its type is indicated by the <code>Content-Type</code> header.</p>
<h3 id="heading-how-to-add-a-body">How to Add a <code>body</code></h3>
<p>The <code>body</code> of the request is the <em>payload</em> that is being sent to the server with the request. Its type is indicated by the <code>Content-Type</code> header - for us, that's going to be JSON.</p>
<p><code>POST</code> requests are generally <em>not</em> safe methods to call multiple times, because it alters the state of the server. You wouldn't want to accidentally create 2 accounts for the same user, for example.</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data)
})
</code></pre>
<h3 id="heading-http-status-codes">HTTP Status Codes</h3>
<p>Now that we understand how to write HTTP requests from scratch, we need to learn how to ensure that the server is doing what we want.</p>
<p>Earlier in the course, we learned about how to access the browser's <em>developer tools</em> and use those tools to inspect HTTP requests. We can use that same process to check on the requests we are making and verify what they are doing so we can address potential problems.</p>
<p>When looking at requests, we can check on the <code>Status Code</code> of the request to get some information if the request was successful or not.</p>
<ul>
<li><p><code>100-199</code>: Informational responses. These are very rare.</p>
</li>
<li><p><code>200-299</code>: Successful responses. Hopefully, most responses are 200's!</p>
</li>
<li><p><code>300-399</code>: Redirection messages. These are typically invisible because the browser or HTTP client will automatically do the redirect.</p>
</li>
<li><p><code>400-499</code>: Client errors. You'll see these often, especially when trying to debug a client application</p>
</li>
<li><p><code>500-599</code>: Server errors. You'll see these sometimes, usually only if there is a bug on the server.</p>
</li>
</ul>
<p>Here are some of the most common status codes, but you can see a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status">full list here</a> if you're interested.</p>
<ul>
<li><p><code>200</code> - OK. This is by far the most common code, it just means that everything worked as expected.</p>
</li>
<li><p><code>201</code> - Created. This means that a resource was created successfully. Typically in response to a <code>POST</code> request.</p>
</li>
<li><p><code>301</code> - Moved permanently. This means the resource was moved to a new place, and the response will include where that new place is. Websites often use <code>301</code> redirects when they change their domain name, for example.</p>
</li>
<li><p><code>400</code> - Bad request. A general error indicating the client made a mistake in their request.</p>
</li>
<li><p><code>403</code> - Unauthorized. This means the client doesn't have the correct permissions. Maybe they didn't include a required authorization header, for example.</p>
</li>
<li><p><code>404</code> - Not found. You'll see this on websites quite often. It just means the resource doesn't exist.</p>
</li>
<li><p><code>500</code> - Internal server error. This means something went wrong on the server, likely a bug on their end.</p>
</li>
</ul>
<h3 id="heading-you-dont-need-to-memorize-them">You don't need to memorize them</h3>
<p>You need to know the basics, like "2XX is good", "4XX is a client error", and "5XX is a server error". That said, you don't need to memorize all the codes, they're easy to look up.</p>
<p><img src="https://i.imgur.com/FJl2z9O.jpg" alt="Image" width="549" height="454" loading="lazy"></p>
<p>Let's check some status codes!</p>
<p>The <code>.status</code> property on a Response object will give you the code. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStatusCode</span>(<span class="hljs-params">url, headers</span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
    <span class="hljs-attr">headers</span>: headers
  })
  <span class="hljs-keyword">return</span> response.status
}
</code></pre>
<h3 id="heading-put-method">PUT Method</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT">HTTP PUT method</a> creates a new resource or replaces a representation of the target resource with the contents of the request's <code>body</code>. In short, it updates a resource's properties.</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> fetch(url, {
   <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
   <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>,
   <span class="hljs-attr">headers</span>: {
   <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
   },
   <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(data)
})
</code></pre>
<h3 id="heading-post-vs-put">POST vs PUT</h3>
<p>You may be thinking <code>PUT</code> is similar to <code>POST</code> or <code>PATCH</code>, and frankly, you'd be right. The main difference is that PUT is meant to be <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Idempotent">idempotent</a>, meaning multiple identical PUT requests should have the same effect on the server.</p>
<p>In contrast, several identical <code>POST</code> requests would have additional side effects, such as creating multiple copies of the resource.</p>
<h3 id="heading-http-patch-vs-put">HTTP Patch vs PUT</h3>
<p>You may encounter <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH">PATCH</a> methods from time to time. While it is not nearly as common as the other methods, like <code>PUT</code>, it's important to know about it and what it does. The <code>PATCH</code> method is intended to <em>partially</em> modify a resource.</p>
<p>Long story short, <code>PATCH</code> isn't nearly as popular as <code>PUT</code>, and many servers, even if they allow partial updates, will still just use the <code>PUT</code> method for that.</p>
<h3 id="heading-http-delete">HTTP Delete</h3>
<p>The <code>DELETE</code> method does exactly as you would expect: it's conventionally used to delete a specified resource.</p>
<pre><code class="lang-js"><span class="hljs-comment">// This deletes the location with ID: 52fdfc07-2182-454f-963f-5f0f9a621d72</span>
<span class="hljs-keyword">const</span> url = <span class="hljs-string">'https://example-api.com/locations/52fdfc07-2182-454f-963f-5f0f9a621d72'</span>

<span class="hljs-keyword">await</span> fetch(url, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">'cors'</span>
})
</code></pre>
<h2 id="heading-url-paths-and-parameters">URL Paths and Parameters</h2>
<p>The URL Path comes right after the domain (or port if one is provided) in a URL string.</p>
<p>In this URL, the path is <code>/root/next</code>: <code>http://testdomain.com/root/next</code>.</p>
<h3 id="heading-what-paths-meant-in-the-early-internet">What paths meant in the early internet</h3>
<p>In the early days of the internet, and sometimes still today, many web servers simply served raw files from the server's file system.</p>
<p>For example, if I wanted you to be able to access some text documents, I could start a web server in my <code>documents</code> directory. If you made a request to my server, you would be able to access different documents by using the path that matched my local file structure.</p>
<p>If I had a file in my local <code>/documents/hello.txt</code>, you could access it by making a <code>GET</code> request to <code>http://example.com/documents/hello.txt</code>.</p>
<h3 id="heading-how-paths-are-used-today">How paths are used today</h3>
<p>Most modern web servers don't use that simple mapping of <code>URL path</code> -&gt; <code>file path</code>. Technically, a URL path is just a string that the web server can do what it wants with, and modern websites take advantage of that flexibility.</p>
<p>Some common examples of what paths are used for include:</p>
<ul>
<li><p>The hierarchy of pages on a website, whether or not that reflects a server's file structure</p>
</li>
<li><p>Parameters being passed into an HTTP request, like an ID of a resource</p>
</li>
<li><p>The version of the API</p>
</li>
<li><p>The type of resource being requested</p>
</li>
</ul>
<h3 id="heading-restful-apis">RESTful APIs</h3>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/REST">Representational State Transfer, or REST</a>, is a popular convention that HTTP servers follow. Not all HTTP APIs are "REST APIs", or "RESTful", but it is <em>very</em> common.</p>
<p>RESTful servers follow a loose set of rules that makes it easy to build reliable and predictable web APIs. REST is more or less a set of conventions about how HTTP <em>should</em> be used.</p>
<h3 id="heading-separate-and-agnostic">Separate and agnostic</h3>
<p>The big idea behind REST is that resources are transferred via well-recognized, language-agnostic client/server interactions.</p>
<p>A RESTful style means the implementation of the client and server can be done independently of one another, as long as some simple standards, like the names of the available resources, have been established.</p>
<h3 id="heading-stateless">Stateless</h3>
<p>A RESTful architecture is stateless. This means that the server does not need to know what state the client is in, nor does the client need to know what state the server is in.</p>
<p>Statelessness in REST is enforced by interacting with resources instead of commands. Keep in mind, this doesn't mean the applications are stateless - on the contrary, what would "updating a resource" even mean if the server wasn't keeping track of its state?</p>
<h3 id="heading-paths-in-rest">Paths in REST</h3>
<p>In a RESTful API, the last section of the <code>path</code> of a URL should specify which resource is being accessed. Then, as we talked about in the "methods" section, depending on whether the request is a <code>GET</code>, <code>POST</code>, <code>PUT</code> or <code>DELETE</code>, the resource is read, created, updated, or deleted.</p>
<p>For example, in the <a target="_blank" href="https://pokeapi.co/">PokeAPI</a>:</p>
<ul>
<li><p><a target="_blank" href="https://pokeapi.co/api/v2/pokemon/"><code>https://pokeapi.co/api/v2/pokemon/</code></a></p>
</li>
<li><p><a target="_blank" href="https://pokeapi.co/api/v2/pokemon/"><code>https://pokeapi.co/api/v2/location/</code></a></p>
</li>
</ul>
<p>The first part of the path specifies that we're interacting with an API rather than a website. The next part specifies the version, in this case, version 2, or <code>v2</code>.</p>
<p>Finally, the last part denotes which resource is being accessed, be it a <code>location</code> or <code>pokemon</code>.</p>
<h3 id="heading-url-query-parameters">URL Query Parameters</h3>
<p>A URL's query parameters appear next in the URL structure but are <em>not</em> always present - they're optional. For example:</p>
<p><a target="_blank" href="https://www.google.com/search?q=boot.dev">https://www.google.com/search?q=boot.dev</a></p>
<p><code>q=boot.dev</code> is a query parameter. Like headers, query parameters are <code>key / value</code> pairs. In this case, <code>q</code> is the key and <code>boot.dev</code> is the value.</p>
<h3 id="heading-the-documentation-of-an-http-server">The Documentation of an HTTP Server</h3>
<p>You may be wondering:</p>
<blockquote>
<p>How the heck am I supposed to memorize how all these different servers work???</p>
</blockquote>
<p>The good news is that <em>you don't need to</em>. When you work with a backend server, it's the responsibility of that server's developers to provide you with instructions, or <em>documentation</em> that explains how to interact with it.</p>
<p>For example, the documentation should tell you:</p>
<ul>
<li><p>The domain of the server</p>
</li>
<li><p>The resources you can interact with (HTTP paths)</p>
</li>
<li><p>The supported query parameters</p>
</li>
<li><p>The supported HTTP methods</p>
</li>
<li><p>Anything else you'll need to know to work with the server</p>
</li>
</ul>
<p><img src="https://i.imgur.com/GIlWhYF.jpg" alt="Image" width="500" height="553" loading="lazy"></p>
<p>The server has control</p>
<p>As we mentioned earlier, the server has complete control over how the path in a URL is interpreted and used in a request. The same goes for query parameters.</p>
<p>Not all servers support query parameters for every type of request, it just depends, so you'll need to consult the docs.</p>
<h3 id="heading-multiple-query-parameters">Multiple Query Parameters</h3>
<p>We mentioned that query parameters are <code>key/value</code> pairs - that means we can have multiple pairs.</p>
<p><code>http://example.com?firstName=lane&amp;lastName=wagner</code></p>
<p>In the example above:</p>
<ul>
<li><p><code>firstName</code> = <code>lane</code></p>
</li>
<li><p><code>lastName</code> = <code>wagner</code></p>
</li>
</ul>
<p>The <code>?</code> separates the query parameters from the rest of the URL. The <code>&amp;</code> is then used to separate <em>every pair</em> of query parameters after that.</p>
<p>For example, make this request to limit the number of Pokémon returned from the PokeAPI to <code>2</code>:</p>
<pre><code class="lang-plaintext">https://pokeapi.co/api/v2/location/?limit=2
</code></pre>
<h2 id="heading-what-is-https">What is HTTPs?</h2>
<p>Hypertext Transfer Protocol <em>Secure</em> or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-https-http-vs-https-meaning-and-how-it-works/">HTTPS</a> is an extension of the HTTP protocol. HTTPS secures the data transfer between client and server by <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Encryption">encrypting</a> all of the communication.</p>
<p>HTTPS allows a client to safely share sensitive information with the server through an HTTP request, such as credit card information, passwords, or bank account numbers.</p>
<p>HTTPS requires that the client use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/SSL">SSL</a> or <a target="_blank" href="https://www.freecodecamp.org/news/what-is-tls-transport-layer-security-encryption-explained-in-plain-english/">TLS</a> to protect requests and traffic by encrypting the information in the request. HTTPS is just HTTP with extra security.</p>
<p><img src="https://i.imgur.com/iOkQUdG.png" alt="Image" width="517" height="487" loading="lazy"></p>
<p><em>HTTP vs HTTPS</em></p>
<h3 id="heading-https-keeps-your-messages-private-but-not-your-identity">HTTPS keeps your messages private, but not your identity</h3>
<p>We won't cover <em>how</em> encryption works in this course, but we will in later courses. For now, it's important to note that while HTTPS encrypts <em>what you are saying</em>, it doesn't necessarily protect <em>who you are</em>. Tools like <a target="_blank" href="https://nordvpn.com/what-is-a-vpn/">VPNs</a> are needed for remaining anonymous online.</p>
<h3 id="heading-https-ensures-that-youre-talking-to-the-right-person-or-server">HTTPS ensures that you're talking to the right person (or server)</h3>
<p>In addition to encrypting the information within a request, HTTPS uses <a target="_blank" href="https://en.wikipedia.org/wiki/Digital_signature">digital signatures</a> to prove that you're communicating with the server that you think you are.</p>
<p>If a hacker were to intercept an HTTPS request by tapping into a network cable, they wouldn't be able to successfully pretend they are your bank's web server.</p>
<p>Assuming that a server supports HTTPs, you use it by simply changing the protocol on your request URL: <code>https://boot.dev</code></p>
<h3 id="heading-want-to-put-what-youve-learned-into-practice-with-a-project">Want to put what you've learned into practice with a project?</h3>
<p>Check out this <a target="_blank" href="https://boot.dev/build/link-analyzer">project guide where you'll build a web crawler in JavaScript</a> from scratch. It will have you using the Fetch API and parsing JSON data like a pro! You don't need to build the project, but it's a great way to practice what you're learned.</p>
<h2 id="heading-congratulations-on-making-it-to-the-end">Congratulations on making it to the end!</h2>
<p>If you're interested in doing the interactive coding assignments and quizzes for this course you can check out the <a target="_blank" href="https://boot.dev/learn/learn-object-oriented-programming">Learn HTTP course</a> over on <a target="_blank" href="https://boot.dev/">Boot.dev</a>.</p>
<p>This course is a part of my <a target="_blank" href="https://boot.dev/tracks/backend">full back-end developer career path</a>, made up of other courses and projects if you're interested in checking those out.</p>
<p>If you want to see the other content I'm creating related to web development, check out some of my links below:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/wagslane">Lane on Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://youtube.com/@bootdotdev">Lane on YouTube</a></p>
</li>
<li><p><a target="_blank" href="https://wagslane.dev">Lane's Personal Site</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Master the HTTP Networking Protocol ]]>
                </title>
                <description>
                    <![CDATA[ HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. It is used to transfer data from the client (web browser) to the server (web host) and vice versa. Understanding the basics of HTTP networking is crucia... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/http-networking-protocol-course/</link>
                <guid isPermaLink="false">66b20389125aeccef6f65cc8</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Mon, 30 Jan 2023 16:54:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/httpnetworking.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. It is used to transfer data from the client (web browser) to the server (web host) and vice versa. Understanding the basics of HTTP networking is crucial for anyone who wants to pursue a career in web development.</p>
<p>We just published a full course on the freeCodeCamp.org YouTube channel that will help you master the HTTP networking protocol by completing over 80 coding exercises and quizzes in JavaScript. The course is designed to help students understand the various concepts of HTTP networking through hands-on learning.</p>
<p>Lane Wagner created this course. He is a senior back end engineer and is the creator of boot.dev where he has published many interactive courses.</p>
<p>Starting from the basics, students watching this course will learn about:</p>
<ul>
<li>why HTTP is important, </li>
<li>how DNS (Domain Name System) works,</li>
<li>the difference between URIs (Uniform Resource Identifiers) and URLs (Uniform Resource Locators),</li>
<li>how HTTP headers work,</li>
<li>how to write and use JSON (JavaScript Object Notation),</li>
<li>the difference between various HTTP methods,</li>
<li>how URL paths are used in HTTP communication, and</li>
<li>implementing security using HTTPS.</li>
</ul>
<p>To help students put their knowledge into practice, the course includes a project where they will build a real web crawler using Node.js. The project will cover the following topics: setting up a development environment, creating a "Hello World" program, normalizing URLs, extracting URLs from HTML, using the Fetch API, recursively crawling the web, and printing an SEO report.</p>
<p>By the end of this video course, students will have a solid understanding of HTTP networking and will be able to put their skills into practice by building a real web crawler.</p>
<p>In conclusion, if you're looking to deepen your knowledge of HTTP networking and build practical skills, this video course is an excellent choice. With over 80 coding exercises and quizzes, students will get a hands-on learning experience that will help them understand the various concepts of HTTP networking. Sign up now and start your journey to mastering HTTP networking.</p>
<p>Watch the full course on <a target="_blank" href="https://www.youtube.com/watch?v=2JYT5f2isg4">the freeCodeCamp.org YouTube channel</a> (5-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/2JYT5f2isg4" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript POST Request – How to Send an HTTP POST Request in JS ]]>
                </title>
                <description>
                    <![CDATA[ HTTP requests allow your front-end application to interact successfully with a back-end server or database. One of the five popular HTTP methods for making requests and interacting with your servers is the POST method, which you can use to send data ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-post-request-how-to-send-an-http-post-request-in-js/</link>
                <guid isPermaLink="false">66d45fdc787a2a3b05af43bc</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 06 Jan 2023 23:40:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/cover-template--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTTP requests allow your front-end application to interact successfully with a back-end server or database.</p>
<p>One of the five popular HTTP methods for making requests and interacting with your servers is the POST method, which you can use to send data to a server.</p>
<p>In this article, you will learn the various methods that you can use to send an HTTP POST request to your back-end server in JavaScript. We'll send GET requests to the <a target="_blank" href="https://jsonplaceholder.typicode.com/todos">free JSON Placeholder todos API</a> for this guide.</p>
<p>There are two built-in JavaScript methods for making an HTTP POST request that don't require the installation of a library or the use of a CDN. These methods are the FetchAPI, based on JavaScript promises, and XMLHttpRequest, based on callbacks.</p>
<p>There are other methods, such as Axios and jQuery, that you will also learn how to use.</p>
<h2 id="heading-how-to-send-a-post-request-with-the-fetch-api">How to Send a POST Request with the Fetch API</h2>
<p>The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request.</p>
<p>The second parameter is used to define the body (data to be sent) and type of request to be sent, while the third parameter is the header that specifies the type of data you will send, for example JSON.</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
    <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
  }),
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  }
});
</code></pre>
<p>In the code above, the body holds the data to be sent to the server and added to the JSONPlaceholder todos API. Also, the headers hold the type of content you want to send to the server, which in this case is JSON data.</p>
<p><strong>Note:</strong> It is always best to serialize your data before sending it to a web server or API using the <strong>JSON.stringify()</strong> method. This will help convert and ensure your JSON data is in string format.</p>
<p>The Fetch API is based on JavaScript promises, so you need to use the .then method to access the promise or response returned.</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
    <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
  }),
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">"Content-type"</span>: <span class="hljs-string">"application/json; charset=UTF-8"</span>
  }
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(json));
</code></pre>
<p>If this is successful, it will return the new JSON data you send to the server.</p>
<h2 id="heading-how-to-send-a-post-request-with-xmlhttprequest">How to Send a POST Request with <code>XMLHttpRequest</code></h2>
<p>Like the Fetch API, <code>XMLHttpRequest</code> is also in-built and has existed much longer than the Fetch API. This means that almost all modern browsers have a built-in XMLHttpRequest object to request data from a server.</p>
<p>You will start by creating a new XMLHttpRequest object stored in a variable called <code>xhr</code>. This is important as it gives you access to all its objects using the variable.</p>
<p>For example, you can then open a connection with <code>.open()</code>, which is used to specify the request type and endpoint (the URL of the server). As you did for the FetchAPI, you will specify the type of data using the <code>setRequestHeader</code> method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.open(<span class="hljs-string">"POST"</span>, <span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>);
xhr.setRequestHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json; charset=UTF-8"</span>)
</code></pre>
<p>The next step is to create the data to be sent to the server. Make sure you serialize the data and then store it in a variable that you'll send with the <code>.send()</code> method after making some checks with the <code>.onload</code> method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> body = <span class="hljs-built_in">JSON</span>.stringify({
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
  <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
});
xhr.onload = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (xhr.readyState == <span class="hljs-number">4</span> &amp;&amp; xhr.status == <span class="hljs-number">201</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(xhr.responseText));
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error: <span class="hljs-subst">${xhr.status}</span>`</span>);
  }
};
xhr.send(body);
</code></pre>
<p>When you put the code together, it will look like this and return the JSON data you send to the server:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.open(<span class="hljs-string">"POST"</span>, <span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>);
xhr.setRequestHeader(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json; charset=UTF-8"</span>);
<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">JSON</span>.stringify({
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
  <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
});
xhr.onload = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (xhr.readyState == <span class="hljs-number">4</span> &amp;&amp; xhr.status == <span class="hljs-number">201</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.parse(xhr.responseText));
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error: <span class="hljs-subst">${xhr.status}</span>`</span>);
  }
};
xhr.send(body);
</code></pre>
<p>The major difference between the Fetch API and <code>XMLHttpRequest</code> method is that the Fetch API has a better syntax that is easier to read and understand.</p>
<p>At this point, you have learned how to use the two JavaScript inbuilt methods to send POST HTTP requests. Let’s now learn how to use Axios and jQuery.</p>
<h2 id="heading-how-to-send-a-post-request-with-axios">How to Send a POST Request with Axios</h2>
<p>Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.</p>
<p>Unlike the Fetch API and <code>XMLHttpRequest</code>, Axios is not built-in. This means you need to install Axios in your JavaScript project.</p>
<p>To install a dependency into your JavaScript project, you will first initialize a new <code>npm</code> project by running the following command in your terminal:</p>
<pre><code class="lang-bash">$ npm init -y
</code></pre>
<p>And now, you can install Axios in your project by running the following command:</p>
<pre><code class="lang-bash">$ npm install axios
</code></pre>
<p>Once Axios is successfully installed, you can send your POST request. This is quite similar to the Fetch API request.</p>
<p>You will pass the API endpoint/URL to the <code>post()</code> method, which will return a promise. You can then handle the promise with the <code>.then()</code> and <code>.catch()</code> methods.</p>
<pre><code class="lang-js">axios.post(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, {
    <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
    <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
  })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .then(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p><strong>Note:</strong> Axios will automatically serialize the object to JSON and set the Content-Type header to 'application/json' for you.</p>
<p>This will return the new data sent to the server.</p>
<h2 id="heading-how-to-send-a-post-request-with-jquery">How to Send a POST Request with jQuery</h2>
<p>Making an HTTP request in jQuery is similar to the Fetch API and Axios, but jQuery is not in-built. So you will first have to install or use its CDN in your project:</p>
<pre><code class="lang-js">&lt;script src=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js"</span> integrity=<span class="hljs-string">"sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ=="</span> crossorigin=<span class="hljs-string">"anonymous"</span> referrerpolicy=<span class="hljs-string">"no-referrer"</span>&gt;&lt;/script&gt;
</code></pre>
<p>With jQuery, you can access the POST method <code>$.post()</code>, which takes in three parameters: the API endpoint/URL, the data to be sent to the server, and a callback function that runs when the request is successful.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> body = {
  <span class="hljs-attr">userId</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Fix my bugs"</span>,
  <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
};
$.post(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos"</span>, body, <span class="hljs-function">(<span class="hljs-params">data, status</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
});
</code></pre>
<p><strong>Note:</strong> You can access the request's data and status in the callback function.</p>
<p>You can check <a target="_blank" href="https://www.freecodecamp.org/news/javascript-get-request-tutorial/">this similar article on how to make an HTTP GET request in JavaScript</a>.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you have learned how to send an HTTP POST request in JavaScript. You might now begin to think — which method should I use?</p>
<p>You can choose between the Fetch API and Axios if it's a new project. Also, if you want to consume basic APIs for a small project, Axios is optional because it demands installing a library.</p>
<p>Have fun coding!</p>
<p>You can access over 150 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Get Request – How to Make an HTTP Request in JS ]]>
                </title>
                <description>
                    <![CDATA[ When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data. This interaction between your frontend application and the backend server is possible through HTTP requests. There are five pop... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-get-request-tutorial/</link>
                <guid isPermaLink="false">66d45fd9d1ffc3d3eb89de0e</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ axios ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Thu, 15 Dec 2022 19:05:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/cover-template--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.</p>
<p>This interaction between your frontend application and the backend server is possible through HTTP requests.</p>
<p>There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.</p>
<p>This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.</p>
<p>For this guide, we'll retrieve posts from the free <a target="_blank" href="https://jsonplaceholder.typicode.com/posts">JSON Placeholder posts API</a>.</p>
<p>There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.</p>
<h2 id="heading-how-to-make-a-get-request-with-the-fetch-api">How to Make a GET Request with the Fetch API</h2>
<p>The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.</p>
<p>Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an <strong>option</strong> argument, which is an optional object when making a GET request <strong>because it is the default request</strong>.</p>
<pre><code class="lang-js">  fetch(url, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">"GET"</span> <span class="hljs-comment">// default, so we can ignore</span>
  })
</code></pre>
<p>Let’s create a GET request to get a post from the <a target="_blank" href="https://jsonplaceholder.typicode.com/posts">JSON Placeholder posts API</a>.</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(json));
</code></pre>
<p>This will return a single post which you can now store in a variable and use within your project.</p>
<blockquote>
<p>Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.</p>
</blockquote>
<h2 id="heading-how-to-make-a-get-request-with-axios">How to Make a GET Request with Axios</h2>
<p>Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.</p>
<p>Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.</p>
<p>To install a dependency into your JavaScript project, you will first initialize a new <code>npm</code> project by running the following command in your terminal:</p>
<pre><code class="lang-js">$ npm init -y
</code></pre>
<p>And now you can install Axios to your project by running the following command:</p>
<pre><code class="lang-js">$ npm install axios
</code></pre>
<p>Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the <code>get()</code> method, which will return a promise. You can then handle the promise with the <code>.then()</code> and <code>.catch()</code> methods.</p>
<pre><code class="lang-js">axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>)
.then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
.catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<blockquote>
<p><strong>Note:</strong> The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.</p>
</blockquote>
<p>At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> and jQuery.</p>
<h2 id="heading-how-to-make-a-get-request-with-xmlhttprequest">How to Make a GET Request with <code>XMLHttpRequest</code></h2>
<p>You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.</p>
<blockquote>
<p><strong>Note:</strong> All modern browsers have a built-in XMLHttpRequest object to request data from a server.</p>
</blockquote>
<p>Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you'll send the request, and finally listen to the server’s response.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.open(<span class="hljs-string">"GET"</span>, <span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>);
xhr.send();
xhr.responseType = <span class="hljs-string">"json"</span>;
xhr.onload = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (xhr.readyState == <span class="hljs-number">4</span> &amp;&amp; xhr.status == <span class="hljs-number">200</span>) {
    <span class="hljs-built_in">console</span>.log(xhr.response);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error: <span class="hljs-subst">${xhr.status}</span>`</span>);
  }
};
</code></pre>
<p>In the above code, a new XMLHttpRequest object is created and stored in a variable called <code>xhr</code>. You can now access all its objects using the variable, such as the <code>.open()</code> method, when you specify the request type (GET) and the endpoint/URL where you want to request data.</p>
<p>Another method you will use is <code>.send()</code>, which sends the request to the server. You can also specify the format in which the data will be returned using the <code>responseType</code> method. At this point, the GET request is sent, and all you have to do is listen to its response using the <code>onload</code> event listener.</p>
<p>If the client's state is done (<strong>4),</strong> and the status code is successful (<strong>200)</strong>, then the data will be logged to the console. Otherwise, an error message showing the error status will appear.</p>
<h2 id="heading-how-to-make-a-get-request-with-jquery">How to Make a GET Request with jQuery</h2>
<p>Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:</p>
<pre><code class="lang-js">&lt;script src=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js"</span> integrity=<span class="hljs-string">"sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ=="</span> crossorigin=<span class="hljs-string">"anonymous"</span> referrerpolicy=<span class="hljs-string">"no-referrer"</span>&gt;&lt;/script&gt;
</code></pre>
<p>With jQuery, you can access the GET method <code>$.get()</code>, which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.</p>
<pre><code class="lang-js">$.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>, <span class="hljs-function">(<span class="hljs-params">data, status</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
});
</code></pre>
<blockquote>
<p><strong>Note:</strong> In the callback function, you have access to the request's <strong>data</strong> and the request's <strong>status</strong>.</p>
</blockquote>
<p>You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:</p>
<pre><code class="lang-js">$.ajax({
  <span class="hljs-attr">url</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>,
  <span class="hljs-attr">type</span>: <span class="hljs-string">"GET"</span>,
  <span class="hljs-attr">success</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) </span>{
    <span class="hljs-built_in">console</span>.log(data);
  }
});
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?</p>
<p>If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.</p>
<p>Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTTP vs HTTPS – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ By Karlgusta Annoh We interact with HTTP and HTTPS a lot in our day-to-day lives, but many people don't know the difference.  Most computer users just see that the browser is telling them their application is not safe and that a hacker might want to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/http-vs-https/</link>
                <guid isPermaLink="false">66d45f6551f567b42d9f845d</guid>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ https ]]>
                    </category>
                
                    <category>
                        <![CDATA[ information security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 16 Aug 2022 17:47:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/HTTP-VS-HTTPS.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Karlgusta Annoh</p>
<p>We interact with HTTP and HTTPS a lot in our day-to-day lives, but many people don't know the difference. </p>
<p>Most computer users just see that the browser is telling them their application is not safe and that a hacker might want to steal their important information. This leads to users running away faster than Usain Bolt's current record.</p>
<p>But this is avoidable. That is where HTTPS comes in and replaces HTTP. And we are going to discuss that today. :)</p>
<h2 id="heading-heres-what-well-cover">Here's What We'll Cover:</h2>
<ol>
<li>What is HTTP?</li>
<li>How HTTP works</li>
<li>Features of HTTP</li>
<li>How to know if a site is not secure</li>
<li>Are all HTTP websites insecure?</li>
<li>What is HTTPS?</li>
<li>How HTTPS works</li>
<li>Features of HTTPS</li>
<li>How encryption works</li>
<li>How to know if a site is secure</li>
<li>What is an SSL certificate?</li>
<li>How does SSL work?</li>
<li>How can I get SSL for my website?</li>
<li>Where can I get an SSL certificate?</li>
<li>Can I get an SSL certificate for free?</li>
<li>The main differences between HTTPS and HTTP</li>
<li>Conclusion</li>
</ol>
<h2 id="heading-what-is-http">What is HTTP?</h2>
<p>Hyper Text Transfer Protocol, or HTTP, is a communication method between your browser and the site you want to visit (web server).</p>
<p>This allows you to get the information that you need from the server on your browser.</p>
<p>A good way to understand HTTP and HTTPS is by using an analogy. We know that browsers and servers communicate using HTTP. HTTP is usually in plain text. Many people around the world speak English. If a hacker who knows English hacks into your computer, they can easily see any password you input.</p>
<p>Here in Kenya, in my mother tongue, we speak Turkana. If you don't speak the language and you come to Kenya and find two Turkanas speaking, you may not understand what they are saying. </p>
<p>That's the beauty of HTTPS. It is encrypted so that the hacker hopefully doesn't understand the communication between the browser and the server.</p>
<p>![Client to server](https://user-images.githubusercontent.com/33565767/178446926-d904cc04-57cd-4427-bdcc-e76c35f8b51b.png "client/browser communicating with server")</p>
<p>If I was to go to http://www.google.com, I would expect to see Google's default page.</p>
<p>![Googles default page](https://user-images.githubusercontent.com/33565767/178450768-e1fed4a5-993d-4d49-a47f-83cce6473085.png "Google's default page")</p>
<p>The client, which in most cases is the web browser, sends a message which in computer terms is a request. Then the server will give back an answer, which is the response.</p>
<p>HTTP is very useful in sending HTML documents as well as images and videos to the web browser for the user to see. It is also used to send data to the server in HTML forms.</p>
<p>![Where HTTP Protocol sits](https://user-images.githubusercontent.com/33565767/178460366-d0568e2d-d107-4afe-a778-0ce1d224b176.png "HTTP Protocol is between the web browser(client) and the web server, which is in constant communication with the server side script and the database.")</p>
<h2 id="heading-how-http-works">How HTTP Works</h2>
<p>HTTP sends data through plain text. For example, if you were to access your bank's web page and they are using HTTP, a hacker may be able to access it and read any information that you send.</p>
<p>This is where HTTPS comes in. Many companies have implemented HTTPS to be able to allow their users to send data securely. We'll discuss this further below.</p>
<h2 id="heading-features-of-http">Features of HTTP</h2>
<ul>
<li>Plain text. Initially when HTTP was developed, developers had one thing in mind: to serve only text documents. Now, HTTP is used in more ways than it was initially intended.</li>
<li><p>Layer 7 protocol. HTTP is a layer 7 protocol in the OSI Model of networking. Layer 7 is the application layer. This layer is the top-most layer in the OSI model. The other layers include the physical, data link, network, transport, session, and presentation layer. To learn more about the OSI model, you can check out this free video on freeCodeCamp's YouTube channel by Brian Ferrill about how the internet works. There are more cookies in the jar other than the OSI model. <a target="_blank" href="https://www.youtube.com/watch?v=qiQR5rTSshw&amp;t=27s&amp;ab_channel=freeCodeCamp.org">Computer Networking Course - Network Engineering [CompTIA Network+ Exam Prep]</a></p>
</li>
<li><p>Insecure. When you send HTTP requests they are sent through plain text. Also, when you get a response, you get it through plain text. This means that anyone who can access the requests and the responses can read them.
![Insecure connection](https://user-images.githubusercontent.com/33565767/179723161-3ec27c27-df79-4749-b810-974583cf1687.png "Insecure connection during a normal HTTP connection by the user")</p>
</li>
<li>Light weight. The advantage of HTTP is that it is very lightweight. It is therefore very fast since it doesn't do the encryption stuff to secure the data, like HTTPS does.</li>
<li>HTTP usually listens on port 80.</li>
</ul>
<h2 id="heading-how-to-know-if-a-site-is-not-secure">How to Know if a Site is Not Secure</h2>
<p>When a site is not secure, Chrome will usually send a warning that says <code>Your connection is not private</code>.
![HTTP Not secure](https://user-images.githubusercontent.com/33565767/182329336-d405d5b4-f5bb-45df-b936-aa1d04b9dffd.png "Your connection is not secure when going to a site that is not secure")</p>
<p>On Chrome, the URL bar will usually show <code>Not Secure</code> in red if a site is not secure.
![Not secure URL image](https://user-images.githubusercontent.com/33565767/182329466-d2db68a8-7033-4f64-bb66-0665e8fc0c62.png "URL of an insecure website")</p>
<h2 id="heading-are-all-http-websites-insecure">Are All HTTP Websites Insecure?</h2>
<p>Well, let's look at an example. Imagine you are browsing a meme website, laughing at each one as you scroll by. If it is using HTTP, then you are off the hook. It's not a big deal.</p>
<p>You get bored and decide to go to your bank's site to access your account on your browser. If the site is not using HTTPS, you might as well be serving your account details to a hacker on a silver plate.</p>
<p>So the bottom line is, if you're browsing inconsequential information, HTTP is ok. But if you are dealing with insecure information, HTTP isn't enough.</p>
<h2 id="heading-what-is-https">What is HTTPS?</h2>
<p>Hyper Text Transfer Protocol Secure, or HTTPS, is a way that communication can happen SECURELY between your browser and the site you want to visit (web server).</p>
<h2 id="heading-how-https-works">How HTTPS Works</h2>
<p>HTTPS makes a secure connection by using a secure protocol that encrypts your data. </p>
<p>For most websites, the best way to have HTTPS is by getting an SSL (Secure Sockets Layer) Certificate or a TLS (Transport Layer Security) certificate.</p>
<p>At the moment, SSL has become advanced enough that it supports TLS. So you don't need to get a TLS certificate.</p>
<h2 id="heading-features-of-https">Features of HTTPS</h2>
<ul>
<li>Encrypts data. Data encryption happens through the TLS/SSL protocol.</li>
<li>It is a layer 4 (Transport layer) protocol. </li>
<li>Key exchanges of public and private keys happen in HTTPS to encypt and decrypt data.</li>
<li>Compared to HTTP, is it heavier. When encrpytion and decryption happens in HTTPS, it becomes heavier.</li>
<li>HTTP listens on port 443.<h2 id="heading-how-encryption-works">How Encryption Works</h2>
</li>
</ul>
<p>![How encryption works](https://user-images.githubusercontent.com/33565767/180215739-5e731309-eda1-4993-927c-c9daa400c3c5.png "I am a dev from the client text passing through an encyption")</p>
<p>Let's say I type "I am a dev". This text gets encrypted when I click send, and then it gets decrypted on the server side.</p>
<p>The same is also true from the server side. If I get a response from the server, it will first get encrypted, then it will get decrypted on the client side.</p>
<h2 id="heading-how-to-know-if-a-site-is-secure">How to Know if a Site is Secure</h2>
<p>To know that a site is secure, you usually look at the URL bar where you can see a lock. If there is a lock, the connection from the client to the server is secure.</p>
<p>![Showing that the site is secure](https://user-images.githubusercontent.com/33565767/178449484-738fb908-901d-4a61-9f8f-fa5a39029012.png "A padlock that shows the site is secure on the URL")</p>
<p>When you click on the lock icon, it tells you more about the secure connection.</p>
<p>![Shows site is secure](https://user-images.githubusercontent.com/33565767/180213859-21460cfa-6a8c-484e-81e5-5dba4fc31f2a.png "The URL section with more details of a secure site")</p>
<h2 id="heading-what-is-an-ssl-certificate">What is an SSL Certificate?</h2>
<p>An SSL certificate is a little file that tells browsers that your website –for example, freecodecamp.org – is who it says it is, and that it is reliable.</p>
<p>In order to authenticate, the certificate is able to confirm to the client (user) that the server they are connecting to is the one that manages that domain. All this is to keep the user safe from security issues such as domain spoofing.</p>
<p>It contains a public key and tells you who the owner of the website is that you are trying to connect to. If a website doesn't have an SSL certificate, it cannot be encrypted with TLS.</p>
<p>You can personally create your own SSL certificate (also known as a self-signed certificate), if you are the website owner. The problem with this approach is that browsers like Chrome don't trust these certificates. They prefer trusting certificates that are issued by a certificate authority.</p>
<h2 id="heading-how-does-ssl-encryption-work">How Does SSL Encryption Work?</h2>
<p>There are two types of SSL encryption, asymmetric and symmetric. The combination of asymmetric and symmetric is what makes SSL Encryption work. Let's look at them below to learn more.</p>
<h3 id="heading-what-is-asymmetric-encryption">What is asymmetric encryption?</h3>
<p>In Asymmetric encryption, you have two keys. These are:</p>
<ol>
<li>Public key.</li>
<li>Private key.</li>
</ol>
<p>![Asymmetric encryption](https://user-images.githubusercontent.com/33565767/181718454-847858dc-0df5-4bc5-bfaf-b6210c571d8f.png "Asymmetric (Public key) encryption")</p>
<p>The client/user/browser gives the public key to the server with which they are communicating. Then, the encyption happens with the help of the public key, and the decryption happens with the help of the server's private key.</p>
<p>The private key can only be found on that particular server. No one else has it. This shows you why asymmetric encryption is stronger and tougher to hack, because it has two different keys, the private and public key. The two keys work together to make sure the data is more secure.</p>
<p>This also tells you why the size of this encryption is 1024/2048 bits.</p>
<h3 id="heading-what-is-symmetric-encryption">What is symmetric encryption?</h3>
<p>In symmetric encryption, it's very simple. You have one key, and that's it. The client uses one key for encryption, and the server uses the same key for decrypting the data.</p>
<p>Symmetric encryption is very light weight. The size is 128/256 bits. But it is a bit easier to hack into as compared to asymmetric. This doesn't mean it is not useful. When we use SSL, we combine Asymmetric and Symmetric to be able to make the communication safer and more secure.</p>
<p>![Symmetric encryption](https://user-images.githubusercontent.com/33565767/181720497-326e0dd9-5e0b-4bfb-b01a-2effec5ab9e0.png "How symmetric encryption works by using one key on the client side to encrypt and the same key on the server side to decrypt")</p>
<h3 id="heading-how-asymmetric-symmetric-encryption-work">How asymmetric + symmetric encryption work</h3>
<p>The combination of both asymmetric and symmetric is now the double-sided wall. 
![Asymmetric and Symmetric](https://user-images.githubusercontent.com/33565767/182565306-224f199a-da88-4a68-be81-707636cc1069.png "How asymmetric and symmetric encryption work by client first sending a Hello to the server. The server then sends to the client, its public key and certificate in response. The client on step 3, sends a session key that is encrypted using the public key. On step 4, the server will decrypt the session key using the server's private key. Finally, step 5, the connection is established between the client and the server.")</p>
<p>In the first step, the server will send to the browser the asymmetric public key. As we now know, the asymmetric key has both the public key and the private key. Therefore, the browser will receive the public key.</p>
<p>After this, the browser generates a session key.</p>
<p>Symmetric encryption uses only one single key for both the client and the server. So what will happen is, the browser will generate a local session key. This is a symmetric encryption session key. It will then encrypt it, with the use of the public key which is asymmetric, given in the first step. The locally generated session key will then be combined with the public key, and sent to the server.</p>
<p>The server will then use a private key to decrypt the encrypted session key it has received. In this particular step, the server will use asymmetric private key to decrypt the session key it has received.</p>
<p>Now, once the decryption has happened, the server and the browser will use the session key for communication. The session key will only be used for that specific session.</p>
<p>Let's say you close your browser, and maybe sign in the next day – everything starts all over again. Session keys get created again.</p>
<h2 id="heading-how-can-i-get-ssl-for-my-website">How Can I Get SSL for My Website?</h2>
<p>If you are a website owner, you can acquire an SSL certificate from a certificate issuing authority. </p>
<p>You will then need to install the certificate on you web server where your website is hosted. Most of the time, the hosting company where you host your website handles this process for you.</p>
<h2 id="heading-where-can-i-get-an-ssl-certificate">Where Can I Get an SSL Certificate?</h2>
<p>There are organizations that issue security certificates. These organizations are called certificate authorities. Some of these certificate authorities include: DigiCert, Comodo, and many others.</p>
<p>Many developers get certificates from these organizations. Since they are the most widely used certificate issuers, browsers usually trust certificates from these organizations.</p>
<h2 id="heading-can-i-get-an-ssl-certificate-for-free">Can I Get an SSL Certificate for Free?</h2>
<p>Cloudflare offers SSL certificates for free. It is one of the first internet security companies to do so. </p>
<p>If you want to get one, you can <a target="_blank" href="https://www.cloudflare.com/ssl/">check it out here</a>.</p>
<h2 id="heading-what-is-https-used-for">What is HTTPS Used For?</h2>
<p>HTTPS helps a lot with security. Without it, passing sensitive information becomes a big challenge especially if your business requires a secure way of communication. </p>
<p>Sites that accept online payments like ecommerce sites typically require HTTPS. This is to avoid information such as credit card details and login information from being stolen (Source: <a target="_blank" href="https://www.entrepreneur.com/article/281633">Tony Messer</a>).</p>
<h2 id="heading-the-main-differences-between-https-and-http">The Main Differences between HTTPS and HTTP</h2>
<ul>
<li>The encryption layer is enabled in HTTPS while there is no encryption layer in HTTP.</li>
<li>Your data is protected in HTTPS while in HTTP it is not.</li>
<li>Your ranking is boosted in Google when you use HTTPS while with HTTP, you don't get any ranking boost.</li>
<li>You are protected against phishing when you use HTTPS while there is not protection when using HTTP.</li>
<li>You are compliant with the regulations of the payment industry when you use HTTPS while HTTP is non-compliant.</li>
<li>Loading HTTPS in the first few seconds may be slower than loading HTTP.</li>
<li>Getting SSL certificates can cost money while there is no certification costs with HTTP.</li>
<li>While using HTTPS, you become buddies with Google Chrome. Google Chrome doesn't like HTTP and therefore you will always be getting unsecured site notifications.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>HTTP and HTTPS are very important in our day to day lives as developers. The communication between the browser and the server is what fuels much the work we do.</p>
<p>By protecting your users' data as much as you're able so their information doesn't get stolen, you'll gain their trust and provide a better user experience.</p>
<p>See you soon.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 429 Error – Too Many Requests HTTP Code Explained ]]>
                </title>
                <description>
                    <![CDATA[ Whether you are a web developer or you are a regular internet user, you might have encountered a 429 error. It means that the website can't handle the number of requests being sent to it. For a developer, this error can be hard to resolve because, on... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-the-429-too-many-requests-http-error/</link>
                <guid isPermaLink="false">66adf282db5636c0b30cbaa4</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Tue, 28 Jun 2022 15:45:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/429.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Whether you are a web developer or you are a regular internet user, you might have encountered a 429 error. It means that the website can't handle the number of requests being sent to it.</p>
<p>For a developer, this error can be hard to resolve because, on many occasions, it doesn’t show what you need to do to fix it.
<img src="https://www.freecodecamp.org/news/content/images/2022/06/deve-429.png" alt="deve-429" width="600" height="400" loading="lazy"></p>
<p>But if you’re surfing the net as a user and you encounter the error, there could be a hint showing what to do.
<img src="https://www.freecodecamp.org/news/content/images/2022/06/429-clinet.png" alt="429-clinet" width="600" height="400" loading="lazy"></p>
<p>In this case, you should wait a bit to make another request. For security reasons, the period of time to wait might not be specified. But if the website proritzes user experience, they'll show you how much time to wait before making another request.</p>
<p>In this article, I will explain what the 429 error means and how a developer might have implemented it. I will also show what you can do to resolve it as an internet user.</p>
<h2 id="heading-what-is-the-429-error">What is the 429 Error?</h2>
<p>The 429 error is an HTTP status code. It tells you when the use of an internet resource has surpassed the number of requests it can send within a given period of time.</p>
<p>This error might be shown to you in another form like:</p>
<ul>
<li>Error 429 </li>
<li>429 Too many requests</li>
<li>429 (Too many requests)</li>
</ul>
<p>It all depends on how the administrator in charge of the internet resource customizes it.</p>
<p>In the small app I built to show you how rate limiting is implemented in an Express app, this is how I customized the error:
<img src="https://www.freecodecamp.org/news/content/images/2022/06/custom429.png" alt="custom429" width="600" height="400" loading="lazy"></p>
<p>With this error, the administrators in charge of a website or internet resource are telling you they don’t have enough resources to handle the number of requests you are sending over. This is called “rate limiting”.</p>
<h2 id="heading-what-causes-the-429-error">What Causes the 429 Error?</h2>
<p>The most common cause of the 429 error is not having enough resources to handle so many concurrent requests. </p>
<p>For example, if this error is shown on a hosting server, it could mean that the package you’re using has a limit for the number of requests you can send. </p>
<p>And if the error comes up while making an API request, it means you’ve exceeded the number of requests you can make for a certain period of time.</p>
<p>Also, if a user tries to access a page on a website too often, the server of that website could trigger a rate-limiting feature implemented in it. So, this is a good security measure to put in place in order to prevent attacks from hackers.</p>
<p>For example, this is how you can implement rate limiting in an Express app using the <a target="_blank" href="https://www.npmjs.com/package/express-rate-limit">express-rate-limit package</a>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import deps</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> rateLimit = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express-rate-limit"</span>);

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// Port</span>
<span class="hljs-keyword">const</span> port = <span class="hljs-number">4000</span>;

<span class="hljs-keyword">const</span> limiter = rateLimit({
  <span class="hljs-attr">windowMs</span>: <span class="hljs-number">5</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span>,
  <span class="hljs-attr">max</span>: <span class="hljs-number">5</span>, <span class="hljs-comment">// Limits each IP to 5 per 15 minutes</span>
  <span class="hljs-attr">message</span>:
    <span class="hljs-string">`&lt;h1 style='display:flex; align-items:center; justify-content:center; height:100vh'&gt;
     429 - Too many Requests &lt;br&gt; Try again later!
    &lt;/h1&gt;`</span>,
});

<span class="hljs-comment">// Apply to all requests</span>
app.use(limiter);

app.get(<span class="hljs-string">"/"</span>, limiter, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">"Hello World!"</span>));

app.listen(port, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`App listening on port <span class="hljs-subst">${port}</span>!`</span>));
</code></pre>
<p>And when the limit is surpassed for the number of seconds specified, this message gets shown to the user:
<img src="https://www.freecodecamp.org/news/content/images/2022/06/custom429.png" alt="custom429" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-you-can-do-to-resolve-the-429-error">What you can do to Resolve the 429 Error</h2>
<p>As an internet user, you should wait a bit before making another request. But if the error persists, you should contact the website administrator.</p>
<p>If you’re a web administrator, you should reduce the number of requests you make within the specified time (if any). If you are in control of the limit yourself, you should increase it for a particular period of time.</p>
<p>If the website you’re handling is a WordPress website, one of your plugins or themes might be causing the 429 error. You should disable your site plugins and themes one by one to see which one of them is the cause.</p>
<p>If the error is related to hosting, you should contact the customer care service of your hosting provider.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>No website admin wants their server to get clunked up or crash. So, from a technical perspective, the 429 error is not an error. It’s the server’s way of telling you it doesn’t have enough resources to handle the high number of requests you’re making.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Error 502 Bad Gateway Meaning ]]>
                </title>
                <description>
                    <![CDATA[ When you visit a website and you get a “502 Bad Gateway” error, it means there’s an issue with the servers powering the website.   On many occasions, this error is an issue with the website itself, so on your end, there’s nothing you can do to solve ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/error-502-bad-gateway-meaning/</link>
                <guid isPermaLink="false">66adf0c2b0efb2bf012fd7b5</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 08 Jun 2022 20:21:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/502b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you visit a website and you get a “502 Bad Gateway” error, it means there’s an issue with the servers powering the website.  </p>
<p>On many occasions, this error is an issue with the website itself, so on your end, there’s nothing you can do to solve it. </p>
<p>But the error can also occur if your network adapters or network settings of your computer are badly configured. </p>
<p>The “502” in the error is an HTTP status code that indicates one server received an invalid response from another server.</p>
<p>Google shows the error this way:
<img src="https://www.freecodecamp.org/news/content/images/2022/06/502-error.png" alt="502-error" width="600" height="400" loading="lazy"></p>
<p>Sometimes, a popular forum in my country shows it this way:
<img src="https://www.freecodecamp.org/news/content/images/2022/06/cloudflare-502-bad-gateway-error.png" alt="cloudflare-502-bad-gateway-error" width="600" height="400" loading="lazy"></p>
<p>It looks like websites powered by Cloudflare show the error that way.</p>
<p>Some other websites show it in their own customized way.</p>
<h2 id="heading-what-exactly-does-502-bad-gateway-mean">What Exactly Does 502 Bad Gateway Mean?</h2>
<p>The international engineering task force (IETF) defines the 502 Bad Gateway Error in a more extensive way:</p>
<blockquote>
<p>The 502 (Bad Gateway) status code indicates that the server while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.</p>
</blockquote>
<p>The “proxy server” is a system or router that acts as a gateway between your computer and the internet. </p>
<p>The inbound server, on the other hand, is the one conveying an incoming connection onto your computer. That is, a web server.</p>
<h2 id="heading-what-causes-a-bad-gateway-error">What Causes a Bad Gateway Error?</h2>
<p>As earlier pointed out, 502 Bad Gateway is a server error just like other HTTP status code errors in the 500 range such as 501 (Not Implemented), 503 (Service Unavailable), 504 (Gateway Timeout), and 505 (HTTP Version not supported).</p>
<p>This particular server error could be an overloaded server, programming, and backend configuration error, or even a yet-to-be-propagated domain name.</p>
<p>But sometimes, the browser could throw this error due to past-due updates, ad-blockers, browser extensions, or computer DNS server problems.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>I hope this article helps you understand what the 502 Bad Gateway error means.</p>
<p>If you’re a web administrator and your users are complaining of this error, you should try to fix it as soon as possible as it could have a negative effect on your website's SEO.</p>
<p>If you’re facing this error as a user, there’s a high chance it’s from the website you’re trying to visit. Some other times, it could be due to a badly configured router and settings.</p>
<p>You can try refreshing the web page, clearing your browser cache, and switching to another browser.</p>
<p>To see how you can solve the error as a user, I wrote <a target="_blank" href="https://www.freecodecamp.org/news/502-bad-gateway-error-solved/">a detailed article that can help you out.</a></p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTTP Error 504 – 504 Gateway Timeout Status Code Explained ]]>
                </title>
                <description>
                    <![CDATA[ While surfing the internet, we are able to interact with web servers through HyperText Transfer Protocol (HTTP) requests. These requests are sent from the client (our browsers) to the server before we get a response.  HTTP status codes allows us know... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/http-error-504-gateway-timeout-status-code-explained/</link>
                <guid isPermaLink="false">66b0a2f8d7edba94d20b3bbe</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 12 Apr 2022 20:21:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/error.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>While surfing the internet, we are able to interact with web servers through HyperText Transfer Protocol (HTTP) requests. These requests are sent from the client (our browsers) to the server before we get a response. </p>
<p>HTTP status codes allows us know if our request to the server was successful or not. Here are the status codes and what each type means:</p>
<ul>
<li>100 - 199 (Informational).</li>
<li>200 - 299 (Successful).</li>
<li>300 - 399 (Redirection).</li>
<li>400 - 499 (Client error).</li>
<li>500 - 599 (Server error).</li>
</ul>
<p>In this article, we'll be talking about the 504 error which falls under the server error category. We'll see some of the reasons why you might encounter this error and the possible ways of fixing it.</p>
<h2 id="heading-what-is-the-http-504-error">What Is the HTTP 504 Error?</h2>
<p>From the status codes listed before this section, we can see that the 504 error is a server error. This means that it is not a problem from our end as the client. Our request was sent successfully to the server but something went wrong while we were awaiting a response. </p>
<p>You'll usually get a response saying "Gateway Timeout Error" or something similar if it is a 504 error.</p>
<p>This error occurs when our server doesn't receive a response fast enough from the server where our request was sent. As a result of the delay, our server times out and returns an error instead.</p>
<p>The reasons for this error can vary. The server where the request was sent to could be down for maintenance or overloaded, amongst other reasons.</p>
<h2 id="heading-how-to-fix-the-http-504-error">How to Fix the HTTP 504 Error</h2>
<p>In this section, we'll talk about some of the ways in which you can fix the 504 error. </p>
<p>The following solutions are for users visiting websites:</p>
<h3 id="heading-refresh-your-browser">Refresh Your Browser</h3>
<p>The first thing you should try when you encounter this error is to refresh your browser. Each browser usually has a shortcut for refreshing, but you can always use the refresh button.</p>
<h3 id="heading-disconnect-and-reconnect-your-network-devices">Disconnect and Reconnect Your Network Devices</h3>
<p>If refreshing your browser doesn't fix the problem then you should try disconnecting from and reconnecting to your network devices. This could be a modem, a router, a Wi-Fi hotspot, and so on. </p>
<h3 id="heading-clear-browser-data-and-cookies">Clear Browser Data and Cookies</h3>
<p>Each browser has a way of clearing data and cookies but this is usually in the browser settings. </p>
<p>While this may fix the problem, you should know that in most cases, it doesn't – so be sure you are willing to get rid of the data and cookies before proceeding.</p>
<h3 id="heading-find-out-if-other-users-are-experiencing-the-same-problem">Find Out If Other Users Are Experiencing the Same Problem</h3>
<p>If you are on any community platform or know other users who make use of the website then you should probably try and find out from them to see if it is a general problem.</p>
<p>If this is a general problem then you can sit back and relax. The website owners might be up to something on the backend.</p>
<p>Note that trying these fixes above may not work all the time. In situations like this, the best thing to do is to wait and try later because it is usually not a problem from your end as the client. </p>
<p>The following solutions are for you if you own a website:</p>
<h3 id="heading-contact-your-hosting-provider">Contact Your Hosting Provider</h3>
<p>In cases where the website belongs to you and users cannot access it, you should try contacting your hosting provider to be sure everything is in check. </p>
<p>It could be as a result of your hosting plan requiring an upgrade because you may have reached the limits of your current plan.</p>
<h3 id="heading-check-for-dns-changes">Check for DNS Changes</h3>
<p>When you change servers for your website, the DNS information changes will usually take some time before updating. So you can inform your users of changes like this before or after they happen.</p>
<p>DNS stands for Domain Name System. They change domain names to IP addresses which browsers can easily recognize before loading websites.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we talked about the HTTP 504 error. We talked about HTTP status codes and found out what category the 504 error belonged to.</p>
<p>We then talked about why this error might happen and some of the possible ways of fixing it.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is REST? Rest API Definition for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn what the term REST means and how it lets us communicate with the server efficiently. Before we get into REST, let's learn what an API is. I believe this will help you understand REST better.  What is an API? Since we'r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-rest-rest-api-definition-for-beginners/</link>
                <guid isPermaLink="false">66b0a3903dc92ea6a5a091f7</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 28 Jan 2022 17:21:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/REST-API.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn what the term REST means and how it lets us communicate with the server efficiently.</p>
<p>Before we get into REST, let's learn what an API is. I believe this will help you understand REST better. </p>
<h2 id="heading-what-is-an-api"><strong>What is an API?</strong></h2>
<p>Since we're talking about REST APIs, our definition of an API will not go beyond the scope of the web. </p>
<p>API stands for Application Programming Interface. An API establishes a connection between programs so they can transfer data. </p>
<p>A program that has an API implies that some parts of its data is exposed for the client to use. The client could be the frontend of the same program or an external program.</p>
<p>In order to get this data, a structured request has to be sent to the API. If the request meets the desired requirements, a response which contains the data gets sent back to where the request was made. This response usually comes in the form of JSON or XML data.</p>
<p>In some cases, you'll need some sort of authorization to gain access to external API data.</p>
<p>Every API has documentation that tells you what data is available and how to structure your request in order to get a valid response.</p>
<h3 id="heading-api-example">API Example</h3>
<p>Was that confusing?</p>
<p>Let's use a real life scenario to give an example.</p>
<p>Imagine visiting a new restaurant. You're there to order food, and since you haven't been there before, you don't exactly know what type of food they serve. </p>
<p>The server then approaches you with a menu so you can pick what you'd like to eat. After making your choice, the server then goes to the kitchen and gets your food.</p>
<p>In this case, the server is the API who is connecting you to the kitchen. The API's documentation is the menu. The request is made when you pick what you'd like to eat, and the response is the food being served.</p>
<p>I hope that helps you understand what an API is and how it works.</p>
<h2 id="heading-what-is-rest">What is REST?</h2>
<p>REST stands for REpresentational State Transfer. It is a standard that guides the design and development of processes which enable us interact with data stored on a web servers. </p>
<p>The above definition may not look as complex or "professional" as the ones you come across on the internet, but the goal here is for you to understand the basic purpose of REST APIs.</p>
<p>An API that complies with some or all of the <a target="_blank" href="https://en.wikipedia.org/wiki/Representational_state_transfer#:~:text=The%20REST%20architectural%20style%20defines,visibility%2C%20portability%2C%20and%20reliability.">six guiding constraints</a> of REST is considered to be <strong>RESTful.</strong></p>
<p>We are able to communicate with servers using the HTTP protocol. With these protocols, we can <strong>Create</strong>, <strong>Read</strong>, <strong>Update</strong> and <strong>Delete</strong> data – otherwise known as <strong>CRUD</strong> operations. </p>
<p>But how can we perform these CRUD operations and communicate with data on the server? </p>
<p>We can do this by sending HTTP requests, and that is where REST comes in. REST simplifies the communication process by providing various HTTP methods/operations/verbs which we can use to send requests to the server.</p>
<h2 id="heading-how-to-communicate-with-a-server-using-rest-apis">How to communicate with a server using REST APIs</h2>
<p>As we discussed in the last section, REST APIs make the communication process with the server easier for us by giving us various HTTP request methods. The most commonly used methods are:</p>
<ul>
<li><strong>GET</strong>: The get method is used to <strong>Read</strong> data on the server.</li>
<li><strong>POST</strong>: The post method is used to <strong>Create</strong> data.</li>
<li><strong>PATCH/PUT</strong>: The patch method is used to <strong>Update</strong> data.</li>
<li><strong>DELETE</strong>: The delete method is used to <strong>Delete</strong> data.</li>
</ul>
<p>These methods provided by REST allow us perform CRUD operations easily. That is:</p>
<p>Create =&gt; POST.<br>Read =&gt; GET.<br>Update =&gt; PATCH/PUT.<br>Delete =&gt; DELETE.</p>
<p>So if we are to make a request to a server, let's say to retrieve data, we are going to make a <strong>GET</strong> request to an endpoint/resource provided by the server. The endpoint is similar to a URL.</p>
<p>If the request made is a valid one, then the server will respond to us with the data we requested. It also sends a status code where 200 is a success and 400 is a client error.</p>
<p>Here is an example of a request made to the JSONPlaceholder API using JavaScript:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(json))
</code></pre>
<p>When making a request using the <code>fetch</code> API, the default method is the GET method – so we are not forced to specify it. But we do need to specify when making a request using the other methods. </p>
<p>In the code example above, the endpoint is <a target="_blank" href="https://jsonplaceholder.typicode.com">https://jsonplaceholder.typicode.com</a> and the specific data we are requesting is one todo item. The data will be returned to us in JSON format.</p>
<p>If we were to make a POST request, then we would include the method type which would be POST and a request body which would contain the data we are creating to send to the server. </p>
<p>Deleting would require that we use the corresponding request method along with the id of the todo item we want to delete. Like this: </p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/3'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>,
});
</code></pre>
<p>Updating would require both the id and the request body that would be used to update the data. Here is an example:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts/5'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">title</span>: <span class="hljs-string">'new todo'</span>,
  }),
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-type'</span>: <span class="hljs-string">'application/json; charset=UTF-8'</span>,
  },
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(json));
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned what REST is and how it helps us communicate with the server efficiently. </p>
<p>We defined an API and gave an example to help explain its meaning. We also got to know some of the methods provided by REST to create, read, update and delete data stored on the server.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
