DeveloperBreeze

Creating a Simple REST API with Flask

In this tutorial, we will walk through the process of building a simple REST API using Flask, a lightweight and flexible web framework for Python. We will cover setting up the Flask environment, creating endpoints, handling HTTP requests, and returning JSON responses.


Introduction to REST APIs

A REST API (Representational State Transfer Application Programming Interface) is a set of rules that allow applications to communicate with each other over the web. REST APIs are commonly used to build web services and are known for their simplicity and scalability. They rely on stateless communication, typically using HTTP methods like GET, POST, PUT, DELETE, etc.


Setting Up the Flask Environment

Step 1: Install Flask

Make sure Python is installed on your machine. Then, install Flask using pip:

pip install Flask

Step 2: Create a Project Directory

mkdir flask_rest_api
cd flask_rest_api

Step 3: Create a Virtual Environment

python -m venv venv

Activate the virtual environment:

  • On Windows:
  venv\Scripts\activate
  • On macOS/Linux:
  source venv/bin/activate

Building the REST API

Step 1: Create the Flask Application

Create a file named app.py and add:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask REST API!"

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

Run the application:

python app.py

Visit http://127.0.0.1:5000/ in your browser to see the welcome message.


Step 2: Create an API Endpoint

from flask import Flask, jsonify

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

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

Step 3: Handle HTTP Methods (GET, POST, PUT, DELETE)

from flask import Flask, jsonify, request, abort

app = Flask(__name__)

items = [
    {"id": 1, "name": "Item 1", "price": 100},
    {"id": 2, "name": "Item 2", "price": 150},
    {"id": 3, "name": "Item 3", "price": 200}
]

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    return jsonify(item)

@app.route('/api/items', methods=['POST'])
def create_item():
    if not request.json or 'name' not in request.json or 'price' not in request.json:
        abort(400)
    new_item = {
        "id": items[-1]['id'] + 1 if items else 1,
        "name": request.json['name'],
        "price": request.json['price']
    }
    items.append(new_item)
    return jsonify(new_item), 201

@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    if not request.json:
        abort(400)
    item['name'] = request.json.get('name', item['name'])
    item['price'] = request.json.get('price', item['price'])
    return jsonify(item)

@app.route('/api/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    item = next((item for item in items if item["id"] == item_id), None)
    if item is None:
        abort(404)
    items.remove(item)
    return jsonify({"result": True})

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

Explanation

MethodEndpointDescription
GET/api/itemsRetrieves all items.
GET/api/items/<item_id>Retrieves a specific item by ID.
POST/api/itemsAdds a new item (requires name and price).
PUT/api/items/<item_id>Updates an existing item by ID.
DELETE/api/items/<item_id>Deletes an item by ID.

Testing the API

You can use Postman or curl to test the API.

  • Get all items:
  curl http://127.0.0.1:5000/api/items
  • Get a specific item:
  curl http://127.0.0.1:5000/api/items/1
  • Create a new item:
  curl -X POST -H "Content-Type: application/json" -d '{"name": "Item 4", "price": 250}' http://127.0.0.1:5000/api/items
  • Update an existing item:
  curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Item 2"}' http://127.0.0.1:5000/api/items/2
  • Delete an item:
  curl -X DELETE http://127.0.0.1:5000/api/items/3

Conclusion

In this tutorial, we built a simple REST API using Flask that can handle basic CRUD operations. This fundamental skill is crucial for web developers and serves as a solid foundation for building more complex APIs. You can extend this by adding authentication, database integration, and deploying your Flask application to production.

Related Posts

More content you might like

Tutorial
python

Build a Facial Recognition Attendance System

Use the face_recognition library to encode faces from the dataset. This step creates unique numerical representations for each face.

import os
import face_recognition
import cv2
import pickle

# Path to dataset
DATASET_PATH = "dataset"
ENCODINGS_FILE = "encodings.pickle"

def encode_faces():
    known_encodings = []
    known_names = []

    # Iterate through each person's folder
    for person in os.listdir(DATASET_PATH):
        person_path = os.path.join(DATASET_PATH, person)
        if not os.path.isdir(person_path):
            continue

        # Process each image
        for img_file in os.listdir(person_path):
            img_path = os.path.join(person_path, img_file)
            image = face_recognition.load_image_file(img_path)
            face_encodings = face_recognition.face_encodings(image)

            if face_encodings:
                known_encodings.append(face_encodings[0])
                known_names.append(person)

    # Save encodings to a file
    with open(ENCODINGS_FILE, "wb") as f:
        pickle.dump({"encodings": known_encodings, "names": known_names}, f)

    print("Encodings saved!")

encode_faces()

Dec 10, 2024
Read More
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

Laravel's Http facade simplifies making POST requests to external APIs. Here’s how you can send a basic POST request with some data:

use Illuminate\Support\Facades\Http;

$response = Http::post('https://api.example.com/endpoint', [
    'key1' => 'value1',
    'key2' => 'value2',
]);

dd($response->body()); // Display the raw response body

Oct 24, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

  • Simplicity: SQLite's serverless architecture simplifies database management.
  • Efficiency: sqlite3 provides a robust API to perform complex SQL operations seamlessly.
  • Security: Always prioritize the security of your data by following best practices.

As you continue developing, consider exploring more advanced topics such as database migrations, indexing for performance optimization, and integrating with ORMs (Object-Relational Mappers) for more complex data interactions.

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

To delete tasks, update App.js with a delete button for each task:

const deleteTask = (id) => {
  axios.delete(`http://127.0.0.1:5000/tasks/${id}`)
    .then(() => {
      setTasks(tasks.filter(task => task.id !== id));
    })
    .catch(error => console.log(error));
};

Sep 30, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!