Creating a Simple REST API with Python and Flask

 

Introduction:

Creating a simple REST API with Python and Flask is straightforward and a great way to get started with web development and APIs. Below is a step-by-step guide to help you create your own RESTful API using Flask, a lightweight Python web framework.






Step 1: Install Flask

First, you need to install Flask. If you don't have it installed, you can do so with pip:

bash

pip install Flask


Step 2: Create the Flask Application

Create a new Python file, for example, app.py. This file will contain the core logic of your Flask application.

Step 3: Define Your API Endpoints

Below is a simple example of a Flask application that exposes a few RESTful API endpoints.

from flask import Flask, jsonify, request # Initialize the Flask application app = Flask(__name__) # Sample data to work with tasks = [ {'id': 1, 'title': 'Learn Python', 'done': False}, {'id': 2, 'title': 'Build a Flask API', 'done': False}, ] # Home route to test the server @app.route('/') def index(): return "Welcome to the Flask REST API!" # GET endpoint to retrieve all tasks @app.route('/tasks', methods=['GET']) def get_tasks(): return jsonify({'tasks': tasks}) # GET endpoint to retrieve a task by ID @app.route('/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): task = next((task for task in tasks if task['id'] == task_id), None) if task is None: return jsonify({'error': 'Task not found'}), 404 return jsonify({'task': task}) # POST endpoint to create a new task @app.route('/tasks', methods=['POST']) def create_task(): # Get JSON data from the request body new_task = request.get_json() if not new_task or not new_task.get('title'): return jsonify({'error': 'Missing task title'}), 400 task = { 'id': tasks[-1]['id'] + 1 if tasks else 1, 'title': new_task['title'], 'done': False } tasks.append(task) return jsonify({'task': task}), 201 # PUT endpoint to update a task by ID @app.route('/tasks/<int:task_id>', methods=['PUT']) def update_task(task_id): task = next((task for task in tasks if task['id'] == task_id), None) if task is None: return jsonify({'error': 'Task not found'}), 404 # Update task data updated_data = request.get_json() task['title'] = updated_data.get('title', task['title']) task['done'] = updated_data.get('done', task['done']) return jsonify({'task': task}) # DELETE endpoint to delete a task by ID @app.route('/tasks/<int:task_id>', methods=['DELETE']) def delete_task(task_id): global tasks tasks = [task for task in tasks if task['id'] != task_id] return jsonify({'message': 'Task deleted successfully'}), 200 # Run the application if __name__ == '__main__': app.run(debug=True)

Step 4: Run the Application

To run the Flask application, open a terminal, navigate to the folder where app.py is located, and execute:

        python app.py

You should see something like this in the terminal:


* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Your API will now be accessible at http://127.0.0.1:5000/.


Step 5: Test the API Endpoints

You can test the API using tools like Postman, Insomnia, or directly via curl commands in the terminal. Below are examples of how to interact with your API.

            1. GET all tasks:

                        curl http://127.0.0.1:5000/tasks

            2. GET a specific task by ID:

                        curl http://127.0.0.1:5000/tasks/1

            3. POST a new task:

                        curl -X POST -H "Content-Type: application/json" -d '{"title": "Learn Flask"}' http://127.0.0.1:5000/tasks

            4. PUT (update) a task:

                        curl -X PUT -H "Content-Type: application/json" -d '{"title": "Learn Flask and APIs", "done": true}' http://127.0.0.1:5000/tasks/1

            5. DELETE a task:

                        curl -X DELETE http://127.0.0.1:5000/tasks/1

Step 6: Explanation of the API Routes

  • GET /tasks – Retrieves the list of all tasks.
  • GET /tasks/int:task_id – Retrieves a specific task by its ID.
  • POST /tasks – Creates a new task. You must send a JSON body with the title key.
  • PUT /tasks/int:task_id – Updates an existing task's title or status.
  • DELETE /tasks/int:task_id – Deletes the task with the given ID.


Step 7: Handling Errors

Notice that we use Flask's jsonify to return JSON responses, and we handle errors with proper HTTP status codes. For example:

  • If the task is not found in a GET request, we return a 404 Not Found error.
  • If a required field is missing in a POST request, we return a 400 Bad Request error.


Step 8: Improvements and Next Steps

Now that you’ve created a basic REST API, you could improve it by:

  • Connecting to a database (e.g., SQLite, PostgreSQL) instead of using an in-memory list for tasks.
  • Authentication and authorization using tokens (JWT) for secure access.
  • Unit testing your API with Flask’s built-in testing tools.
  • Deploying the API to platforms like Heroku, AWS, or DigitalOcean.

At Computer Tech Hackers, we will keep you updated on the latest developments in  Simple REST API with Python and Flask Technology.

     Thank You.

No comments:

Powered by Blogger.