Building a Robust REST API in Python

python @ Freshers.in

Building a REST API in Python is a fundamental skill for developers. In this step-by-step guide, we’ll explore the Flask framework to create a robust REST API. Follow along to understand the essentials of API development, from setting up endpoints to handling requests, and witness it in action with a hands-on example.

Understanding REST and Flask Basics

REST (Representational State Transfer) is an architectural style for designing networked applications. Flask, a lightweight and versatile web framework, is an excellent choice for building REST APIs in Python.

Setting Up Flask

Install Flask using pip:

pip install Flask

Create a file named app.py for your Flask application.

Creating Endpoints

Define routes and endpoints to handle different requests. For simplicity, let’s create an endpoint that returns a list of items.

from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/items', methods=['GET'])
def get_items():
    items = ['item1', 'item2', 'item3']
    return jsonify({'items': items})
if __name__ == '__main__':
    app.run(debug=True)

Running the Flask Application

Run the Flask application:

python app.py

Visit http://localhost:5000/api/items in your browser or use a tool like curl to test the endpoint:

curl http://localhost:5000/api/items

Handling Requests and Responses

Flask simplifies request handling. Access request data, parse JSON, and send responses effortlessly.

from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/greet', methods=['POST'])
def greet_user():
    data = request.get_json()
    name = data.get('name', 'Guest')
    greeting = f"Hello, {name}!"
    return jsonify({'greeting': greeting})
if __name__ == '__main__':
    app.run(debug=True)

Test the new endpoint:

curl -X POST -H "Content-Type: application/json" -d '{"name": "Sachin"}' http://localhost:5000/api/greet

Todo API

Create a simple Todo API with endpoints for listing, creating, and deleting tasks. Define routes and use a list to store tasks.

from flask import Flask, jsonify, request
app = Flask(__name__)
tasks = []
@app.route('/api/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})
@app.route('/api/tasks', methods=['POST'])
def create_task():
    data = request.get_json()
    task = {'id': len(tasks) + 1, 'title': data.get('title', ''), 'done': False}
    tasks.append(task)
    return jsonify({'task': task}), 201
@app.route('/api/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    task = next((t for t in tasks if t['id'] == task_id), None)
    if task:
        tasks.remove(task)
        return jsonify({'result': True})
    else:
        return jsonify({'result': False, 'message': 'Task not found'}), 404
if __name__ == '__main__':
    app.run(debug=True)

Test the Todo API with various requests to /api/tasks.

Refer more on python here :

Author: Freshers