Building a Simple API with Flask: A Step-by-Step Example
Flask, a popular Python web framework, is an excellent choice for creating APIs due to its simplicity and flexibility. In this guide, we'll walk you through creating a simple REST API using Flask, focusing on CRUD (Create, Read, Update, Delete) operations for a basic 'To-Do' item. By the end, you'll have a functional API ready to manage your tasks.
Setting Up the Project and Environment
First, ensure you have Python and pip installed. Then, install Flask and Flask-CORS (to handle Cross-Origin Resource Sharing) using pip:
pip install flask flask_cors
Create a new folder for your project and navigate into it. Inside this folder, create a new file named app.py. This will be the entry point of your API.

Creating the Flask Application
Let's start by importing the necessary modules and creating a basic Flask application:
```python from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # Enable CORS for all routes ```
Defining the Data Structure
For this example, we'll use a simple list to store our 'To-Do' items. Each item will be a dictionary containing an 'id' and 'task' key:
```python tasks = [ {'id': 1, 'task': 'Buy groceries'}, {'id': 2, 'task': 'Walk the dog'}, ] ```
Implementing the API Endpoints
GET /tasks: Retrieve all tasks
We'll use the jsonify function to return a JSON response:

```python @app.route('/tasks', methods=['GET']) def get_tasks(): return jsonify(tasks) ```
POST /tasks: Create a new task
To create a new task, we'll expect a JSON object with a 'task' key in the request body:
```python @app.route('/tasks', methods=['POST']) def create_task(): new_task = { 'id': tasks[-1]['id'] + 1 if tasks else 1, 'task': request.json['task'] } tasks.append(new_task) return jsonify(new_task), 201 ```
GET /tasks/: Retrieve a single task
We'll use a route parameter to specify the task ID:
```python
@app.route('/tasks/ To update a task, we'll expect a JSON object with a 'task' key in the request body:PUT /tasks/

```python
@app.route('/tasks/ To delete a task, we'll simply remove it from the list:DELETE /tasks/
```python
@app.route('/tasks/ Finally, add the following lines to run the application:Running the Application
```python if __name__ == '__main__': app.run(debug=True) ```
Now, run your application using python app.py. Your API is now live and ready to manage your 'To-Do' items at http://127.0.0.1:5000/tasks.




















