NameError: name 'request' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "NameError: name 'request' is not defined" occurs when we use the request object in Flask without importing it first. To solve the error import request before using it - from flask import request.

main.py
# 👇️ import request from flask import Flask, request app = Flask(__name__) @app.route("/") def hello_world(): # 👇️ can use request here print(request.method) return "<p>Hello, World!</p>"

We had to import request from flask in order to use it.

Note that you should only use the request global object in your request handler functions because the request object is only populated in an active HTTP request.

The global request object is used to access incoming request data.

Flask parses the incoming request data for us and gives us access to it through the request object.

You will most often have to access the method property on the request object.

main.py
from flask import Flask, request app = Flask(__name__) @app.route("/") def hello_world(): print(request.method) if request.method == 'GET': return "<p>Request method is GET</p>" elif request.method == 'POST': return "<p>Request method is POST</p>" else: return "<p>Request method is not GET or POST</p>"

The method property returns the method of the HTTP request, e.g. GET or POST.

You can use the method property on the request to conditionally return a different response depending on the HTTP verb.

Conclusion #

The Python "NameError: name 'request' is not defined" occurs when we use the request object in Flask without importing it first. To solve the error import request before using it - from flask import request.

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.