How to Build a REST API with Flask: A Step-by-Step Guide

Flask is a lightweight Python framework that makes building REST APIs fast and straightforward. In this tutorial, you’ll learn how to create a simple RESTful API with Flask, covering project setup, endpoint creation, request handling, and testing. By the end, you’ll have a functional API you can extend for your own projects.

Article illustration

Setting Up Flask

First, create a virtual environment and install Flask:

  • python -m venv venv
  • source venv/bin/activate (or venv\Scripts\activate on Windows)
  • pip install flask

Create a file named app.py and import Flask:

from flask import Flask, request, jsonify
app = Flask(__name__)

Defining Routes and Endpoints

Use Flask decorators to map HTTP methods to functions. For a simple CRUD API for a resource called “items”:

  • GET /items – return all items
  • POST /items – create a new item
  • GET /items/<id> – get a single item
  • PUT /items/<id> – update an item
  • DELETE /items/<id> – delete an item

Example route:

items = []
@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)

Handling Requests and Responses

Access request data with request.get_json() for POST/PUT. Return JSON using jsonify(). Include proper HTTP status codes:

@app.route('/items', methods=['POST'])
def create_item():
    data = request.get_json()
    new_item = {"id": len(items)+1, "name": data["name"]}
    items.append(new_item)
    return jsonify(new_item), 201

Testing Your API

Run the app with flask run. Test using curl or tools like Postman:

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

Flask’s built-in server is fine for development. For production, use a WSGI server like Gunicorn.

Conclusion: Flask’s simplicity lets you build REST APIs quickly. Start with the basic structure above, then add authentication, database integration, and error handling as needed. Happy coding!

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *