URL Parsing API
The URL Parsing API in BanglaCode provides powerful tools for parsing, manipulating, and constructing URLs. Whether you're building APIs, handling query parameters, or working with web services, these functions make URL operations simple and reliable.
Quick Start
// Parse a URL
dhoro url = url_parse("https://api.example.com:8080/users?role=admin&page=2#results");
dekho("Protocol:", url.Protocol); // "https:"
dekho("Hostname:", url.Hostname); // "api.example.com"
dekho("Port:", url.Port); // "8080"
dekho("Pathname:", url.Pathname); // "/users"
dekho("Search:", url.Search); // "?role=admin&page=2"
dekho("Hash:", url.Hash); // "#results"
// Work with query parameters
dhoro params = url_query_params(url.Search);
dekho("Role:", url_query_get(params, "role")); // "admin"
dekho("Page:", url_query_get(params, "page")); // "2"Core Concepts
URL Object (ইউআরএল অবজেক্ট)
A URL object represents a parsed URL with all its components: protocol, hostname, port, pathname, query string, and hash. It provides structured access to each part of a URL for easy manipulation.
URLSearchParams (কোয়েরি প্যারামিটার)
URLSearchParams provides a convenient interface for working with URL query strings. It supports getting, setting, appending, and deleting parameters, making query string manipulation straightforward and error-free.
Query String Manipulation
Query strings encode key-value pairs in URLs (e.g., ?name=value&key=data). The API handles encoding/decoding automatically, supports multiple values per key, and provides methods to iterate over all parameters.
URL Encoding
Special characters in URLs must be encoded. The API automatically handles URL encoding when setting parameters, ensuring your URLs are always valid and safe to use in HTTP requests.
API Reference
url_parse(urlString)
Parses a URL string and returns a URL object with all its components.
Parameters:
urlString(string): The URL to parse
Returns:
URL object with properties:
Href: Full URL stringProtocol: Protocol scheme (e.g., "https:")Username: Username for authenticationPassword: Password for authenticationHostname: Domain name or IP addressPort: Port number (if specified)Host: Hostname + port (if present)Pathname: Path portion of the URLSearch: Query string (including "?")Hash: Fragment identifier (including "#")Origin: Protocol + hostname + port
dhoro url = url_parse("https://user:pass@api.example.com:8080/v1/users?active=true#top");
dekho(url.Href); // "https://user:pass@api.example.com:8080/v1/users?active=true#top"
dekho(url.Protocol); // "https:"
dekho(url.Username); // "user"
dekho(url.Password); // "pass"
dekho(url.Hostname); // "api.example.com"
dekho(url.Port); // "8080"
dekho(url.Host); // "api.example.com:8080"
dekho(url.Pathname); // "/v1/users"
dekho(url.Search); // "?active=true"
dekho(url.Hash); // "#top"
dekho(url.Origin); // "https://api.example.com:8080"url_query_params(queryStringOrURL)
Creates a URLSearchParams object from a query string or URL object.
Parameters:
queryStringOrURL(string or URL object): Query string (with or without "?") or URL object
Returns:
URLSearchParams object for manipulating query parameters
// From query string
dhoro params1 = url_query_params("?name=John&age=30");
dhoro params2 = url_query_params("name=John&age=30"); // Works without "?"
// From URL object
dhoro url = url_parse("https://api.com/users?role=admin");
dhoro params3 = url_query_params(url.Search);
// Empty params
dhoro params4 = url_query_params(""); // Create empty paramsurl_query_get(params, key)
Gets the value of a query parameter. Returns the first value if multiple exist.
Parameters:
params(URLSearchParams): The params objectkey(string): The parameter name
Returns:
String value of the parameter, or null if not found
dhoro params = url_query_params("?name=John&age=30&tag=js&tag=go");
dhoro name = url_query_get(params, "name"); // "John"
dhoro age = url_query_get(params, "age"); // "30"
dhoro tag = url_query_get(params, "tag"); // "js" (first value)
dhoro missing = url_query_get(params, "city"); // null
jodi (name != mittha) {
dekho("Name is:", name);
} nahole {
dekho("Name not found");
}url_query_set(params, key, value)
Sets a query parameter value. Replaces all existing values for that key.
Parameters:
params(URLSearchParams): The params objectkey(string): The parameter namevalue(string): The value to set
Returns:
None (modifies params in place)
dhoro params = url_query_params("?name=John&age=30");
// Set new parameter
url_query_set(params, "city", "Boston");
dekho(url_query_toString(params)); // "name=John&age=30&city=Boston"
// Replace existing parameter
url_query_set(params, "age", "31");
dekho(url_query_toString(params)); // "name=John&age=31&city=Boston"
// Set replaces all values if multiple exist
url_query_set(params, "tag", "first");
url_query_append(params, "tag", "second");
url_query_set(params, "tag", "only"); // Removes "first" and "second"
dekho(url_query_get(params, "tag")); // "only"url_query_append(params, key, value)
Appends a query parameter value. Allows multiple values for the same key.
Parameters:
params(URLSearchParams): The params objectkey(string): The parameter namevalue(string): The value to append
Returns:
None (modifies params in place)
dhoro params = url_query_params("?name=John");
// Append multiple values for same key
url_query_append(params, "tag", "javascript");
url_query_append(params, "tag", "golang");
url_query_append(params, "tag", "python");
dekho(url_query_toString(params));
// "name=John&tag=javascript&tag=golang&tag=python"
// Get only returns first value
dekho(url_query_get(params, "tag")); // "javascript"
// Get all values
dhoro allTags = url_query_values(params); // ["John", "javascript", "golang", "python"]url_query_delete(params, key)
Removes a query parameter and all its values.
Parameters:
params(URLSearchParams): The params objectkey(string): The parameter name to remove
Returns:
None (modifies params in place)
dhoro params = url_query_params("?name=John&age=30&city=Boston");
dekho(url_query_toString(params));
// "name=John&age=30&city=Boston"
// Delete a parameter
url_query_delete(params, "age");
dekho(url_query_toString(params));
// "name=John&city=Boston"
// Delete removes all values if multiple exist
url_query_append(params, "tag", "js");
url_query_append(params, "tag", "go");
url_query_delete(params, "tag"); // Removes both values
dekho(url_query_has(params, "tag")); // mitthaurl_query_has(params, key)
Checks if a query parameter exists.
Parameters:
params(URLSearchParams): The params objectkey(string): The parameter name to check
Returns:
Boolean: shotti (true) if parameter exists, mittha (false) otherwise
dhoro params = url_query_params("?name=John&age=30");
jodi (url_query_has(params, "name")) {
dekho("Name exists:", url_query_get(params, "name"));
}
jodi (url_query_has(params, "email")) {
dekho("Email exists");
} nahole {
dekho("Email not found"); // This will print
}
// Use for conditional logic
jodi (!url_query_has(params, "page")) {
url_query_set(params, "page", "1"); // Set default page
}url_query_keys(params)
Returns an array of all query parameter keys.
Parameters:
params(URLSearchParams): The params object
Returns:
Array of strings containing all parameter names (includes duplicates)
dhoro params = url_query_params("?name=John&age=30&city=Boston");
dhoro keys = url_query_keys(params);
dekho(keys); // ["name", "age", "city"]
// Iterate over keys
ghuriye (dhoro i = 0; i < dorghyo(keys); i = i + 1) {
dhoro key = keys[i];
dhoro value = url_query_get(params, key);
dekho(key, "=", value);
}
// Multiple values for same key
url_query_append(params, "tag", "js");
url_query_append(params, "tag", "go");
dhoro allKeys = url_query_keys(params);
// ["name", "age", "city", "tag", "tag"] - duplicates includedurl_query_values(params)
Returns an array of all query parameter values.
Parameters:
params(URLSearchParams): The params object
Returns:
Array of strings containing all parameter values
dhoro params = url_query_params("?name=John&age=30&city=Boston");
dhoro values = url_query_values(params);
dekho(values); // ["John", "30", "Boston"]
// Get all values including duplicates
url_query_append(params, "tag", "javascript");
url_query_append(params, "tag", "golang");
dhoro allValues = url_query_values(params);
// ["John", "30", "Boston", "javascript", "golang"]
// Iterate over values
ghuriye (dhoro i = 0; i < dorghyo(values); i = i + 1) {
dekho("Value", i, ":", values[i]);
}url_query_toString(params)
Converts URLSearchParams back to a query string.
Parameters:
params(URLSearchParams): The params object
Returns:
String: URL-encoded query string (without leading "?")
dhoro params = url_query_params("");
url_query_set(params, "name", "John Doe");
url_query_set(params, "age", "30");
url_query_set(params, "city", "New York");
dhoro queryString = url_query_toString(params);
dekho(queryString); // "name=John+Doe&age=30&city=New+York"
// Build complete URL
dhoro baseUrl = "https://api.example.com/users";
dhoro fullUrl = baseUrl + "?" + queryString;
dekho(fullUrl);
// "https://api.example.com/users?name=John+Doe&age=30&city=New+York"
// Special characters are automatically encoded
url_query_set(params, "search", "hello world & more");
dekho(url_query_toString(params));
// "name=John+Doe&age=30&city=New+York&search=hello+world+%26+more"Real-World Examples
Example 1: API Request Building with Query Parameters
Build API requests dynamically with filters, pagination, and sorting:
// Build API URL with dynamic filters
kaj buildAPIRequest(baseUrl, filters) {
dhoro params = url_query_params("");
// Add filters if provided
jodi (url_query_has(filters, "status")) {
url_query_set(params, "status", url_query_get(filters, "status"));
}
jodi (url_query_has(filters, "role")) {
url_query_set(params, "role", url_query_get(filters, "role"));
}
// Add pagination
dhoro page = url_query_has(filters, "page") ?
url_query_get(filters, "page") : "1";
dhoro limit = url_query_has(filters, "limit") ?
url_query_get(filters, "limit") : "20";
url_query_set(params, "page", page);
url_query_set(params, "limit", limit);
// Add sorting
jodi (url_query_has(filters, "sortBy")) {
url_query_set(params, "sortBy", url_query_get(filters, "sortBy"));
url_query_set(params, "order",
url_query_has(filters, "order") ?
url_query_get(filters, "order") : "asc"
);
}
dhoro queryString = url_query_toString(params);
ferao baseUrl + "?" + queryString;
}
// Usage
dhoro userFilters = url_query_params("?status=active&role=admin&page=2&sortBy=name");
dhoro apiUrl = buildAPIRequest("https://api.example.com/users", userFilters);
dekho(apiUrl);
// "https://api.example.com/users?status=active&role=admin&page=2&limit=20&sortBy=name&order=asc"
// Make API request
dhoro response = http_get(apiUrl);
dekho("Found", dorghyo(response.users), "users");Example 2: GitHub API URL Parsing and Manipulation
Parse and modify GitHub API URLs for repository operations:
// Parse GitHub repository URL
kaj analyzeGitHubURL(githubUrl) {
dhoro url = url_parse(githubUrl);
// Extract repository information
dhoro pathParts = bibhajan(url.Pathname, "/");
dhoro owner = pathParts[1];
dhoro repo = pathParts[2];
dekho("Repository:", owner + "/" + repo);
dekho("API Base:", url.Origin);
// Parse query parameters
dhoro params = url_query_params(url.Search);
jodi (url_query_has(params, "page")) {
dekho("Page:", url_query_get(params, "page"));
}
jodi (url_query_has(params, "per_page")) {
dekho("Per Page:", url_query_get(params, "per_page"));
}
// Build issues API URL
dhoro issuesParams = url_query_params("");
url_query_set(issuesParams, "state", "open");
url_query_set(issuesParams, "labels", "bug");
url_query_set(issuesParams, "sort", "created");
url_query_set(issuesParams, "direction", "desc");
dhoro issuesUrl = url.Origin + "/repos/" + owner + "/" + repo +
"/issues?" + url_query_toString(issuesParams);
dekho("Issues URL:", issuesUrl);
ferao issuesUrl;
}
// Usage
dhoro repoUrl = "https://api.github.com/repos/golang/go?page=1&per_page=30";
dhoro issuesEndpoint = analyzeGitHubURL(repoUrl);
// Repository: golang/go
// API Base: https://api.github.com
// Page: 1
// Per Page: 30
// Issues URL: https://api.github.com/repos/golang/go/issues?state=open&labels=bug&sort=created&direction=desc
// Fetch issues
dhoro response = http_get(issuesEndpoint);
dekho("Found", dorghyo(response), "open bug issues");Example 3: Search and Filter URL Construction
Build complex search URLs with multiple filters and tags:
// Build search URL with multiple filters
kaj buildSearchURL(searchTerm, tags, options) {
dhoro baseUrl = "https://example.com/search";
dhoro params = url_query_params("");
// Add search term (encoded automatically)
jodi (searchTerm != "" && searchTerm != mittha) {
url_query_set(params, "q", searchTerm);
}
// Add multiple tags
jodi (tags != mittha && dorghyo(tags) > 0) {
ghuriye (dhoro i = 0; i < dorghyo(tags); i = i + 1) {
url_query_append(params, "tag", tags[i]);
}
}
// Add optional filters
jodi (options != mittha) {
jodi (url_query_has(options, "category")) {
url_query_set(params, "category", url_query_get(options, "category"));
}
jodi (url_query_has(options, "minPrice")) {
url_query_set(params, "minPrice", url_query_get(options, "minPrice"));
}
jodi (url_query_has(options, "maxPrice")) {
url_query_set(params, "maxPrice", url_query_get(options, "maxPrice"));
}
jodi (url_query_has(options, "sortBy")) {
url_query_set(params, "sortBy", url_query_get(options, "sortBy"));
}
}
// Build final URL
dhoro queryString = url_query_toString(params);
ferao queryString != "" ? baseUrl + "?" + queryString : baseUrl;
}
// Usage 1: Simple search
dhoro url1 = buildSearchURL("laptop computers", mittha, mittha);
dekho(url1);
// "https://example.com/search?q=laptop+computers"
// Usage 2: Search with tags
dhoro tags = ["electronics", "computers", "portable"];
dhoro url2 = buildSearchURL("gaming laptop", tags, mittha);
dekho(url2);
// "https://example.com/search?q=gaming+laptop&tag=electronics&tag=computers&tag=portable"
// Usage 3: Full featured search
dhoro filters = url_query_params("?category=electronics&minPrice=500&maxPrice=2000&sortBy=price");
dhoro url3 = buildSearchURL("laptop", tags, filters);
dekho(url3);
// "https://example.com/search?q=laptop&tag=electronics&tag=computers&tag=portable&category=electronics&minPrice=500&maxPrice=2000&sortBy=price"
// Parse existing search URL to modify
dhoro existingUrl = url_parse(url3);
dhoro existingParams = url_query_params(existingUrl.Search);
// Modify filters
url_query_set(existingParams, "maxPrice", "1500");
url_query_delete(existingParams, "sortBy");
url_query_set(existingParams, "sortBy", "rating");
dhoro modifiedUrl = existingUrl.Origin + existingUrl.Pathname +
"?" + url_query_toString(existingParams);
dekho("Modified:", modifiedUrl);Best Practices
✅ DO: Always Validate URLs
Check that URLs are valid before parsing. Handle parsing errors gracefully and provide meaningful error messages to users.
✅ DO: Use url_query_has() Before Getting
Always check if a parameter exists before getting its value. This prevents null reference errors and makes your code more robust.
✅ DO: Let the API Handle Encoding
The API automatically encodes special characters in query parameters. Don't manually encode - let url_query_set() and url_query_append() handle it.
✅ DO: Use Append for Multiple Values
Use url_query_append() when you need multiple values for the same parameter (e.g., tags, filters). Use url_query_set() to replace all values.
❌ DON'T: Manually Build Query Strings
Never concatenate query strings manually with "&" and "=". Use URLSearchParams to ensure proper encoding and avoid injection vulnerabilities.
❌ DON'T: Assume Parameter Existence
Don't assume query parameters exist without checking. url_query_get() returns null for missing parameters - always handle this case.
❌ DON'T: Trust User Input URLs
Always validate and sanitize URLs from user input. Check the protocol, hostname, and parameters to prevent security issues like SSRF.
❌ DON'T: Modify URL Strings Directly
Don't use string manipulation to modify URLs. Parse the URL, modify the URLSearchParams, then reconstruct - this ensures correctness.
Performance Tips
Cache Parsed URLs
If you're parsing the same URL multiple times, cache the parsed result. URL parsing is relatively fast but caching can improve performance in tight loops.
Reuse URLSearchParams Objects
Create a URLSearchParams object once and modify it as needed rather than creating new ones. This is more efficient for building multiple similar URLs.
Batch Parameter Operations
When setting multiple parameters, do all operations before calling url_query_toString(). Convert to string only once at the end.
Avoid Redundant Parsing
Don't parse a URL, convert it to string, and parse it again. Keep the parsed objects in memory and only convert to strings when needed for HTTP requests.
Minimize Query String Size
Keep query strings concise. Use short parameter names and remove unnecessary parameters. Large query strings can impact performance and may hit browser/server limits.
Common Patterns
Pattern 1: URL Builder Helper
// Reusable URL builder
kaj URLBuilder(baseUrl) {
dhoro params = url_query_params("");
ferao {
setParam: kaj(key, value) {
url_query_set(params, key, value);
ferao ei; // Return self for chaining
},
appendParam: kaj(key, value) {
url_query_append(params, key, value);
ferao ei;
},
removeParam: kaj(key) {
url_query_delete(params, key);
ferao ei;
},
build: kaj() {
dhoro queryString = url_query_toString(params);
ferao queryString != "" ? baseUrl + "?" + queryString : baseUrl;
}
};
}
// Usage with method chaining
dhoro url = URLBuilder("https://api.example.com/users")
.setParam("status", "active")
.setParam("role", "admin")
.setParam("page", "1")
.appendParam("tag", "verified")
.appendParam("tag", "premium")
.build();
dekho(url);
// "https://api.example.com/users?status=active&role=admin&page=1&tag=verified&tag=premium"Pattern 2: Query Parameter Merger
// Merge query parameters from multiple sources
kaj mergeQueryParams(params1, params2) {
dhoro merged = url_query_params("");
// Add all from first params
dhoro keys1 = url_query_keys(params1);
dhoro values1 = url_query_values(params1);
ghuriye (dhoro i = 0; i < dorghyo(keys1); i = i + 1) {
url_query_append(merged, keys1[i], values1[i]);
}
// Add all from second params (may override)
dhoro keys2 = url_query_keys(params2);
dhoro values2 = url_query_values(params2);
ghuriye (dhoro i = 0; i < dorghyo(keys2); i = i + 1) {
// Use set to override, or append to add multiple
url_query_set(merged, keys2[i], values2[i]);
}
ferao merged;
}
// Usage
dhoro defaultParams = url_query_params("?limit=20&sort=asc");
dhoro userParams = url_query_params("?page=5&filter=active");
dhoro finalParams = mergeQueryParams(defaultParams, userParams);
dekho(url_query_toString(finalParams));
// "limit=20&sort=asc&page=5&filter=active"Pattern 3: URL Router
// Route handler based on URL path and params
kaj routeRequest(urlString) {
dhoro url = url_parse(urlString);
dhoro path = url.Pathname;
dhoro params = url_query_params(url.Search);
// Route based on path
jodi (path == "/api/users") {
// Handle users endpoint
dhoro page = url_query_has(params, "page") ?
url_query_get(params, "page") : "1";
dhoro limit = url_query_has(params, "limit") ?
url_query_get(params, "limit") : "20";
ferao handleUsers(page, limit, params);
} nahole jodi (path == "/api/products") {
// Handle products endpoint
dhoro category = url_query_get(params, "category");
dhoro minPrice = url_query_get(params, "minPrice");
dhoro maxPrice = url_query_get(params, "maxPrice");
ferao handleProducts(category, minPrice, maxPrice);
} nahole jodi (khuje(path, "/api/users/") == 0) {
// Handle specific user by ID
dhoro pathParts = bibhajan(path, "/");
dhoro userId = pathParts[3];
ferao handleUserById(userId, params);
}
ferao {status: 404, message: "Route not found"};
}
// Helper functions
kaj handleUsers(page, limit, params) {
dhoro filters = [];
jodi (url_query_has(params, "status")) {
joro(filters, "status=" + url_query_get(params, "status"));
}
jodi (url_query_has(params, "role")) {
joro(filters, "role=" + url_query_get(params, "role"));
}
dekho("Fetching users: page=" + page + ", limit=" + limit);
dekho("Filters:", joro(filters, ", "));
ferao {status: 200, data: "users list"};
}
// Usage
dhoro result = routeRequest("https://api.com/api/users?page=2&status=active&role=admin");
dekho(result);Pattern 4: Pagination Helper
// Build paginated URLs
kaj buildPaginationURLs(currentUrl, totalPages) {
dhoro url = url_parse(currentUrl);
dhoro params = url_query_params(url.Search);
dhoro currentPage = url_query_has(params, "page") ?
text_shongkha(url_query_get(params, "page")) : 1;
dhoro baseUrl = url.Origin + url.Pathname;
// Build URL for specific page
dhoro buildPageUrl = kaj(pageNum) {
dhoro newParams = url_query_params(url.Search);
url_query_set(newParams, "page", shongkha_text(pageNum));
ferao baseUrl + "?" + url_query_toString(newParams);
};
dhoro urls = {
first: buildPageUrl(1),
prev: currentPage > 1 ? buildPageUrl(currentPage - 1) : mittha,
current: currentUrl,
next: currentPage < totalPages ? buildPageUrl(currentPage + 1) : mittha,
last: buildPageUrl(totalPages)
};
ferao urls;
}
// Usage
dhoro currentUrl = "https://api.com/users?status=active&page=3&limit=20";
dhoro pagination = buildPaginationURLs(currentUrl, 10);
dekho("First:", pagination.first);
dekho("Previous:", pagination.prev);
dekho("Next:", pagination.next);
dekho("Last:", pagination.last);Related APIs
Summary
The URL Parsing API in BanglaCode provides comprehensive tools for working with URLs and query parameters. Whether you're building web APIs, parsing external URLs, or constructing complex query strings, these functions make URL operations safe, reliable, and easy.
Key benefits:
- Complete URL Parsing: Extract all components from any URL string
- Safe Query Handling: Automatic encoding/decoding prevents injection attacks
- Flexible Parameters: Support for single and multiple values per key
- Easy Manipulation: Simple API for getting, setting, and deleting parameters
- API Integration: Perfect for building REST API clients and web services
Use the URL Parsing API whenever you need to work with web addresses, build API requests, handle query parameters, or route requests based on URL patterns. Combined with the HTTP API, it provides everything you need for web and API development.