w3resource

Uniform Resource Locator (URL): A Beginner’s Guide


Uniform Resource Locator: Your Guide to Web Addresses

What is a Uniform Resource Locator (URL)?

A Uniform Resource Locator (URL) is a web address used to locate resources on the internet. Whether it’s a website, file, or API, the URL specifies its location and how to access it.

For instance, in the URL https://example.com/page, the browser knows where to go (example.com) and what resource to request (/page).


Structure of a URL

A URL consists of several components that work together:

    1. Scheme/Protocol: Specifies the communication method, e.g., http or https.

    2. Domain/Host: The name or IP address of the server, e.g., example.com.

    3. Port: (Optional) Defines the server port, e.g., :80.

    4. Path: The specific resource location on the server, e.g., /about.

    5. Query Parameters: (Optional) Provides additional information, e.g., ?id=123.

    6. Fragment: (Optional) A reference to a specific section of the page, e.g., #section1.

Example:

https://example.com:8080/page?id=123#section1


Why do we use URLs?

    1. Resource Identification: Easily locate and access web resources.

    2. Universal Access: URLs work across all internet-connected devices.

    3. API Interaction: Simplify communication between applications.

Advantages of URLs

  • Simplicity: Easy for users and systems to understand.
  • Global Standard: Recognized and supported worldwide.
  • Versatility: Works with websites, APIs, multimedia, and more.
  • Shareability: Can be easily shared and reused.

Where are URLs used?

    1. Web Browsing: Navigate to websites.

    2. APIs: Access endpoints for data exchange.

    3. IoT Devices: Connect and interact with smart devices.

    4. File Sharing: Access and download files.


Best Practices for Working with URLs

    1. Use HTTPS: Ensure secure communication with encrypted connections.

    2. Keep URLs Clean: Avoid unnecessary parameters for readability.

    3. SEO Optimization: Include keywords for better search engine ranking.

    4. Redirects: Properly handle outdated URLs to prevent broken links.


Examples of using URLs in code

Accessing a Webpage in Python

Code:

import requests

# URL to access
url = "https://example.com/api/resource"

try:
    # Sending a GET request
    response = requests.get(url)

    # Print the status code
    print("Status Code:", response.status_code)

    # Check if the status code is 200 (OK)
    if response.status_code == 200:
        # Try to parse the response as JSON
        print("Response JSON:", response.json())
    else:
        # Handle other status codes
        print(f"Error: Received status code {response.status_code}")
        print("Response Text:", response.text)

except requests.exceptions.RequestException as e:
    # Handle connection errors or other request issues
    print("Request Error:", e)

Output:

Status Code: 404
Error: Received status code 404
Response Text: <!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
………………………………………………………………………………………………… 
 
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

Accessing a Resource in JavaScript

Code:

// Public API for testing
const url = "https://jsonplaceholder.typicode.com/posts";

// Fetching data
fetch(url)
    .then(response => {
        console.log(`HTTP Status: ${response.status}`);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => console.log("Data received:", data))
    .catch(error => console.error("Fetch Error:", error.message));

Output:

"HTTP Status: 200"
"Data received:"
[[object Object] {
  body: "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto",
  id: 1,
  title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  userId: 1
},
………………………………………………………….. 
accusamus ratione error aut",
  id: 100,
  title: "at nam consequatur ea labore ea harum",
  userId: 10
}]

Click to explore a comprehensive list of computer programming topics and examples.



Follow us on Facebook and Twitter for latest update.