python 42 lines · 7 steps

Validating URLs into a safe endpoint in Python

Parse a raw URL string and reject anything unsupported before returning a clean, typed endpoint.

Explained by highlit
1from urllib.parse import urlparse, parse_qs
2from dataclasses import dataclass, field
3 
4ALLOWED_SCHEMES = {"http", "https"}
5 
6 
7@dataclass
8class ParsedEndpoint:
9 scheme: str
10 host: str
11 port: int
12 path: str
13 query: dict[str, list[str]] = field(default_factory=dict)
14 
15 
16def parse_endpoint(raw: str) -> ParsedEndpoint:
17 parts = urlparse(raw.strip())
18 
19 if parts.scheme not in ALLOWED_SCHEMES:
20 raise ValueError(f"unsupported scheme: {parts.scheme!r}")
21 
22 if not parts.hostname:
23 raise ValueError("missing host")
24 
25 try:
26 port = parts.port or (443 if parts.scheme == "https" else 80)
27 except ValueError as exc:
28 raise ValueError("invalid port") from exc
29 
30 if not (0 < port < 65536):
31 raise ValueError(f"port out of range: {port}")
32 
33 if parts.username or parts.password:
34 raise ValueError("credentials in URL are not allowed")
35 
36 return ParsedEndpoint(
37 scheme=parts.scheme,
38 host=parts.hostname.lower(),
39 port=port,
40 path=parts.path or "/",
41 query=parse_qs(parts.query, keep_blank_values=True),
42 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Validate every part of untrusted input explicitly rather than trusting the parser's defaults.
  2. 2A dataclass gives you a typed, self-documenting result once validation passes.
  3. 3Normalizing values like host casing and default ports produces predictable, comparable output.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating URLs into a safe endpoint in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code