NameError: name 'requests' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'requests' is not defined in Python #

The Python "NameError: name 'requests' is not defined" occurs when we use the requests module without importing it first. To solve the error, install the module and import it (import requests) before using it.

nameerror name requests is not defined

Open your terminal in your project's root directory and install the requests module.

shell
# 👇️ in a virtual environment or using Python 2 pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install requests # 👇️ if you get permissions error sudo pip3 install requests # 👇️ if you don't have pip in your PATH environment variable python -m pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install requests # 👇️ alternative for Ubuntu/Debian sudo apt-get install python3-requests # 👇️ alternative for CentOS sudo yum install python-requests # 👇️ for Anaconda conda install -c anaconda requests

After you install the requests module, make sure to import it before using it.

main.py
# 👇️ import requests import requests def make_request(): res = requests.get('https://reqres.in/api/users') print(res.json()) make_request()

The example shows how to make a GET request to a remote API using the requests module.

The res variable is a Response object that allows us to access information from the HTTP response.

Here are some of the most commonly used properties on the Response object.

main.py
import requests def make_request(): res = requests.get('https://reqres.in/api/users') print(res.headers) # access response headers print(res.text) # parse JSON response to native Python string print(res.json()) # parse JSON response to native Python object make_request()

You can use the same approach to make a POST request.

main.py
import requests def make_request(): res = requests.post( 'https://reqres.in/api/users', data={'name': 'John Smith', 'job': 'manager'} ) print(res.json()) # parse JSON response to native Python object make_request()

The same approach can be used to make a PUT, DELETE, HEAD or OPTIONS requests.

If you need to send a request body, set the data keyword argument like we did in the example above.

Conclusion #

The Python "NameError: name 'requests' is not defined" occurs when we use the requests module without importing it first. To solve the error, install the module and import it (import requests) before using it.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.