Skip to content

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

Table of Contents

  1. Prerequisites
  2. Setup
  3. Creating the Flask API
  4. Running the API
  5. Testing the API
  6. Extending the API
  7. Conclusion

Prerequisites

Before you begin, ensure you have the following installed:

  • Python 3.6 or higher: You can download it from python.org.
  • pip: Python's package installer (comes with Python).
  • Virtual Environment (optional but recommended): To manage dependencies.

Setup

  1. Create a Project Directory

    mkdir flask_api
    cd flask_api
  2. Set Up a Virtual Environment

    It's good practice to use a virtual environment to manage dependencies.

    python3 -m venv venv

    Activate the virtual environment:

    • On Windows:

      venv\Scripts\activate
    • On macOS and Linux:

      source venv/bin/activate
  3. Install Flask

    pip install Flask

Creating the Flask API

Project Structure

Here's a simple project structure:

flask_api/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   └── models.py
│
├── venv/
│
├── requirements.txt
└── run.py

Writing the Code

1. Initialize the Flask App

Create the __init__.py file inside the app directory:

# app/__init__.py

from flask import Flask
from flask import jsonify

def create_app():
    app = Flask(__name__)

    # Import and register blueprints
    from .routes import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # Error handling
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({'error': 'Not found'}), 404

    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({'error': 'Internal server error'}), 500

    return app

2. Define Routes

Create the routes.py file inside the app directory:

# app/routes.py

from flask import Blueprint, request, jsonify

main = Blueprint('main', __name__)

# In-memory data store
items = []

@main.route('/', methods=['GET'])
def home():
    return jsonify({'message': 'Welcome to the Flask API!'})

@main.route('/items', methods=['GET'])
def get_items():
    return jsonify({'items': items})

@main.route('/items', methods=['POST'])
def add_item():
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Bad Request', 'message': 'Name is required'}), 400
    item = {
        'id': len(items) + 1,
        'name': data['name']
    }
    items.append(item)
    return jsonify({'item': item}), 201

@main.route('/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:
        return jsonify({'item': item})
    else:
        return jsonify({'error': 'Item not found'}), 404

@main.route('/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Bad Request', 'message': 'Name is required'}), 400
    item = next((item for item in items if item['id'] == item_id), None)
    if item:
        item['name'] = data['name']
        return jsonify({'item': item})
    else:
        return jsonify({'error': 'Item not found'}), 404

@main.route('/items/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
    global items
    item = next((item for item in items if item['id'] == item_id), None)
    if item:
        items = [itm for itm in items if itm['id'] != item_id]
        return jsonify({'message': 'Item deleted'})
    else:
        return jsonify({'error': 'Item not found'}), 404

3. (Optional) Define Models

If you plan to use a database, you can define your models in models.py. For simplicity, we'll skip this in the basic setup.

4. Create the run.py File

This file will serve as the entry point to run the Flask application.

# run.py

from app import create_app

app = create_app()

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

5. Generate requirements.txt

It's helpful to have a requirements.txt file for dependencies.

pip freeze > requirements.txt

The requirements.txt should include:

Flask==2.3.2

(Note: The exact version may vary.)

Running the API

  1. Ensure the Virtual Environment is Activated

    # On Windows
    venv\Scripts\activate
    
    # On macOS and Linux
    source venv/bin/activate
  2. Run the Application

    python run.py

    You should see output similar to:

    * Serving Flask app 'run'
    * Debug mode: on
    WARNING: This is a development server. Do not use it in a production deployment.
    * Running on http://127.0.0.1:5000
    * Restarting with stat
    

    The API is now running at http://127.0.0.1:5000.

Testing the API

You can test the API using tools like Postman, cURL, or even your web browser for GET requests.

1. GET Home

  • Endpoint: GET /
  • Description: Returns a welcome message.

Example using cURL:

curl http://127.0.0.1:5000/

Response:

{
  "message": "Welcome to the Flask API!"
}

2. GET All Items

  • Endpoint: GET /items
  • Description: Retrieves all items.

Example:

curl http://127.0.0.1:5000/items

Response:

{
  "items": []
}

3. POST Add an Item

  • Endpoint: POST /items
  • Description: Adds a new item.
  • Payload: JSON object with a name field.

Example:

curl -X POST http://127.0.0.1:5000/items \
     -H "Content-Type: application/json" \
     -d '{"name": "Sample Item"}'

Response:

{
  "item": {
    "id": 1,
    "name": "Sample Item"
  }
}

4. GET Single Item

  • Endpoint: GET /items/<id>
  • Description: Retrieves a single item by ID.

Example:

curl http://127.0.0.1:5000/items/1

Response:

{
  "item": {
    "id": 1,
    "name": "Sample Item"
  }
}

5. PUT Update an Item

  • Endpoint: PUT /items/<id>
  • Description: Updates an existing item's name.
  • Payload: JSON object with a name field.

Example:

curl -X PUT http://127.0.0.1:5000/items/1 \
     -H "Content-Type: application/json" \
     -d '{"name": "Updated Item"}'

Response:

{
  "item": {
    "id": 1,
    "name": "Updated Item"
  }
}

6. DELETE an Item

  • Endpoint: DELETE /items/<id>
  • Description: Deletes an item by ID.

Example:

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

Response:

{
  "message": "Item deleted"
}

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages