Programming & Development

Flask GET and POST Requests Explained

When building a Flask application, your server constantly receives HTTP requests from browsers, mobile apps, frontend applications, and other services. Two of…

D
DevByteTechnical Author
Published
16 min read3 views
Flask GET and POST requests explained with query parameters, form data, JSON, validation, and HTTP responses

When you start building a web application with Python, one of the first things you need to understand is how the frontend communicates with the backend.

For example, imagine you're building a login page. A user enters their email and password, clicks the login button, and expects the server to verify their credentials. Or perhaps you're building a blog where users can submit new articles.

In both cases, your application needs a way to send data to the server and receive a response.

This is where HTTP methods like GET and POST come in.

In this guide, we'll explore how GET and POST requests work in Flask, how they differ, and how to use them in real-world applications. We'll also look at practical code examples that you can run on your local machine.

What Is Flask?

Flask is a lightweight Python web framework used to build web applications, REST APIs, and backend services.

Unlike larger frameworks that include many features by default, Flask gives you the flexibility to choose the tools you need for your project.

You can use Flask to:

  • Build REST APIs for React, Next.js, or other frontend applications.

  • Handle form submissions.

  • Create authentication and registration endpoints.

  • Connect applications to databases.

  • Build backend services for AI and machine learning applications.

If you're coming from Node.js and Express, Flask will feel familiar. Both frameworks use routes to handle incoming HTTP requests and return responses.

For example, an Express route might look like this:

app.get("/users", (req, res) => {
  res.json({ message: "Users fetched successfully" });
});

The equivalent route in Flask looks like this:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/users", methods=["GET"])
def get_users():
    return jsonify({"message": "Users fetched successfully"})

The syntax is different, but the basic idea is the same.

What Are HTTP GET and POST Requests?

HTTP methods tell the server what the client wants to do with a resource.

Two of the most commonly used methods are GET and POST.

1. GET Request

A GET request is used to retrieve data from a server.

For example:

  • Fetching a list of users.

  • Getting a particular product by its ID.

  • Retrieving blog posts.

  • Loading a user's profile.

When you open a website or request information from an API, your browser or frontend application often sends a GET request.

Example API endpoint:

GET /users

The server might respond with:

[
  {
    "id": 1,
    "name": "Manjeet"
  },
  {
    "id": 2,
    "name": "Rahul"
  }
]

GET requests can include query parameters in the URL.

For example:

GET /products?category=electronics&page=1

Here, category and page are query parameters that the server can use to filter or paginate the results.

2. POST Request

A POST request is commonly used to submit data to a server for processing or to create a resource.

For example:

  • Registering a new user.

  • Creating a blog post.

  • Submitting a contact form.

  • Sending data to an API.

  • Uploading information to a database.

Suppose you want to create a new user. Your frontend might send this request:

POST /users
Content-Type: application/json

With the following JSON body:

{
  "name": "Manjeet",
  "email": "manjeet@example.com"
}

The server reads the submitted data, validates it, performs the required operation, and returns a response.

Important: POST does not automatically save data to a database. Your backend code must perform that operation.

Setting Up a Flask Project

Before writing GET and POST routes, let's set up a basic Flask application.

Step 1: Create a Project Folder

Open your terminal and run:

mkdir flask-requests
cd flask-requests

Step 2: Create a Virtual Environment

A virtual environment keeps your project's Python dependencies separate from other projects.

On macOS or Linux:

python3 -m venv venv
source venv/bin/activate

On Windows:

python -m venv venv
venv\Scripts\activate

Step 3: Install Flask

Install Flask using pip:

pip install Flask

You can verify the installation with:

python -m flask --version

Step 4: Create the Application

Create a file named app.py:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Welcome to my Flask application!"

if __name__ == "__main__":
    app.run(debug=True)

Start the application:

python app.py

By default, Flask's development server will be available at:

http://127.0.0.1:5000

Open this address in your browser. You should see:

Welcome to my Flask application!

Your Flask application is now running.

Note: Debug mode is useful during local development, but you should disable it when deploying your application to production.

How to Handle GET Requests in Flask

Let's start with a simple GET endpoint.

Imagine you're building an API that returns a list of users.

Example 1: Create a GET Route

Update your app.py file:

from flask import Flask, jsonify

app = Flask(__name__)

users = [
    {"id": 1, "name": "Manjeet"},
    {"id": 2, "name": "Rahul"},
    {"id": 3, "name": "Amit"}
]

@app.route("/users", methods=["GET"])
def get_users():
    return jsonify(users)

if __name__ == "__main__":
    app.run(debug=True)

Let's understand what's happening here.

Flask(__name__)

This creates the Flask application.

@app.route("/users", methods=["GET"])

This decorator tells Flask to call the get_users() function when it receives a GET request for /users.

jsonify(users)

This converts the Python data into a JSON HTTP response, which is useful when building APIs.

Now open this URL:

http://127.0.0.1:5000/users

You'll receive a JSON response similar to this:

[
  {
    "id": 1,
    "name": "Manjeet"
  },
  {
    "id": 2,
    "name": "Rahul"
  },
  {
    "id": 3,
    "name": "Amit"
  }
]

You have successfully created your first GET API.

Example 2: Get Data Using a Query Parameter

Sometimes you don't want to return every record. You might want to retrieve a specific user or filter results.

Flask provides the request object to access incoming request data.

Let's create a route that searches for a user by name.

from flask import Flask, jsonify, request

app = Flask(__name__)

users = [
    {"id": 1, "name": "Manjeet"},
    {"id": 2, "name": "Rahul"},
    {"id": 3, "name": "Amit"}
]

@app.route("/users/search", methods=["GET"])
def search_users():
    name = request.args.get("name", "")

    results = [
        user for user in users
        if name.lower() in user["name"].lower()
    ]

    return jsonify(results)

if __name__ == "__main__":
    app.run(debug=True)

Now send a GET request to:

http://127.0.0.1:5000/users/search?name=rahul

Response:

[
  {
    "id": 2,
    "name": "Rahul"
  }
]

Let's break down this line:

name = request.args.get("name", "")
  • request.args contains query parameters from the URL.

  • .get("name") retrieves the value of the name parameter.

  • "" is the default value when the parameter is missing.

This approach is useful when building search APIs, filters, and pagination.

For example, you could retrieve pagination parameters like this:

page = request.args.get("page", default=1, type=int)
limit = request.args.get("limit", default=10, type=int)

In a real application, you should also validate the values and enforce sensible limits.

How to Handle POST Requests in Flask

Now let's look at POST requests.

Suppose you're building an API that allows users to submit their name and email address. The backend receives the information and creates a new user.

For this example, we'll temporarily store users in a Python list. This is useful for learning, but the data will disappear when the application restarts.

Example 1: Create a POST Route

Update your app.py file:

from flask import Flask, jsonify, request

app = Flask(__name__)

users = [
    {"id": 1, "name": "Manjeet"}
]

@app.route("/users", methods=["GET"])
def get_users():
    return jsonify(users)

@app.route("/users", methods=["POST"])
def create_user():
    data = request.get_json(silent=True)

    if not isinstance(data, dict):
        return jsonify({"error": "A JSON object is required"}), 400

    name = data.get("name")

    if not isinstance(name, str) or not name.strip():
        return jsonify({"error": "Name is required"}), 400

    new_user = {
        "id": len(users) + 1,
        "name": name.strip()
    }

    users.append(new_user)

    return jsonify(new_user), 201

if __name__ == "__main__":
    app.run(debug=True)

Let's understand the important parts.

1. Read the JSON body

data = request.get_json(silent=True)

This attempts to parse the incoming JSON request body. With silent=True, Flask returns None instead of raising an error when the JSON cannot be parsed.

2. Validate the incoming data

name = data.get("name")

if not isinstance(name, str) or not name.strip():
    return jsonify({"error": "Name is required"}), 400

The server checks whether the name is a non-empty string before creating the user.

Validation is important because you should never assume that incoming data is correct.

3. Create the user

new_user = {
    "id": len(users) + 1,
    "name": name.strip()
}

This creates a new Python dictionary representing the user.

4. Return the response

return jsonify(new_user), 201

The HTTP status code 201 Created indicates that the request successfully created a resource.

Example 2: Send a POST Request Using Postman

You can test your POST endpoint using Postman, curl, or a frontend application.

In Postman:

  1. Select the POST method.

  2. Enter http://127.0.0.1:5000/users.

  3. Open the Body tab.

  4. Select raw and choose JSON.

  5. Enter the following data.

  6. Click Send.

{
  "name": "Rahul"
}

Expected response:

{
  "id": 2,
  "name": "Rahul"
}

The status code should be 201 Created.

You can now send a GET request to /users to see the list of users in memory.

Example 3: Send a POST Request Using curl

You don't always need Postman to test an API. You can send a POST request directly from your terminal.

curl -X POST http://127.0.0.1:5000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Amit"}'

Here's what the command does:

  • -X POST specifies the HTTP method.

  • -H sets the request's content type.

  • -d supplies the JSON request body.

This is a quick way to test your backend endpoints while developing.

How to Handle HTML Form Data in Flask

So far, we've sent JSON data to Flask. However, traditional HTML forms often submit form-encoded data instead.

Flask provides request.form to access submitted form fields.

Here's a simple example.

from flask import Flask, request

app = Flask(__name__)

@app.route("/contact", methods=["GET", "POST"])
def contact():
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email = request.form.get("email", "").strip()

        if not name or not email:
            return "Name and email are required", 400

        return f"Thanks, {name}! Your message has been received."

    return """
        <form method="POST" action="/contact">
            <label>
                Name:
                <input type="text" name="name" required>
            </label>
            <br><br>

            <label>
                Email:
                <input type="email" name="email" required>
            </label>
            <br><br>

            <button type="submit">Submit</button>
        </form>
    """

if __name__ == "__main__":
    app.run(debug=True)

Open this URL:

http://127.0.0.1:5000/contact

You'll see a simple HTML form. When you submit it, the browser sends a POST request containing the form fields.

Flask reads those fields using:

name = request.form.get("name", "")
email = request.form.get("email", "")

Remember the difference:

  • Use request.args to read query parameters from a URL.

  • Use request.form to read form-encoded fields.

  • Use request.get_json() to read JSON request bodies.

These are three different ways of accessing incoming request data.

GET vs POST: What's the Difference?

Although both methods allow a client to communicate with a server, they serve different purposes.

Feature

GET

POST

Main purpose

Retrieve data

Submit data or create a resource

Typical use

Fetch users or products

Register users or create posts

Data location

Commonly in the URL

Commonly in the request body

Flask access

request.args

request.get_json() or request.form

Request body

Not generally used for application data

Commonly contains submitted data

Safe by definition

Yes

No

Idempotent by definition

Yes

No

Typical success status

200 OK

200 OK or 201 Created

Can be cached

Often, depending on the response and cache rules

Not usually cached by default

What Does Safe Mean?

A safe HTTP method is intended to retrieve information without requesting a change to the server's application state.

GET should not be used to perform actions such as deleting a user or transferring money.

What Does Idempotent Mean?

An HTTP method is idempotent when making the same request multiple times has the same intended effect on server state as making it once.

For example, calling a GET endpoint repeatedly should not create additional users.

POST is not inherently idempotent. Sending the same create-user request twice might create two users unless the application implements duplicate prevention or idempotency controls.

Is POST More Secure Than GET?

Not automatically.

POST request bodies are not normally displayed as part of the URL, which can reduce accidental exposure compared with putting sensitive values in query parameters. However, POST data can still be exposed through insecure connections, application logs, browser tools, or other mechanisms.

Use HTTPS for data in transit, and never put passwords, API keys, or other secrets in URLs. Sensitive operations also need proper authentication, authorization, validation, and other appropriate security controls.

Using GET and POST in a Real API

Let's put both methods together in a single Flask application.

This example provides two endpoints:

  • GET /api/products returns products.

  • POST /api/products creates a product.

For simplicity, the products are stored in memory rather than a database.

from flask import Flask, jsonify, request

app = Flask(__name__)

products = [
    {"id": 1, "name": "Laptop", "price": 55000},
    {"id": 2, "name": "Keyboard", "price": 1500}
]

@app.route("/api/products", methods=["GET"])
def get_products():
    return jsonify(products), 200

@app.route("/api/products", methods=["POST"])
def create_product():
    data = request.get_json(silent=True)

    if not isinstance(data, dict):
        return jsonify({"error": "A JSON object is required"}), 400

    name = data.get("name")
    price = data.get("price")

    if not isinstance(name, str) or not name.strip():
        return jsonify({"error": "Product name is required"}), 400

    if (
        isinstance(price, bool)
        or not isinstance(price, (int, float))
        or price < 0
    ):
        return jsonify({"error": "A valid non-negative price is required"}), 400

    new_product = {
        "id": max((product["id"] for product in products), default=0) + 1,
        "name": name.strip(),
        "price": price
    }

    products.append(new_product)

    return jsonify(new_product), 201

if __name__ == "__main__":
    app.run(debug=True)

Test the GET Endpoint

Send:

GET http://127.0.0.1:5000/api/products

Example response:

[
  {
    "id": 1,
    "name": "Laptop",
    "price": 55000
  },
  {
    "id": 2,
    "name": "Keyboard",
    "price": 1500
  }
]

Test the POST Endpoint

Send:

POST http://127.0.0.1:5000/api/products
Content-Type: application/json

Request body:

{
  "name": "Mouse",
  "price": 800
}

Example response:

{
  "id": 3,
  "name": "Mouse",
  "price": 800
}

The response status is 201 Created.

This example demonstrates the basic structure of a Flask API. In a production application, you would usually move database operations into a separate service or repository layer, use a persistent database, and add more comprehensive validation and error handling.

How to Call a Flask API From JavaScript

If you're a frontend developer working with React or Next.js, you can call Flask endpoints using the Fetch API.

Sending a GET Request

async function getProducts() {
  try {
    const response = await fetch(
      "http://127.0.0.1:5000/api/products"
    );

    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    const products = await response.json();

    console.log(products);
  } catch (error) {
    console.error("Unable to fetch products:", error);
  }
}

getProducts();

This sends a GET request to Flask and converts the JSON response into a JavaScript value.

Sending a POST Request

async function createProduct() {
  try {
    const response = await fetch(
      "http://127.0.0.1:5000/api/products",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          name: "Monitor",
          price: 12000
        })
      }
    );

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || "Unable to create product");
    }

    console.log("Product created:", data);
  } catch (error) {
    console.error("Error creating product:", error);
  }
}

createProduct();

Notice the following details:

  • method: "POST" specifies the HTTP method.

  • Content-Type: "application/json" tells Flask that the request body contains JSON.

  • JSON.stringify() converts the JavaScript object into a JSON string.

  • response.json() parses the response body.

  • response.ok allows you to handle unsuccessful HTTP responses.

If your frontend and Flask backend run on different origins, you may also need to configure Cross-Origin Resource Sharing (CORS) on the Flask server.

Common Mistakes When Working With Flask GET and POST Requests

Beginners often encounter a few predictable issues while working with request methods.

1. Using the Wrong Request Property

A common mistake is trying to access JSON data through request.args.

Incorrect for JSON request bodies:

name = request.args.get("name")

Correct:

data = request.get_json()
name = data.get("name")

Use request.args for query parameters, not JSON bodies.

2. Forgetting the HTTP Method

Suppose you define a POST-only endpoint:

@app.route("/users", methods=["POST"])
def create_user():
    return "User created"

Opening /users directly in your browser usually sends a GET request, so Flask will reject it with 405 Method Not Allowed.

Test the endpoint using Postman, curl, or frontend code that sends POST.

3. Forgetting the Content-Type Header

When sending JSON from JavaScript, include:

headers: {
  "Content-Type": "application/json"
}

Without the appropriate content type, Flask may not interpret the request body as JSON as expected.

4. Not Validating User Input

Never assume that the client will send valid information.

A request might contain missing fields, empty strings, unexpected data types, or values that violate your application's rules.

Validate incoming data on the server before processing it.

5. Assuming In-Memory Data Is a Database

In our examples, users and products are stored in Python lists.

That works for learning, but the data disappears when the server restarts. It also isn't suitable for concurrent production use or multiple application workers.

For real applications, use a persistent database such as PostgreSQL, MySQL, or MongoDB, depending on your requirements.

6. Using GET for Operations That Change Data

Avoid using GET to create, update, or delete resources.

For example, this is a poor API design:

GET /delete-user?id=10

Use an appropriate method, such as DELETE, for deletion operations. This helps preserve the expected behavior of HTTP methods and reduces the risk of unintended changes.

Best Practices for Flask APIs

When building Flask applications, keep these practices in mind:

  1. Choose the right HTTP method. Use GET to retrieve data and POST to submit data or create resources.

  2. Validate every request. Check required fields, data types, formats, and business rules on the server.

  3. Return meaningful status codes. Use codes such as 200 OK, 201 Created, 400 Bad Request, and 404 Not Found appropriately.

  4. Use JSON consistently for APIs. JSON is a common format for communication between Flask backends and modern frontend applications.

  5. Keep database logic organized. Separate routes from business logic as your application grows.

  6. Handle errors properly. Return useful error messages without exposing internal stack traces or sensitive information.

  7. Protect sensitive operations. Use authentication, authorization, HTTPS, and appropriate CSRF protections where relevant.

  8. Disable debug mode in production. Use a production-ready WSGI server instead of Flask's development server.

  9. Use persistent storage. Store important application data in a database rather than an in-memory list.

  10. Test your endpoints. Tools such as Postman and automated tests can help verify responses, validation, and error handling.

Frequently Asked Questions

1. What is a GET request in Flask?

A GET request retrieves information from a Flask route. You can define a GET endpoint using @app.route() with methods=["GET"] or use the @app.get() shortcut.

Example:

@app.get("/users")
def get_users():
    return {"message": "Users fetched successfully"}

2. What is a POST request in Flask?

A POST request submits data to a Flask endpoint for processing or resource creation. JSON data can be accessed using request.get_json(), while HTML form data can be accessed through request.form.

3. How do I get JSON data in Flask?

Import request and call:

data = request.get_json()

For production applications, handle malformed or missing JSON appropriately and validate the parsed data before using it.

4. Can a Flask route support both GET and POST?

Yes. You can allow both methods in one route:

@app.route("/users", methods=["GET", "POST"])
def users_route():
    if request.method == "POST":
        return {"message": "POST request received"}

    return {"message": "GET request received"}

For larger applications, separate routes or clear method-specific logic can make the code easier to maintain.

5. What is the difference between request.args and request.form?

request.args reads query parameters from the URL, such as ?page=2.

request.form reads form-encoded fields submitted in the request body.

For JSON request bodies, use request.get_json() instead.

6. How can I test Flask POST requests?

You can use Postman, curl, JavaScript's Fetch API, or Flask's built-in test client.

For example:

curl -X POST http://127.0.0.1:5000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Manjeet"}'

7. Does Flask automatically save POST data to a database?

No. Flask handles the incoming HTTP request, but your application must validate the data and explicitly save it using a database library or ORM.

8. Should I use GET or POST for login?

A login form typically sends credentials using POST over HTTPS rather than placing them in URL query parameters. The backend should verify the credentials securely and return an appropriate response.

Conclusion

Understanding GET and POST requests is an important first step toward building web applications and REST APIs with Flask.

GET requests are primarily used to retrieve data, while POST requests are commonly used to submit information for processing or create new resources.

In Flask, you can define routes using decorators, read query parameters with request.args, access form submissions with request.form, and parse JSON request bodies using request.get_json().

Once you understand these basics, you can start building more useful applications, such as authentication systems, CRUD APIs, dashboards, and backends for React or Next.js projects.

The best way to learn is to build a small API, test each endpoint, and gradually connect it to a real database.

Next step: Try extending the product API by adding PUT or PATCH requests for updating products and DELETE requests for removing them. This will help you understand how the different HTTP methods work together in a complete CRUD application.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘