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

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`](https://github.com/kvesteri/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.

```python
>>> import validators

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

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

```python
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")
True
>>> is_string_an_url("http://.www.foo.bar/")
False
```

⚠️ WARNING: You must [trim all leading and trailing spaces](https://miguendes.me/python-trim-string) from the URL string before calling `validators.url`.

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

## 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.

```python
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)

    try:
        validate_url(url_string)
    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.

## Conclusion

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:

- [Design Patterns That Make Sense in Python: Simple Factory](#https://miguendes.me/design-patterns-that-make-sense-in-python-simple-factory)
- [How to Pass Multiple Arguments to a map Function in Python](https://miguendes.me/how-to-pass-multiple-arguments-to-a-map-function-in-python)
- [73 Examples to Help You Master Python's f-strings](https://miguendes.me/73-examples-to-help-you-master-pythons-f-strings)
- [Everything You Need to Know About Python's Namedtuples](https://miguendes.me/everything-you-need-to-know-about-pythons-namedtuples)
- [The Best Way to Compare Two Dictionaries in Python](https://miguendes.me/the-best-way-to-compare-two-dictionaries-in-python)
- [5 Hidden Python Features You Probably Never Heard Of](https://miguendes.me/5-hidden-python-features-you-probably-never-heard-of)


See you next time!
