Skip to content

How to Resolve Python "NameError: name 'requests' / 'request' is not defined"

Fix Python NameError for missing 'requests' library or Flask's 'request' object with step-by-step import solutions and common usage patterns.

Encountering a NameError in Python means you've tried to use a variable or function name that hasn't been defined or imported into the current scope. Two common instances are NameError: name 'requests' is not defined and NameError: name 'request' is not defined. These errors, while similar, relate to different contexts: the first usually involves the popular requests HTTP library, and the second typically occurs within Flask web applications.

This guide explains the causes and provides clear solutions for both requests and request NameErrors.

Understanding NameError

A NameError is Python's way of saying it doesn't recognize a name you're trying to use. This happens if:

  • You misspelled a variable, function, or module name.
  • You forgot to define a variable before using it.
  • You forgot to import the module or specific object you need.

Scenario 1: NameError: name 'requests' is not defined

This error occurs when you try to use functions from the requests library (a very popular third-party library for making HTTP requests) without first importing the library itself.

Cause: requests Library Not Imported (or Not Installed)

Python doesn't know what requests refers to unless you explicitly tell it via an import statement. It's also possible the library isn't installed in your current Python environment.

try:
    response = requests.get("https://example.com")
    print(response.status_code)
except NameError as e:
    print(e)

Solution: Install and Import the requests Library

  1. Install requests (if necessary): If you haven't installed it, open your terminal (and activate your virtual environment if using one) and run:
    pip install requests
  2. Import requests: Add import requests at the top of your Python script before you use any of its functions.
import requests # Import the library

try:
    print("Making request...")
    response = requests.get("https://httpbin.org/get", timeout=10) # Use timeout
    response.raise_for_status() # Check for HTTP errors

    print(f"Status Code: {response.status_code}")
    print(f"Response JSON: {response.json()}")

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except NameError as e:
     print(f"Unexpected Name Error: {e}")

Example Output:

Making request...
Status Code: 200
Response JSON: {'args': {}, 'headers': {'Accept': '*/*', ...}, 'origin': '...', 'url': 'https://httpbin.org/get'}

Basic requests Usage Examples (GET/POST)

import requests

try:
    res_get = requests.get('https://jsonplaceholder.typicode.com/todos/1')
    res_get.raise_for_status()
    print("\nGET Response:")
    print(res_get.json())
except requests.exceptions.RequestException as e:
    print(f"GET Error: {e}")

try:
    post_data = {'title': 'foo', 'body': 'bar', 'userId': 1}
    res_post = requests.post(
        'https://jsonplaceholder.typicode.com/posts',
        json=post_data # Use json parameter for dict data
    )
    res_post.raise_for_status()
    print("\nPOST Response:")
    print(res_post.json())
except requests.exceptions.RequestException as e:
    print(f"POST Error: {e}")

Pitfall: Importing in Incorrect Scopes

Avoid importing requests inside functions or try blocks if you need to use it elsewhere in the module. Place import requests at the top level.

def make_api_call():
    import requests # Local import

try:
    r = requests.get('https://another-url.com')
except NameError as e:
    print(f"\nError due to scope: {e}")

import requests # ✅ Import globally

def make_api_call_fixed():
    r = requests.get('https://some-url.com')

r_global = requests.head('https://example.com')
print("Global request succeeded.")

Scenario 2: NameError: name 'request' is not defined (Flask)

This error specifically occurs within the context of a Flask web application when you try to access information about the incoming HTTP request using the request object, but you haven't imported it from the flask library.

Cause: Flask's request Object Not Imported

Flask provides a special context-local object named request that holds data about the current incoming HTTP request (like headers, form data, query parameters, method). You must import this specific object from the flask module to use it within your route handlers.

from flask import Flask

app = Flask(__name__)

@app.route('/process', methods=['GET', 'POST'])
def process_data():
    try:
        http_method = request.method # 'request' is unknown here
        return f"Method was {http_method}"
    except NameError as e:
        return f"Error: {e}"

with app.app_context(): # Need context for this simulation
    print(process_data()) # Output: Error: name 'request' is not defined

Solution: Import request from flask

Add request to your import statement from the flask module.

from flask import Flask, request # Import 'request' here

app_fixed = Flask(__name__)

@app_fixed.route('/process_fixed', methods=['GET', 'POST'])
def process_data_fixed():
    http_method = request.method
    user_agent = request.headers.get('User-Agent', 'Unknown')
    return f"Request method was {http_method}. User-Agent: {user_agent}"

with app_fixed.test_request_context('/process_fixed', method='POST'):
    print(f"\nFixed route response: {process_data_fixed()}")

Place from flask import request (or add request to an existing from flask import ...) at the top of your Flask application file.

Using the request Object in Flask Routes

Once imported, you can access various attributes of the request object within your route functions during an active request:

from flask import Flask, request, jsonify

app_demo = Flask(__name__)

@app_demo.route('/info', methods=['GET', 'POST'])
def request_info():
    info = {
        "method": request.method,
        "url": request.url,
        "path": request.path,
        "args": request.args.to_dict(),         # Query parameters
        "form_data": request.form.to_dict(),    # Form data (for POST, etc.)
        "headers": dict(request.headers),       # Request headers
        "is_json": request.is_json,
        "json_data": request.get_json(silent=True) # Parsed JSON body (if Content-Type is application/json)
    }
    return jsonify(info)

if __name__ == '__main__':
     app_demo.run(port=5000)

To test this, you would run the Flask app and make requests, e.g., using curl or Postman:

curl http://127.0.0.1:5000/info?param1=value1
curl -X POST -d "field1=data1" http://127.0.0.1:5000/info
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://127.0.0.1:5000/info

Conclusion

NameError exceptions in Python indicate that a name is not recognized in the current scope.

  • For NameError: name 'requests' is not defined:
    1. Ensure the requests library is installed (pip install requests).
    2. Add import requests at the top of your script.
  • For NameError: name 'request' is not defined (within Flask):
    1. Ensure Flask is installed (pip install Flask).
    2. Add from flask import request at the top of your Flask application file.

Always ensure necessary modules and objects are imported correctly before use, paying attention to the scope (top-level vs. local) and the specific library (requests vs. flask).

Navigation