Part 03 · The Language of the Web
URLs, Path and Query Parameters
How a URL is built, and when data belongs in the path versus the query string.
⏱ 1 hours · Station 32 of 153
The search that broke on "&"
A shop's search box works fine until someone searches for "salt & pepper". The results page shows salt, but nothing with pepper. Another user searches in Bangla, "রহিম", and gets an error page.
The frontend built the URL by gluing strings together: "/search?q=" + text. So the server received /search?q=salt & pepper, and read it as q=salt plus a second, empty parameter called pepper. The Bangla text was sent as raw bytes that some proxy in between refused.
A URL looks like simple text, but it's a small language with strict rules: which characters mean "a new part starts here", and how everything else must be encoded. Get it wrong and requests silently mean something else. This lesson takes a URL apart, piece by piece, and shows when data belongs in the path and when in the query.
The problem: one line of text must carry many things
| Part | Question it answers | Example |
|---|---|---|
| Scheme | Which protocol? | https |
| Host and port | Which machine and program? | shop.com:8443 |
| Path | Which resource? | /search/shoes, /orders/42 |
| Query | With which options? | ?q=red&page=2 |
| Fragment | Where on the page? (browser only) | #reviews |
All of that is squeezed into one string, using special characters as separators: : / ? # & =. The trouble starts when the data itself contains those characters, or isn't ASCII at all.
Think of a postal address
A full address on an envelope:
- Country and city (scheme and host): which system and which building.
- Street and flat number (path): which exact place. It's part of the identity: flat 4B is a different place from flat 5A.
- "Leave with the guard, after 5 pm" (query): instructions about how, not which. The same flat, delivered differently.
- "Read the second page first" (fragment): a note for the person reading the letter; the postman ignores it.
If someone's name contains a comma and you write it on the envelope as is, the sorting machine may think the address has an extra line. So you write it in a safe form. That's percent-encoding.
Where the analogy stops working. A postman can guess what a smudged address meant. A URL parser can't: it splits on the separator characters exactly, so an unencoded & or # inside your data really does end the value there. And parts of a URL are case-sensitive (the path and query usually are; the scheme and host aren't).
The building blocks
- The shape:
scheme://[user@]host[:port]/path[?query][#fragment]. Parsers split from the outside in: scheme first, then cut off the fragment at#, then the query at?, then the authority (user, host, port) from the path. - Port defaults: 443 for https, 80 for http.
https://shop.com/andhttps://shop.com:443/are the same place. - The path identifies the resource. It's a list of segments separated by
/:/orders/42/items. Routers match on it (/orders/{id}). Put identity here: which order, which user. - The query adds options.
key=valuepairs separated by&: filters, sorting, pagination, search text (lesson 14). Keys can repeat (tag=a&tag=b), and order usually doesn't matter. Put how here: which page, which sort, which filter. - The fragment stays in the browser. Everything after
#is never sent to the server. It's for scrolling to a section or for single-page apps' client-side state. - Percent-encoding. Only a small set of characters can appear as they are: letters, digits and
- . _ ~("unreserved"). Everything else, including space,&,/,?,#,%and every non-ASCII character, is written as its UTF-8 bytes, each as%XXin hex.রহিমbecomes 12 bytes:%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE. - Space has two spellings.
%20everywhere, and+inside query strings that use the form encoding (application/x-www-form-urlencoded). In a path,+is a literal plus sign. - Encode each piece, not the whole URL. Encode a value before putting it into the path or query. Encoding the finished URL would also encode the
/,?and&that are supposed to be separators. - Length limits are real. No official maximum, but browsers, proxies and servers commonly cap URLs at a few KB to 8 KB. Big inputs go in a request body.
A frontend builds a link with "/search?q=" + text, and the user types: shoes #1 sale. What does the server receive as q?
Behind the scenes: a router reads a URL
From the address bar to the handler's arguments
Step 1/6 The browser drops the fragment
You open https://shop.com/products/12?color=red&size=M#reviews. The #reviews part stays in the browser.
- kept
- #reviews (browser only)
The picture to keep in your head
A URL is an address with instructions:
- Path = which thing. Nouns that identify a resource:
/users/7/orders/42. - Query = how you want it. Options that filter, sort or page:
?status=paid&page=2. - Fragment = a note to the browser. Never reaches the server.
- Every value is encoded before it goes in, so data can never be mistaken for a separator.
Try it: is this URL well built?
Good URL or broken?
GET /users/7/orders?status=paid&sort=-created_at&page=2
Code from first principles
A URL parser and percent-encoder written by hand. It splits a URL from the outside in, decodes each path segment and query value (with + meaning space only in the query), notes that the fragment never reaches the server, and then encodes a tricky value and decodes it back.
package main
import (
"fmt"
"strconv"
"strings"
)
// encode percent-encodes a value: unreserved characters stay, every other UTF-8 byte becomes %XX.
func encode(s string) string {
var b strings.Builder
for i := 0; i < len(s); i++ {
c := s[i]
if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.IndexByte("-._~", c) >= 0 {
b.WriteByte(c)
} else {
fmt.Fprintf(&b, "%%%02X", c)
}
}
return b.String()
}
// decode turns %XX back into bytes. In a query string, '+' also means a space.
func decode(s string, plusIsSpace bool) string {
var out []byte
for i := 0; i < len(s); i++ {
switch {
case s[i] == '%' && i+2 < len(s):
v, _ := strconv.ParseUint(s[i+1:i+3], 16, 8)
out = append(out, byte(v))
i += 2
case s[i] == '+' && plusIsSpace:
out = append(out, ' ')
default:
out = append(out, s[i])
}
}
return string(out)
}
func main() {
url := "https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews"
fmt.Println("url: " + url)
// Split from the outside in: scheme, then fragment, then query, then authority and path.
scheme, rest, _ := strings.Cut(url, "://")
rest, fragment, _ := strings.Cut(rest, "#")
rest, query, _ := strings.Cut(rest, "?")
authority, path, _ := strings.Cut(rest, "/")
path = "/" + path
user, hostPort, found := strings.Cut(authority, "@")
if !found {
user, hostPort = "", authority
}
host, port, found := strings.Cut(hostPort, ":")
if !found {
port = map[string]string{"http": "80", "https": "443"}[scheme] + " (default)"
}
fmt.Printf("scheme: %s\nuser: %s\nhost: %s\nport: %s\n", scheme, user, host, port)
segments := []string{}
for _, seg := range strings.Split(strings.Trim(path, "/"), "/") {
segments = append(segments, "'"+decode(seg, false)+"'")
}
fmt.Printf("path: %s -> segments %s\n", path, strings.Join(segments, ", "))
fmt.Println("query:")
for _, pair := range strings.Split(query, "&") {
k, v, _ := strings.Cut(pair, "=")
fmt.Printf(" %s = '%s'\n", decode(k, true), decode(v, true))
}
fmt.Printf("fragment: %s (never sent to the server)\n", fragment)
value := "red & blue/রহিম?"
fmt.Printf("encode '%s' -> %s\n", value, encode(value))
fmt.Printf("decode it back -> '%s'\n", decode(encode(value), true))
}// encode percent-encodes a value: unreserved characters stay, every other UTF-8 byte becomes %XX.
function encode(s) {
let out = "";
for (const byte of Buffer.from(s, "utf8")) {
const c = String.fromCharCode(byte);
if (/[A-Za-z0-9\-._~]/.test(c)) out += c;
else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
}
return out;
}
// decode turns %XX back into bytes. In a query string, '+' also means a space.
function decode(s, plusIsSpace) {
const bytes = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "%" && i + 2 < s.length) {
bytes.push(parseInt(s.slice(i + 1, i + 3), 16));
i += 2;
} else if (s[i] === "+" && plusIsSpace) bytes.push(32);
else bytes.push(s.charCodeAt(i));
}
return Buffer.from(bytes).toString("utf8");
}
// cut splits at the first sep, like Go's strings.Cut: [before, after, found].
function cut(s, sep) {
const i = s.indexOf(sep);
return i < 0 ? [s, "", false] : [s.slice(0, i), s.slice(i + sep.length), true];
}
const url = "https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews";
console.log("url: " + url);
// Split from the outside in: scheme, then fragment, then query, then authority and path.
let [scheme, rest] = cut(url, "://");
let fragment, query, authority, path;
[rest, fragment] = cut(rest, "#");
[rest, query] = cut(rest, "?");
[authority, path] = cut(rest, "/");
path = "/" + path;
let [user, hostPort, hasUser] = cut(authority, "@");
if (!hasUser) [user, hostPort] = ["", authority];
let [host, port, hasPort] = cut(hostPort, ":");
if (!hasPort) port = { http: "80", https: "443" }[scheme] + " (default)";
console.log(`scheme: ${scheme}\nuser: ${user}\nhost: ${host}\nport: ${port}`);
const segments = path.replace(/^\/+|\/+$/g, "").split("/").map((seg) => `'${decode(seg, false)}'`);
console.log(`path: ${path} -> segments ${segments.join(", ")}`);
console.log("query:");
for (const pair of query.split("&")) {
const [k, v] = cut(pair, "=");
console.log(` ${decode(k, true)} = '${decode(v, true)}'`);
}
console.log(`fragment: ${fragment} (never sent to the server)`);
const value = "red & blue/রহিম?";
console.log(`encode '${value}' -> ${encode(value)}`);
console.log(`decode it back -> '${decode(encode(value), true)}'`);// encode percent-encodes a value: unreserved characters stay, every other UTF-8 byte becomes %XX.
fn encode(s: &str) -> String {
let mut out = String::new();
for &b in s.as_bytes() {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
// decode turns %XX back into bytes. In a query string, '+' also means a space.
fn decode(s: &str, plus_is_space: bool) -> String {
let bytes = s.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
out.push(u8::from_str_radix(&s[i + 1..i + 3], 16).unwrap());
i += 3;
continue;
}
out.push(if bytes[i] == b'+' && plus_is_space { b' ' } else { bytes[i] });
i += 1;
}
String::from_utf8(out).unwrap()
}
fn main() {
let url = "https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews";
println!("url: {url}");
// Split from the outside in: scheme, then fragment, then query, then authority and path.
let (scheme, rest) = url.split_once("://").unwrap();
let (rest, fragment) = rest.split_once('#').unwrap_or((rest, ""));
let (rest, query) = rest.split_once('?').unwrap_or((rest, ""));
let (authority, path) = rest.split_once('/').unwrap_or((rest, ""));
let path = format!("/{path}");
let (user, host_port) = authority.split_once('@').unwrap_or(("", authority));
let (host, port) = match host_port.split_once(':') {
Some((h, p)) => (h, p.to_string()),
None => (host_port, format!("{} (default)", if scheme == "http" { "80" } else { "443" })),
};
println!("scheme: {scheme}\nuser: {user}\nhost: {host}\nport: {port}");
let segments: Vec<String> = path.trim_matches('/').split('/').map(|seg| format!("'{}'", decode(seg, false))).collect();
println!("path: {path} -> segments {}", segments.join(", "));
println!("query:");
for pair in query.split('&') {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
println!(" {} = '{}'", decode(k, true), decode(v, true));
}
println!("fragment: {fragment} (never sent to the server)");
let value = "red & blue/রহিম?";
println!("encode '{value}' -> {}", encode(value));
println!("decode it back -> '{}'", decode(&encode(value), true));
}def encode(s):
"""Percent-encode a value: unreserved characters stay, every other UTF-8 byte becomes %XX."""
out = ""
for byte in s.encode("utf-8"):
c = chr(byte)
if c.isascii() and (c.isalnum() or c in "-._~"):
out += c
else:
out += f"%{byte:02X}"
return out
def decode(s, plus_is_space):
"""Turn %XX back into bytes. In a query string, '+' also means a space."""
out = bytearray()
i = 0
while i < len(s):
if s[i] == "%" and i + 2 < len(s):
out.append(int(s[i + 1 : i + 3], 16))
i += 3
continue
out.append(ord(" ") if s[i] == "+" and plus_is_space else ord(s[i]))
i += 1
return out.decode("utf-8")
url = "https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews"
print("url: " + url)
# Split from the outside in: scheme, then fragment, then query, then authority and path.
scheme, _, rest = url.partition("://")
rest, _, fragment = rest.partition("#")
rest, _, query = rest.partition("?")
authority, _, path = rest.partition("/")
path = "/" + path
user, found, host_port = authority.partition("@")
if not found:
user, host_port = "", authority
host, found, port = host_port.partition(":")
if not found:
port = {"http": "80", "https": "443"}[scheme] + " (default)"
print(f"scheme: {scheme}\nuser: {user}\nhost: {host}\nport: {port}")
segments = [f"'{decode(seg, False)}'" for seg in path.strip("/").split("/")]
print(f"path: {path} -> segments {', '.join(segments)}")
print("query:")
for pair in query.split("&"):
k, _, v = pair.partition("=")
print(f" {decode(k, True)} = '{decode(v, True)}'")
print(f"fragment: {fragment} (never sent to the server)")
value = "red & blue/রহিম?"
print(f"encode '{value}' -> {encode(value)}")
print(f"decode it back -> '{decode(encode(value), True)}'")import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
// encode percent-encodes a value: unreserved characters stay, every other UTF-8 byte becomes %XX.
static String encode(String s) {
StringBuilder out = new StringBuilder();
for (byte raw : s.getBytes(StandardCharsets.UTF_8)) {
int b = raw & 0xFF;
char c = (char) b;
if (b < 128 && (Character.isLetterOrDigit(c) || "-._~".indexOf(c) >= 0)) out.append(c);
else out.append(String.format("%%%02X", b));
}
return out.toString();
}
// decode turns %XX back into bytes. In a query string, '+' also means a space.
static String decode(String s, boolean plusIsSpace) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '%' && i + 2 < s.length()) {
out.write(Integer.parseInt(s.substring(i + 1, i + 3), 16));
i += 2;
} else out.write(c == '+' && plusIsSpace ? ' ' : c);
}
return out.toString(StandardCharsets.UTF_8);
}
// cut splits at the first sep, like Go's strings.Cut: {before, after} or null if not found.
static String[] cut(String s, String sep) {
int i = s.indexOf(sep);
return i < 0 ? null : new String[] {s.substring(0, i), s.substring(i + sep.length())};
}
public static void main(String[] args) {
String url = "https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews";
System.out.println("url: " + url);
// Split from the outside in: scheme, then fragment, then query, then authority and path.
String[] p = cut(url, "://");
String scheme = p[0], rest = p[1];
p = cut(rest, "#");
rest = p[0];
String fragment = p[1];
p = cut(rest, "?");
rest = p[0];
String query = p[1];
p = cut(rest, "/");
String authority = p[0], path = "/" + p[1];
p = cut(authority, "@");
String user = p == null ? "" : p[0], hostPort = p == null ? authority : p[1];
p = cut(hostPort, ":");
String host = p == null ? hostPort : p[0];
String port = p != null ? p[1] : (scheme.equals("http") ? "80" : "443") + " (default)";
System.out.printf("scheme: %s%nuser: %s%nhost: %s%nport: %s%n", scheme, user, host, port);
StringJoiner segments = new StringJoiner(", ");
for (String seg : path.replaceAll("^/+|/+$", "").split("/")) segments.add("'" + decode(seg, false) + "'");
System.out.println("path: " + path + " -> segments " + segments);
System.out.println("query:");
for (String pair : query.split("&")) {
String[] kv = cut(pair, "=");
System.out.println(" " + decode(kv[0], true) + " = '" + decode(kv[1], true) + "'");
}
System.out.println("fragment: " + fragment + " (never sent to the server)");
String value = "red & blue/রহিম?";
System.out.println("encode '" + value + "' -> " + encode(value));
System.out.println("decode it back -> '" + decode(encode(value), true) + "'");
}
}Output (the same in all five languages):
url: https://[email protected]:8443/search/red%20shoes?q=%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE&page=2&tag=a&tag=b+c#reviews
scheme: https
user: rahim
host: shop.com
port: 8443
path: /search/red%20shoes -> segments 'search', 'red shoes'
query:
q = 'রহিম'
page = '2'
tag = 'a'
tag = 'b c'
fragment: reviews (never sent to the server)
encode 'red & blue/রহিম?' -> red%20%26%20blue%2F%E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE%3F
decode it back -> 'red & blue/রহিম?'
Reading the output:
- The parts came out in the order the parser cut them: scheme at
://, fragment at#, query at?, path at the first/, user at@, port at:. red%20shoesin the path decoded tored shoes, one segment. Had the space been a raw/, it would have been two segments.qis 12 encoded bytes that decode toরহিম: 4 Bangla characters, 3 bytes each.tagappears twice, and the second valueb+cdecoded tob c, because+means space in a query string.- Encoding
red & blue/রহিম?turned the space,&,/,?and every Bangla byte into%XX, so none of them can be mistaken for a separator. Decoding gives back the exact text.
And here's what a real client sends. curl --data-urlencode encodes values for you, and a plain nc listener shows the request line that arrived:
$ nc -l 127.0.0.1 8097 > cap1.txt &
$ curl -s -G --data-urlencode 'q=red & blue/রহিম?' --data-urlencode 'page=2' 'http://localhost:8097/search#reviews'
$ head -2 cap1.txt | tr -d '\r'
GET /search?q=red+%26+blue%2f%e0%a6%b0%e0%a6%b9%e0%a6%bf%e0%a6%ae%3f&page=2 HTTP/1.1
Host: localhost:8097
#reviewsis gone: curl, like a browser, never sends the fragment.- curl wrote spaces as
+and hex in lowercase (%2f,%e0), where our encoder wrote%20and uppercase. Both are valid; a correct decoder treats%2fand%2Fthe same, and+as a space in queries.
Real engineering
- Never build URLs by string concatenation. Use your language's URL builder (
url.Valuesin Go,URLSearchParamsin JavaScript,urllib.parse.urlencodein Python) so every value is encoded. - Validate path parameters.
/orders/{id}gives you a string; check it's a valid ID before using it. Watch for path traversal (../) when a path segment is used as a file name. - Keep secrets out of URLs. Tokens, passwords and personal data in query strings leak into logs, browser history, analytics and
Refererheaders. Use headers or bodies. - Normalise for caching.
?a=1&b=2and?b=2&a=1are usually the same request but different cache keys. CDNs can sort or ignore parameters; tracking parameters likeutm_*are often stripped. - Pick conventions: lowercase paths, hyphens over underscores (
/order-items), plural nouns for collections (/orders), no trailing-slash ambiguity (redirect one form to the other). - Stay well under length limits. If a filter can grow without bound (hundreds of IDs), accept it as a POST body (
POST /orders/search).
When it breaks
Pick a failure
GET /search?q=C++
Think before you read on
GET /users/7 and GET /users?id=7 can both return user 7. Your teammate says it doesn't matter which one you pick. When does it actually matter?
Reveal
/users/7 names one resource; /users?id=7 is a search over the collection that happens to match one. It matters for: status codes (a missing /users/7 is 404, while a search with no matches is usually 200 with an empty list), caching and logging (paths group cleanly in metrics; queries vary), routing and permissions (it's easy to protect /users/{id} per user), and REST design (lesson 12): URLs that name things are guessable and stable. Use the path for identity and the query for filtering.
Check yourself
1. Name the parts of a URL in order.
Answer
Scheme, optional user info, host, optional port, path, optional query (after ?), optional fragment (after #).
2. Which part of a URL is never sent to the server, and what is it for?
Answer
The fragment, everything after #. It's used by the browser to scroll to a section or by single-page apps for client-side state.
3. How is রহিম written in a URL, and why?
Answer
As the percent-encoded UTF-8 bytes %E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE. Only unreserved ASCII characters may appear as they are; every other byte must be written as %XX so it can't be confused with separators and travels safely through every system.
4. What should go in the path, and what in the query?
Answer
The path identifies the resource (which order, which user). The query carries options about how you want it (filters, sorting, pagination, search terms).
Your challenge: build URLs safely
Write a buildURL(base, pathSegments, params) function:
baseis likehttps://shop.com,pathSegmentsa list like["files", "annual report.pdf"],paramsan ordered list of key/value pairs (keys may repeat).- Encode each path segment (so
/inside a segment becomes%2F) and each query key and value, join with/,&and=, and add?only if there are params. - Feed the result back into the parser from this lesson.
Before you run it, predict what buildURL("https://shop.com", ["search", "a/b"], [["q", "salt & pepper"], ["tag", "x"], ["tag", "y"]]) produces.
You've succeeded when parsing your built URL gives back exactly the segments 'search', 'a/b' and the query values 'salt & pepper', 'x', 'y', for any input you try, including Bangla text and #.
The mental model
A URL is an address with instructions, in a strict little language: scheme and host say where, the path says which resource, the query says how you want it, and the fragment is a note for the browser that never reaches the server. Separators (: / ? # & =) give it structure, so every piece of data must be percent-encoded as UTF-8 bytes before it goes in. Build URLs with a proper builder, put identity in the path and options in the query, and keep secrets out entirely.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →