Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a small Flask API by mapping URLs and HTTP methods to Python functions, returning JSON with meaningful status codes, and testing the routes with Flask’s test client. The example below implements GET /items, GET /items/<id>, and POST /items using an in-memory collection; it is suitable for learning and local development, not persistent production storage.

What you will build

A REST API exposes resources through HTTP endpoints. In this example, an item is a resource represented as JSON. A client can list items, retrieve one by ID, or submit JSON to create one. The route’s URL and accepted HTTP method together determine which view function handles a request.

Flask routes accept GET by default, so API routes should declare other methods explicitly. Flask also supports method-specific decorators such as @app.get and @app.post. See the Flask Quickstart for routing and request/response behavior.

Install Flask in a virtual environment

The Flask installation documentation currently states that Flask supports Python 3.9 and newer; check the linked documentation if you are working with a newer or unusual Python environment. A virtual environment keeps this project’s dependencies separate from other Python projects.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
  1. Create a project directory and move into it:

    mkdir flask-api
    cd flask-api
  2. Create and activate a virtual environment. On macOS or Linux:

    python3 -m venv .venv
    source .venv/bin/activate

    On Windows PowerShell:

    py -m venv .venv
    .venvScriptsActivate.ps1
  3. Install Flask:

    python -m pip install Flask

Using python -m pip helps ensure that installation uses the Python interpreter associated with the active environment. Flask documents the virtual-environment workflow and installation command in its installation guide.

Create the API

Save this as app.py. The data is deliberately stored in a Python list so the route and JSON behavior are easy to see. The records disappear when the process stops; use a database or other persistent store for an application that must retain data.

from flask import Flask, abort, request, url_for

app = Flask(__name__)

items = [
    {"id": 1, "name": "Notebook"},
    {"id": 2, "name": "Pen"},
]
next_item_id = 3


@app.get("/items")
def list_items():
    return {"items": items}


@app.get("/items/<int:item_id>")
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404, description="Item not found")
    return item


@app.post("/items")
def create_item():
    global next_item_id

    if not request.is_json:
        return {"error": "Content-Type must be application/json"}, 415

    data = request.get_json()
    if not isinstance(data, dict):
        return {"error": "JSON body must be an object"}, 400

    name = data.get("name")
    if not isinstance(name, str) or not name.strip():
        return {"error": "'name' must be a non-empty string"}, 400

    item = {"id": next_item_id, "name": name.strip()}
    next_item_id += 1
    items.append(item)

    response = app.response_class(
        response=app.json.dumps(item),
        status=201,
        mimetype="application/json",
    )
    response.headers["Location"] = url_for("get_item", item_id=item["id"])
    return response


@app.errorhandler(404)
def handle_not_found(error):
    return {"error": error.description or "Not found"}, 404


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

Why the routes use these methods and responses

  • GET /items reads the collection, while GET /items/<int:item_id> reads one item. The integer path converter rejects non-integer IDs as unmatched routes.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • POST /items creates an item. The example requires a JSON object with a non-empty string name, trims surrounding whitespace, and responds with 201 Created. The Location header points to the new item’s retrieval URL.

  • A request with a non-JSON content type receives 415 Unsupported Media Type; a JSON body with invalid shape or a missing/blank name receives 400 Bad Request. A request for an item ID that is not present receives 404 Not Found.

    Rank #2
    Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
    • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
    • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
    • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
    • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
    • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
  • The not-found handler returns a JSON error body while retaining the 404 status. Flask also has default handling for errors such as 405 Method Not Allowed and 500 Internal Server Error; an API can add handlers when it needs a consistent JSON format for those cases too. See Flask’s error handling guidance.

Flask can convert a returned dictionary or list into a JSON response automatically. This example uses that behavior for ordinary results and errors, and constructs a response explicitly for the create route because it needs to set both a status and a header. jsonify() is another supported way to make a JSON response. Returned values must be JSON-serializable; convert database models or other complex objects to plain dictionaries or lists first. Details are in the Flask API reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Combined route methods or separate functions?

Flask also allows one route function to handle multiple methods with @app.route("/items", methods=["GET", "POST"]), then branch on request.method. That can be compact when behavior is closely shared. Separate @app.get and @app.post functions make different operations, validation, and return behavior easier to read and maintain, which is why this tutorial uses them.

Run the API locally and make requests

From the directory containing app.py, start Flask’s development server:

flask --app app run --debug

The server prints a local address, usually http://127.0.0.1:5000. Keep it running in that terminal while you send requests from another one.

List items and retrieve one item

Use curl to request the collection:

curl -i http://127.0.0.1:5000/items

The response should have a 200 status and JSON similar to:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
{"items":[{"id":1,"name":"Notebook"},{"id":2,"name":"Pen"}]}

Retrieve the first item with curl -i http://127.0.0.1:5000/items/1. For an ID that is absent, such as 999, the API returns a 404 response with a JSON error body.

Send a JSON POST request

Specify the JSON content type and provide a JSON object in the request body:

curl -i -X POST http://127.0.0.1:5000/items 
  -H "Content-Type: application/json" 
  -d '{"name":"Marker"}'

A successful response has status 201, a JSON representation of the created item, and a Location header. Try {} to see the validation error, or send a non-JSON body to see the unsupported-media-type response.

Test routes without starting a server

Flask’s test client makes requests directly to the application, so a live server is not needed. The json argument serializes a request body and sets its JSON content type; JSON responses can be inspected through response.json. These features are documented in Testing Flask Applications.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create test_app.py beside app.py:

import unittest

from app import app, items


class ItemApiTests(unittest.TestCase):
    def setUp(self):
        app.config["TESTING"] = True
        self.client = app.test_client()

    def test_list_items_returns_json(self):
        response = self.client.get("/items")
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response.json["items"], list)

    def test_missing_item_returns_json_404(self):
        response = self.client.get("/items/999")
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.json["error"], "Item not found")

    def test_create_item_returns_created_resource(self):
        response = self.client.post("/items", json={"name": "Test item"})
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.json["name"], "Test item")
        self.assertIn("Location", response.headers)

    def test_create_item_rejects_blank_name(self):
        response = self.client.post("/items", json={"name": "  "})
        self.assertEqual(response.status_code, 400)
        self.assertIn("error", response.json)


if __name__ == "__main__":
    unittest.main()

Run the tests with:

python -m unittest -v

Because this example mutates module-level in-memory data, a POST test can affect later requests during the same process. For larger suites, use a fixture or application factory to create a fresh app and isolated test data for each test. The current tests check response status, JSON content, and a response header rather than depending on incidental implementation details.

Decide what to improve before production

The tutorial app demonstrates request handling, but the in-memory list is neither durable nor designed for concurrent application workers. A production API typically needs persistent storage, explicit data validation, authentication and authorization where appropriate, and operational monitoring. Those are application design decisions, not features Flask automatically supplies.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The debug=True setting and Flask’s built-in server are for local development. Flask explicitly warns not to use the development server or interactive debugger in production: the debugger can expose powerful execution capabilities, and the server is not the production deployment mechanism. Flask is a WSGI application; choose a production deployment option described in the Flask deployment documentation. Do not expose the debug server to the public internet.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common problems

  • ModuleNotFoundError: No module named 'flask': activate the project’s virtual environment, then install Flask with python -m pip install Flask using that same interpreter.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Flask cannot find the application: run the command from the directory containing app.py and use flask --app app run --debug. The value after --app identifies the module, not the filename with its .py suffix.

  • POST returns 415: send Content-Type: application/json; with curl, include -H "Content-Type: application/json". In the test client, pass json={...}.

  • POST returns 400: verify that the body is valid JSON, is an object rather than a string or array, and contains a non-empty string in name.

  • A route returns 404 or 405: check the path spelling, the item ID, and the method. A path that exists for GET does not automatically accept POST; this API only creates through POST /items.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    Best Value
    Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
    • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
    • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
    • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
    • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
    • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • Changes vanish after restarting: that is expected because the sample keeps data in memory. Add a persistent datastore and define how records are created, read, and updated there.

  • Tests fail depending on execution order: the shared list and ID counter persist within the Python process. Reset or isolate application data between tests rather than relying on a particular test order.

Or skip the browser setup

If your Flask project also needs screenshots of web pages—for example, to capture a rendered page for a separate workflow—you can use ScreenshotNeo rather than setting up a browser automation stack for that capture. It is a screenshot API and MCP server, not a replacement for Flask’s routes or test client. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. AI agents can use its MCP server for screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

Sign up for 1,000 free screenshots a month with no card.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does this example implement every REST operation?

No. It demonstrates listing, retrieving, and creating items. Update and delete routes are intentionally omitted so the basic request and response pattern stays focused.

Can a Flask API return database objects directly as JSON?

Not generally: return JSON-serializable values. Convert a model to plain dictionaries or lists, or construct a response with the fields the API should expose.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.