Part 03 · The Language of the Web

URLs, Path and Query Parameters

URLParams

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

PartQuestion it answersExample
SchemeWhich protocol?https
Host and portWhich machine and program?shop.com:8443
PathWhich resource?/search/shoes, /orders/42
QueryWith which options??q=red&page=2
FragmentWhere 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.

https://shop.com:8443/search/shoes?q=red&page=2#reviewshttpsschemeshop.com:8443host : port/search/shoespath: which thingq=red&page=2query: options#reviewsfragmentsent to the serverGET /search/shoes?q=red&page=2 + Hostbrowser onlyscrolls the page
A URL is cut into its parts: the scheme https, the host and port shop.com:8443, the path /search/shoes that says which thing, the query q=red&page=2 with options, and the fragment #reviews. The scheme, host, path and query are used to send the request to the server. The fragment never leaves the browser; it only scrolls the page.

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

  1. 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.
  2. Port defaults: 443 for https, 80 for http. https://shop.com/ and https://shop.com:443/ are the same place.
  3. 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.
  4. The query adds options. key=value pairs 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.
  5. 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.
  6. 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 %XX in hex. রহিম becomes 12 bytes: %E0%A6%B0%E0%A6%B9%E0%A6%BF%E0%A6%AE.
  7. Space has two spellings. %20 everywhere, and + inside query strings that use the form encoding (application/x-www-form-urlencoded). In a path, + is a literal plus sign.
  8. 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.
  9. 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.
Predict first

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

Step through it

From the address bar to the handler's arguments

BrowserRequest lineRouterHandler

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?

Try each case

Good URL or broken?

GET /users/7/orders?status=paid&sort=-created_at&page=2
works: The path says which collection (user 7's orders), the query says how to filter, sort and page it.

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))
}

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%20shoes in the path decoded to red shoes, one segment. Had the space been a raw /, it would have been two segments.
  • q is 12 encoded bytes that decode to রহিম: 4 Bangla characters, 3 bytes each.
  • tag appears twice, and the second value b+c decoded to b 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
  • #reviews is gone: curl, like a browser, never sends the fragment.
  • curl wrote spaces as + and hex in lowercase (%2f, %e0), where our encoder wrote %20 and uppercase. Both are valid; a correct decoder treats %2f and %2F the same, and + as a space in queries.

Real engineering

  • Never build URLs by string concatenation. Use your language's URL builder (url.Values in Go, URLSearchParams in JavaScript, urllib.parse.urlencode in 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 Referer headers. Use headers or bodies.
  • Normalise for caching. ?a=1&b=2 and ?b=2&a=1 are usually the same request but different cache keys. CDNs can sort or ignore parameters; tracking parameters like utm_* 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

Try each case

Pick a failure

GET /search?q=C++
breaks: In a query string, + means space, so q decoded to 'C '. Encode the value: q=C%2B%2B.

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:

  • base is like https://shop.com, pathSegments a list like ["files", "annual report.pdf"], params an 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 →