miguendes's blog

miguendes's blog

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

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

Listen to this article


In this article you'll learn how to determine if a string is a valid web address or not in Python. The good new is, you don't need to write one yourself. Just use a third-party URL validator such as the validators package or if it's a Django project, you can use Django's URLValidator.

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


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("http://.www.foo.bar/")

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!

Share this
Proudly part of