URL Encode and Decode

Est. read: 6 minDeveloper
Percent-encoded characters in a URL query string

Summary

Definition: Percent-encoding replaces bytes with %XX to make URLs unambiguous.

Why it matters: Correct encoding prevents broken parsing and API errors.

Pitfall: Encoding the wrong URL component changes meaning.

Key terms
Percent-encoding
Representing bytes as %XX hex values.
Unreserved
A-Z a-z 0-9 - . _ ~, never encoded.
Reserved
Characters with special meaning in URLs.
Query string
URL part after ? with key=value pairs.
Form encoding
application/x-www-form-urlencoded rules.

Encoding rules at a glance

Encode rules
Unreserved
Never encode.
Reserved
Encode only if meaning changes.
Other bytes
Always percent-encode.

Encoding rules differ by URL component such as path, query, or fragment.

Query strings and APIs

Encode each query key and value separately. Reserved characters like & and = must be encoded inside values.

Common mix-up: URL encoding is not encryption. It only preserves meaning during transport.

application/x-www-form-urlencoded

Definitions
Plus sign
Represents space in form-encoded data.

The + to space rule applies only to form encoding, not to all URLs.

UTF-8 and non-ASCII characters

Characters are first encoded as UTF-8 bytes, then each byte is percent-encoded.
This matters for non-ASCII input like emojis or accented characters.

Quick example

Example

Encode keys and values, then join with separators.

Query string
search=encrypt online&tag=dev+ops
search=encrypt%20online&tag=dev%2Bops

Incorrect vs correct

Example

Encoding the full URL changes its structure.

Do not encode whole URL
https://api.example.com/search?q=foo bar
https%3A%2F%2Fapi.example.com%2Fsearch%3Fq%3Dfoo%20bar
Example

Only encode the query value.

Correct encoding
https://api.example.com/search?q=foo%20bar

Practical check

Practical check
  • Encode each key and value separately.
  • Confirm unreserved characters stay readable.
  • Decode exactly once after validation.

Never decode user input before validation; decoding can change separators and meaning.