Building a RESTful API with Flask and Python

Introduction

In this article we will learn about how to Build a RESTful API with Flask and Python, REST stands for Representational State Transfer, which is an architectural style for designing web services. REST is a stateless client-server communication protocol where the server does not store any session data. It uses HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources identified by URIs.

Flask

Flask is a lightweight and flexible Python web framework that makes it easy to create RESTful APIs. With its simplicity and minimalistic approach, Flask allows developers to build APIs quickly without compromising on functionality. Below, we'll explore the process of creating a RESTful API for managing employee data using Flask and Python. We'll cover the necessary steps, from setting up the environment to defining the API endpoints and testing the application.

Setting up the Flask Environment

python -m venv venv
source venv/bin/activate  
# On Windows use venv\Scripts\activate
pip install flask

Next, we'll create a new Python file (e.g., app.py) and import the necessary modules.

from flask import Flask, jsonify, request
app = Flask(__name__)
# Sample employee data
employees = [
    {
        'id': 1,
        'name': 'Lokendra Singh',
        'department': 'IT',
        'email': '[email protected]'
    },
    {
        'id': 2,
        'name': 'Ravi',
        'department': 'Marketing',
        'email': '[email protected]'
    }
]
@app.route('/employees', methods=['GET'])
def get_employees():
    return jsonify({'employees': employees})
@app.route('/employees/<int:employee_id>', methods=['GET'])
def get_employee(employee_id):
    employee = next((emp for emp in employees if emp['id'] == employee_id), None)
    if employee:
        return jsonify({'employee': employee})
    return jsonify({'message': 'Employee not found'}), 404
@app.route('/employees', methods=['POST'])
def create_employee():
    data = request.get_json()
    new_employee = {
        'id': employees[-1]['id'] + 1 if employees else 1,
        'name': data['name'],
        'department': data['department'],
        'email': data['email']
    }
    employees.append(new_employee)
    return jsonify({'employee': new_employee}), 201

@app.route('/employees/<int:employee_id>', methods=['PUT'])
def update_employee(employee_id):
    data = request.get_json()
    employee = next((emp for emp in employees if emp['id'] == employee_id), None)
    if employee:
        employee.update(data)
        return jsonify({'employee': employee})
    return jsonify({'message': 'Employee not found'}), 404


@app.route('/employees/<int:employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    employee = next((emp for emp in employees if emp['id'] == employee_id), None)
    if employee:
        employees.remove(employee)
        return jsonify({'message': 'Employee deleted'})
    return jsonify({'message': 'Employee not found'}), 404


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

In above this example, we've defined the following endpoints.

  • GET /employees: Returns a list of all employees.
  • GET /employees/<int:employee_id>: Returns a specific employee based on their ID.
  • POST /employees: Creates a new employee.
  • PUT /employees/<int:employee_id>: Updates an existing employee.
  • DELETE /employees/<int:employee_id>: Deletes an employee.

To run the API, execute the app.py file.

python app.py

This will start the Flask development server, and you can access the API endpoints at http://localhost:5000, where 5000 is the default port for Flask.

You can use tools like Postman or cURL to test your API endpoints. For example, to get all employees, send a GET request to http://localhost:5000/employees. To create a new employee, send a POST request to http://localhost:5000/employees with a JSON payload containing the employee details.

curl -X POST http://localhost:5000/employees -H "Content-Type: application/json" -d '{
    "name": "Aditya",
    "department": "IT",
    "email": "[email protected]"
}'

Summary

Flask's simplicity and flexibility make it an excellent choice for building RESTful APIs, especially for smaller projects or prototypes. However, for larger and more complex applications, you might want to consider using a more robust framework like Django REST Framework or Flask-RESTPlus. Building RESTful APIs is an essential skill for modern web development, and Flask provides a straightforward and efficient way to accomplish this task in Python.


Recommended Free Ebook
Similar Articles