How to Build a REST API with Python Flask

Flask is a lightweight Python microframework that makes building REST APIs fast and clean. In this tutorial, you’ll create a simple REST API with CRUD operations for managing tasks. By the end, you’ll have a fully functional API that returns JSON responses.

First, set up a virtual environment and install Flask: pip install flask. Create a new file app.py and import Flask, request, and jsonify. Then initialize your app with app = Flask(__name__). For data, use a simple in-memory list of dictionaries—good for prototyping.

Article illustration

Define Routes and Endpoints

Use Flask’s @app.route() decorator to map HTTP methods to functions. For example:

  • GET /tasks – returns all tasks.
  • GET /tasks/<id> – returns a specific task.
  • POST /tasks – creates a new task.
  • PUT /tasks/<id> – updates an existing task.
  • DELETE /tasks/<id> – deletes a task.

Implement each function with simple logic. For example, in the POST route, get JSON data via request.get_json(), add an ID, and append to your tasks list. Return jsonify(task) with status code 201.

Handle Request and Response

Use request.method to differentiate actions on the same route. Always return JSON using jsonify(). For missing resources, return ({'error': 'Not found'}, 404). For invalid data, return status 400. This ensures your API follows REST best practices.

Testing Your API

Run python app.py and use a tool like Postman or curl to test endpoints. Example curl: curl http://127.0.0.1:5000/tasks. For POST: curl -X POST -H "Content-Type: application/json" -d '{"title":"New Task"}' http://127.0.0.1:5000/tasks. Verify responses are correct.

You now have a basic REST API with Flask. For production, add input validation, use a database, and structure your code with Blueprints. Flask makes scaling simple and is ideal for microservices.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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