How to Check If a String Is a Valid URL in Python

How to Check If a String Is a Valid URL in Python

Learn how to validate URLs in Python with the validators and django url validator

How to check if a URL is valid in python? You'll be surprise how easy it is to check that.

In this article you'll learn how to determine if a string is a valid web address or not.

The good new is, you don't need to write your own URL validator. We'll see how we can leverage a third-party URL validator to do the job for us.

Using the validators package

The validators package is a tool that comes with a wide range of validation utilities. You can validate all sorts of inputs such as emails, IP addresses, bitcoin addresses and, of course, URLs.

The URL validation function is available in the root of the module and will return True if the string is a valid URL, otherwise it returns an instance of ValidationFailure, which is a bit weird but not a deal breaker.

>>> import validators

>>> validators.url("http://localhost:8000")

The function from previous section can be re-written as follows:

import validators
from validators import ValidationFailure


def is_string_an_url(url_string: str) -> bool:
    result = validators.url(url_string)

    if isinstance(result, ValidationFailure):
        return False

    return result


>>> is_string_an_url("http://localhost:8000")
>>> is_string_an_url("")

⚠️ WARNING: You must trim all leading and trailing spaces from the URL string before calling validators.url.

# URL has a whitespace at the end
>>> url = "http://localhost:8000 "
>>> is_string_an_url(url)
# strip any leading or trailing spaces from the URL
>>> is_string_an_url(url.strip())

Using django's URLValidator

django is a great web framework that has many features. It bundles several utilities that makes web development easier. One such utility is the validators module, which contains, amongst other things, an URL validator.

You can validate if a string is, or not, an URL by creating an instance of URLValidator and calling it.

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError


def is_string_an_url(url_string: str) -> bool:
    validate_url = URLValidator(verify_exists=True)

    except ValidationError, e:
        return False

    return True

This works well, but adding Django as a dependency just to use its validator is a bit too much. Unless, of course, your project already has Django as a part of it. If not, we have another alternative.


In this post we saw 2 different ways of validating a URL in Python. I hope you find it useful.

Other posts you may like:

See you next time!