Week 9 - Networking and APIs

Introduction to Networking

Client Server Model

TCP/IP Protocol

HTTP Protocol

URL Format

Web APIs

API Testing Tools

Using APIs

Practice

Assignment

Core program

The HTTP Protocol

The acronym HTTP stands for HyperText Transfer Protocol.

HyperText: Refers to text that contains links (hyperlinks) to other text or resources.

Transfer: The act of moving data from one place (the server) to another (the client).

Protocol: A set of formal rules that defines how computers communicate with each other, ensuring that data is transferred correctly and reliably.

HTTP requests (clients) and responses (servers) are basically just plain text messages with an optional textual or binary content, often referred to as body or payload. Although we usually work with HTTP requests and responses that have already been parsed into structured data (i.e., ready for programmatic consumption), it is might be illustrative to look at (simplified) examples of the plain-text format messages that are actually transferred between client and server.

HTTP Request Example

Here is a plain-text example of HTTP request to an API at deckofcards.com:

GET /api/deck/734iqo5k0u8b/draw/?count=1 HTTP/2
Host: [deckofcardsapi.com](<http://deckofcardsapi.com/>)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:145.0) Gecko/20100101 Firefox/145.0
Accept: **/**
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Origin: [<http://127.0.0.1:5500>](<http://127.0.0.1:5500/>)
Connection: keep-alive
(some lines omitted for brevity)

In this example JavaScript code running in the browser (i.e., the client) sends a GET request for the data associated with the path /api/deck/734iqo5k0u8b/draw/?count=1. When the server (i.e., the host) receives this request it will break it down (i.e. parse it) into a number of components. The first line specifies the Request Method, Path and the HTTP Protocol Version used for this request.

The text lines following the first line represent the Request Headers, each line making up one request header. A request header consist of a name and value, separated by a colon. For the above example request, these are given in the table below.

Header Value Description
Host deckofcardsapi.com The domain name of the server to which the request is addressed.
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:145.0) Gecko/20100101 Firefox/145.0 Identifies this request as originating from a web browser. In this case a FireFox browser was used. This information allows the server to optimize its response for this client.
Accept / The response content types that the client can handle. The */* wildcard specification indicates that the client does not express any preference.
Accept-Language en-US,en;q=0.5 The preferred ISO language for the response.
Origin http://127.0.0.1:5500 The IP address of the device making the request. In this case, it is a local IP address, such as used when using Open in Live Server command in VS Code.
Connection keep-alive A request to the server to keep the client-server connection open, as additional requests may follow quickly, e.g. for associated CSS style sheets and JavaScript files.

GET HTTP requests, as this example, do not use a body part.

For now, knowing the exact meaning of these headers is not needed. We will come back in later chapters on the most important ones. At present, it suffices to know that an HTTP request includes request headers.

HTTP Response Example

The HTTP Response to the HTTP request from the previous section looks like this (it is again a text-based response):

HTTP/2 200 
date: Thu, 27 Nov 2025 16:06:13 GMT
content-type: application/json
server: cloudflare
access-control-allow-origin: *
(some lines omitted for brevity)

{
  "success": true,
  "deck_id": "734iqo5k0u8b",
  "cards": [
    {
      "code": "5H",
      "image": "<https://deckofcardsapi.com/static/img/5H.png>",
      "images": {
        "svg": "<https://deckofcardsapi.com/static/img/5H.svg>",
        "png": "<https://deckofcardsapi.com/static/img/5H.png>"
      },
      "value": "5",
      "suit": "HEARTS"
    }
  ],
  "remaining": 51
}

The first line contains the following information:

The status code 200 stands for OK, meaning that the server processed the request successfully, resulting in the response at hand. HTTP status codes will be discussed in more detail in the next section.

The next response lines, up to the blank line, make up the Response Headers. The Content begins after the blank line and extends to the end of the response.

Header Value Description
date Thu, 27 Nov 2025 16:06:13 GMT The date of the response.
server cloudflare The name of the HTTP server software accepting HTTP requests on the server.
content-type application/json The type of content, i.e. how the requestor should interpret the content. In this example the textual content should be interpreted as JSON.
access-control-allow-origin * The wildcard * indicates that API accept requests from any origin, and not just from the same origin as the server at deckofcardsapi.com. An API that allows this is said to support CORS (Cross-Origin Resource Sharing).

The content in this example is a JSON string. In the JavaScript application this string can be converted into a JavaScript object through the JSON.parse() function.

JSON.parse() - JavaScript | MDN

HTTP Status Codes

HTTP status codes are three-digit numbers returned by a web server in response to an HTTP request (like requesting a web page). They indicate the outcome of the request, essentially telling the client (usually your web browser) whether the request was successful, if it was redirected, if there was a client error, or if there was a server error.

The first digit of the status code defines the class of response:

Class Range Meaning
1xx 100-199 Informational response - the request was received and is continuing.
2xx 200-299 Successful response - the request was successfully received, understood, and accepted.
3xx 300-399 Redirection - further action needs to be taken to complete the request.
4xx 400-499 Client Error - the request contains bad syntax or cannot be fulfilled.
5xx 500-599 Server Error - the server failed to fulfill an apparently valid request.

For web APIs the most commonly used ones are in the 2xx and 4xx ranges.

2xx Success Codes

Code Name Typical Use Case Developer Notes
200 OK The standard success response for GET, PUT, PATCH, DELETE, or POST requests. This means the request was fulfilled and the response body contains the requested data (for GET). This is the most common success code.
201 Created Returned by a POST request when a new resource has been successfully created. The response should typically include the new resource in the body and a Location header pointing to its URI. Essential for API design.
202 Accepted The request has been accepted for processing, but the processing is not yet complete. Used for long-running, asynchronous tasks (e.g., video transcoding, complex report generation). The client can poll a status endpoint later.
204 No Content The server successfully processed the request, but is not returning any content in the response body. Perfect for DELETE operations, or PUT/PATCH updates where the client doesn't need to refresh or receive the updated resource data. This saves bandwidth.

4xx Client Error Codes

Code Name Typical Use Case Developer Notes
400 Bad Request The server cannot process the request due to invalid client-side input, malformed syntax, or missing required parameters. A backend developer's catch-all for validation failures (e.g., submitting a form with an invalid email format). The client must modify the request before retrying.
401 Unauthorized The request requires user authentication but either it was not provided or is invalid (e.g., a missing or expired access token). Semantically means "unauthenticated." The response often includes a WWW-Authenticate header to challenge the client for credentials.
403 Forbidden The server understood the request, but refuses to authorize it because the user (who may be authenticated) lacks the necessary permissions to access the resource. Semantically means "unauthorized." For example, a standard user trying to access an administrator-only endpoint.
404 Not Found The server cannot find the requested resource at the specified URL. The most common error. The resource is simply not present. The server itself is working.

Content Types

The Content-Type header in HTTP requests and responses is used to indicate the media type of the resource being sent in the message body.

This header tells the recipient (the server for a request, or the client/browser for a response) exactly what kind of data is contained in the body, which is necessary for the recipient to process or display it correctly. The most common media types when working with API are:

Media Type Description & Purpose Common Usage
application/json JSON (JavaScript Object Notation). The most common format for data exchange in APIs and modern web services. API Responses, AJAX calls, configuration files.
application/x-www-form-urlencode Default for simple HTML form submissions. Data is encoded into a single string of key/value pairs (like query parameters). HTML form submissions without file uploads.
multipart/form-data Used to send forms that contain file uploads or other non-textual data. The body is divided into multiple parts, each with its own Content-Type. HTML form submissions with file uploads.

Other examples of media types, for instance for HTML, CSS and JavaScript files as loaded by a web browser when visiting a site, are respectively text/html, text/css and text/javascript.


https://www.youtube.com/watch?v=-Zea7GB2OwA


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0 **

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*