Module 5 · Beginner · How the internet and websites work

HTTP and HTTPS explained

HTTP and HTTPS for beginners: requests and responses, URLs, GET and POST, status codes, headers, cookies, and how HTTPS encryption keeps data safe.

By theprogrammers team · · 10 min read

Every time you open a website, scroll Instagram or check your exam result online, your device sends a message that says, more or less, "please give me this page", and a server replies with "here it is" or "sorry, not found". Those messages follow a set of rules called HTTP. When the same conversation is encrypted so no one in between can read it, it's HTTPS, and that's the padlock in your browser's address bar.

HTTP is the language of the web. Websites, mobile apps and APIs all use it. As a programmer you'll read HTTP status codes in error messages, send requests from Python, and build servers that answer them. This lesson explains HTTP and HTTPS: what a request and response look like, methods like GET and POST, status codes like 404 and 500, headers and cookies, and what HTTPS actually protects.

What you need first: how the internet works.

Key terms

  • HTTP: HyperText Transfer Protocol, the rules for how clients and servers exchange web data.
  • HTTPS: HTTP sent through an encrypted connection (TLS), so others can't read or change it.
  • Client: the program that makes requests, such as a browser, a mobile app or a Python script.
  • Server: the program that receives requests and sends responses.
  • Request: the client's message: what it wants, and any data it sends.
  • Response: the server's reply: a status code, headers and usually a body.
  • Status code: a three-digit number saying how the request went, such as 200 (OK) or 404 (Not Found).
  • Header: a named piece of extra information in a request or response, such as Content-Type.

Request and response

HTTP is a simple conversation: the client asks, the server answers. Each request gets exactly one response.

A browser sends the request GET /results to a server, the server looks up the page, and it sends back the response 200 OK with the HTML page

The server doesn't start the conversation; it waits for requests. And by default, each request is independent: the server doesn't remember your previous request. (Cookies, covered below, are how websites remember you anyway.)

Reading a URL

Every HTTP request is for a URL. Python can split one into parts:

from urllib.parse import urlparse, parse_qs

url = "https://shop.example.com:443/products/phones?brand=samsung&sort=price#reviews"
parts = urlparse(url)

print(parts.scheme)
print(parts.hostname)
print(parts.port)
print(parts.path)
print(parse_qs(parts.query))
print(parts.fragment)
https
shop.example.com
443
/products/phones
{'brand': ['samsung'], 'sort': ['price']}
reviews
PartExampleMeaning
SchemehttpsThe protocol to use
Host (domain)shop.example.comWhich server; DNS turns it into an IP address
Port443Which program on the server; usually left out, because 443 is the HTTPS default
Path/products/phonesWhich resource on the server
Query string?brand=samsung&sort=priceExtra options, as name=value pairs joined by &
Fragment#reviewsA spot on the page; never sent to the server

What a request looks like

HTTP messages are (in HTTP/1.1) plain text. A browser asking for that page sends something like:

GET /products/phones?brand=samsung HTTP/1.1
Host: shop.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...
Accept: text/html
Accept-Language: en-IN,en;q=0.9
Cookie: session_id=abc123
  • The first line has the method (GET), the path and the HTTP version.
  • The next lines are headers: who's asking, what formats it accepts, its language, its cookies.
  • Requests that send data (like a form) add a blank line, then a body.

HTTP methods

The method says what the client wants to do:

MethodMeaningExampleHas a body?
GETFetch somethingOpen a page, load a product listNo
POSTSend new dataSubmit a sign-up form, place an orderYes
PUTReplace somethingUpdate a whole profileYes
PATCHChange part of somethingChange only your phone numberYes
DELETERemove somethingDelete a postUsually no

Browsers mostly use GET (for pages and images) and POST (for forms). APIs use all of them. A GET request should never change data on the server; it only reads. That's why a search uses GET (?q=laptop in the URL) but a payment uses POST.

What a response looks like

The server replies with a status line, headers, a blank line, and the body:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5120
Cache-Control: max-age=60
Set-Cookie: session_id=abc123; Secure; HttpOnly

<!DOCTYPE html>
<html> ... the page ... </html>

The body can be HTML, JSON, an image, a PDF, anything. The Content-Type header tells the client what it is.

Status codes

The three-digit status code is the quickest way to know what happened. The first digit gives the group:

RangeGroupCommon codes
1xxInformationRare in everyday work
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirect: look elsewhere301 Moved Permanently, 302 Found, 304 Not Modified
4xxClient error: the request was wrong400 Bad Request, 401 Unauthorized (not logged in), 403 Forbidden (not allowed), 404 Not Found, 429 Too Many Requests
5xxServer error: the server failed500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

The most useful rule for debugging: 4xx means fix your request; 5xx means the server has a problem. Python has the full list built in:

from http import HTTPStatus

for code in [200, 201, 301, 401, 403, 404, 500, 503]:
    print(code, HTTPStatus(code).phrase)
200 OK
201 Created
301 Moved Permanently
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error
503 Service Unavailable

Headers you'll meet often

HeaderSent byMeaning
HostClientWhich website, as one server can host many
User-AgentClientWhich browser or program is asking
AcceptClientWhich formats it can handle
AuthorizationClientLogin token or API key
Content-TypeBothFormat of the body: text/html, application/json
Cache-ControlServerHow long the response may be cached
Set-CookieServerAsks the browser to store a cookie
LocationServerWhere to go, with a 3xx redirect

Cookies: how websites remember you

HTTP itself forgets you between requests. So when you log in, the server sends a cookie with Set-Cookie, usually a random session ID. Your browser stores it and sends it back with every later request to that site, in the Cookie header. The server looks up that ID and knows it's you.

Cookies are also used for shopping carts, language settings and, more controversially, tracking. Session cookies should be marked Secure (only sent over HTTPS) and HttpOnly (hidden from JavaScript), which makes them harder to steal.

HTTPS: HTTP with encryption

Plain HTTP sends everything as readable text. Anyone between you and the server (someone on the same café Wi-Fi, a compromised router) could read your password or change the page. HTTPS wraps HTTP inside an encrypted TLS connection. It gives you three protections:

ProtectionMeans
EncryptionOthers see scrambled data, not your password or messages
IntegrityNo one can change the data on the way without it being detected
AuthenticationYou're really talking to your bank, say kaveribank.example, and not a fake server, because the site proves its identity with a certificate

When you connect, the server shows a certificate signed by a trusted certificate authority. Your browser checks it; if it's invalid or for a different domain, you get a big warning. Then both sides agree on secret keys and encrypt everything after that.

What HTTPS doesn't do: it doesn't prove a site is honest. A scam site can have a perfectly valid padlock. The padlock means the connection is private, not that the site is trustworthy. Always check the domain name.

Today almost every site uses HTTPS, and browsers mark plain HTTP pages as "Not secure". Free certificates from Let's Encrypt made this easy for everyone.

HTTP versions

VersionWhat it added
HTTP/1.1Plain-text messages, reusable connections. Still widely supported
HTTP/2Binary format, many requests at once over one connection, faster pages
HTTP/3Runs over QUIC (built on UDP) instead of TCP, faster on mobile and unreliable networks

The methods, status codes and headers are the same in all versions, so everything in this lesson applies to all three.

Seeing HTTP yourself

  • Browser developer tools: press F12, open the Network tab, and reload any page. You'll see every request, its method, status code, headers and timing.
  • The terminal: curl -I https://example.com shows the response headers of a page. (curl is built into Windows 10 and 11, macOS and Linux.)
  • Python: the requests library (install with pip) makes requests in one line: requests.get(url).status_code.

Practice

  1. Which method would each of these use: loading a news article, posting a comment, removing a saved address, changing only your email address?
Show the answer

GET, POST, DELETE and PATCH.

  1. What does each status code tell you, and whose side is the problem: 404, 500, 401, 201?
Show the answer

404: the resource wasn't found; usually a wrong URL (client side). 500: the server crashed while handling the request (server side). 401: you need to log in or send valid credentials (client side). 201: success, something was created.

  1. Write Python to get the hostname and the value of page from https://news.example.in/search?q=cricket&page=3.
Show the answer
from urllib.parse import urlparse, parse_qs

parts = urlparse("https://news.example.in/search?q=cricket&page=3")
print(parts.hostname)
print(parse_qs(parts.query)["page"][0])
news.example.in
3

Query values are strings, so convert with int() if you need a number.

  1. A website has a valid padlock. Does that mean it's safe to enter your bank details?
Show the answer

No. The padlock only means the connection is encrypted and you're talking to the domain in the address bar. Scam sites can get certificates too. Check the domain is exactly your bank's, such as kaveribank.example for the made-up Kaveri Bank, and be wary of links from messages.

  1. Why is the #reviews part of a URL never sent to the server?
Show the answer

The fragment is only for the browser: it says which part of the page to scroll to. The server sends the whole page either way, so the browser keeps the fragment to itself.

Interview questions

What is the difference between HTTP and HTTPS?

HTTPS is HTTP over TLS. It encrypts traffic, protects it from tampering and authenticates the server with a certificate. HTTP sends everything in plain text. HTTPS uses port 443 by default; HTTP uses port 80.

What is the difference between GET and POST?

GET requests data, should not change anything on the server, and puts parameters in the URL, so responses can be cached and bookmarked. POST sends data in the request body to create or process something, isn't cached by default, and isn't safe to repeat blindly.

What does it mean that HTTP is stateless?

Each request is handled independently; the server keeps no memory of previous requests from the same client. Applications add state with cookies, sessions or tokens sent with each request.

Key takeaways

  • HTTP is a request–response conversation: the client asks, the server answers once.
  • A request has a method (GET, POST, PUT, PATCH, DELETE), a path, headers and sometimes a body.
  • A response has a status code, headers and a body; 2xx is success, 4xx is a client mistake, 5xx is a server failure.
  • Cookies let websites remember you, because HTTP itself is stateless.
  • HTTPS encrypts HTTP with TLS and proves the server's identity, but a padlock doesn't make a site honest.

Frequently asked questions

Is HTTP still used?

Plain HTTP is rare for real websites now; most redirect to HTTPS. It's still used inside private networks and while developing on your own computer, like http://localhost:8000.

What port does HTTPS use?

Port 443 by default, and HTTP uses port 80. Browsers add these automatically, which is why you rarely see a port in a URL.

What is a 404 error?

It means the server is working, but has nothing at the path you asked for. Usually the URL is mistyped, or the page was moved or deleted.

What to learn next

  1. See who handles each part of a request in frontend, backend and databases.
  2. Use HTTP from code in what is an API?
  3. Design HTTP APIs properly with REST API design.