xapi-guard-middleware


Namexapi-guard-middleware JSON
Version 1.0.6 PyPI version JSON
download
home_pageNone
SummaryXAPI Guard is a FastAPI middleware that protects your API endpoints by validating X-API-Key header.
upload_time2025-02-07 17:12:32
maintainerNone
docs_urlNone
authorAbdullah Alqahtani
requires_python<4.0,>=3.11
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # XAPI Guard Middleware

[![Downloads](https://img.shields.io/pypi/dm/xapi-guard-middleware)](https://pypi.org/project/xapi-guard-middleware/)
[![PyPI version](https://img.shields.io/pypi/v/xapi-guard-middleware
)](https://img.shields.io/pypi/v/xapi-guard-middleware)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![XAPI Guard](https://img.shields.io/badge/XAPI_Guard-1.0.6-blue)
![Python](https://img.shields.io/badge/Python->=3.11,<4.0-blue)
![FastAPI](https://img.shields.io/badge/FastAPI->=0.109.0,<0.115.8-blue)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Tests](https://img.shields.io/badge/Tests-Pytest-green)](https://docs.pytest.org/)
[![Coverage](https://img.shields.io/badge/Coverage-100%25-brightgreen)](https://coverage.py/)

XAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with `@guard.protect` to protect them.

## Features

- Protect your FastAPI endpoints by validating the `X-API-Key` header.
- Use `@guard.protect` to secure specific routes or entire routers.
- Easily configure which routes require protection and which are public.
- Automatically handle unauthorized access with appropriate error messages.
- Support for OpenAPI/Swagger documentation with protected routes.

## Installation

Choose your preferred installation method:

### Poetry (Recommended)
```bash
poetry add xapi-guard-middleware
```

### Pip
```bash
pip install xapi-guard-middleware
```

## Quick Start

```python
from fastapi import FastAPI, Depends, APIRouter
from xapi_guard_middleware.middleware import XAPIGuardMiddleware

app = FastAPI(title="XAPI Guard Middleware Example")

guard = XAPIGuardMiddleware(x_api_key="DEN#3xTezZDo1nJg1pO$tIrzQ9A")

# Routers for different route groups
admin_router = APIRouter(dependencies=[Depends(guard.protect)])
settings_router = APIRouter(dependencies=[Depends(guard.protect)])
public_router = APIRouter()

# General routes
@app.get("/", tags=["General"])
async def root():
    return {"message": "Hello World"}

@app.get("/health", tags=["General"])
async def health():
    return {"status": "healthy"}

# Public routes
@public_router.get("/public", tags=["Public"])
async def public():
    return {"message": "This is a public endpoint accessible to everyone."}

# Admin routes
@admin_router.get("/admin", tags=["Admin"])
async def admin():
    return {"message": "Welcome to the admin area!"}

# Settings routes
@settings_router.get("/settings", tags=["Settings"])
async def settings():
    return {"message": "Settings page, accessible only to authorized users."}

# Include the routers in the main app
app.include_router(public_router)
app.include_router(admin_router, prefix="/secure")
app.include_router(settings_router, prefix="/secure")
```

### Making Requests

```bash
# Unauthorized request (missing API key)
curl -X GET http://localhost:8000/secure/admin
# Response: {"detail": "X-API-Key header missing"}
# Status code: 401

# Unauthorized request (invalid API key)
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: wrong-key"
# Response: {"detail": "Invalid X-API-Key"}
# Status code: 403

# Authorized request
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: YOUR_API_KEY"
# Response: {"message": "Welcome to the admin area!"}
# Status code: 200
```

## Demo

```bash
git clone https://github.com/anqorithm/xapi-guard-middleware.git
cd xapi-guard-middleware
poetry install
poetry run uvicorn app:app --reload
```

* The FastAPI app is protected by the XAPI Guard Middleware
![image](./assets/1.png)

* X-API-Key header is missing
![image](./assets/2.png)

* X-API-Key header is invalid
![image](./assets/3.png)
![image](./assets/4.png)

* X-API-Key header is valid
![image](./assets/5.png)
![image](./assets/6.png)


## Contributing

Contributions are welcome! Please open an issue or submit a pull request.
## Contributors

- [Abdullah Alqahtani](https://github.com/anqorithm)

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "xapi-guard-middleware",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.11",
    "maintainer_email": null,
    "keywords": null,
    "author": "Abdullah Alqahtani",
    "author_email": "anqorithm@protonmail.com",
    "download_url": "https://files.pythonhosted.org/packages/2f/0e/a8d8a4eb77efcff34cdfb9b82a341fc61c66cc3b5b914028e3ffbc801237/xapi_guard_middleware-1.0.6.tar.gz",
    "platform": null,
    "description": "# XAPI Guard Middleware\n\n[![Downloads](https://img.shields.io/pypi/dm/xapi-guard-middleware)](https://pypi.org/project/xapi-guard-middleware/)\n[![PyPI version](https://img.shields.io/pypi/v/xapi-guard-middleware\n)](https://img.shields.io/pypi/v/xapi-guard-middleware)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n![XAPI Guard](https://img.shields.io/badge/XAPI_Guard-1.0.6-blue)\n![Python](https://img.shields.io/badge/Python->=3.11,<4.0-blue)\n![FastAPI](https://img.shields.io/badge/FastAPI->=0.109.0,<0.115.8-blue)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Tests](https://img.shields.io/badge/Tests-Pytest-green)](https://docs.pytest.org/)\n[![Coverage](https://img.shields.io/badge/Coverage-100%25-brightgreen)](https://coverage.py/)\n\nXAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with `@guard.protect` to protect them.\n\n## Features\n\n- Protect your FastAPI endpoints by validating the `X-API-Key` header.\n- Use `@guard.protect` to secure specific routes or entire routers.\n- Easily configure which routes require protection and which are public.\n- Automatically handle unauthorized access with appropriate error messages.\n- Support for OpenAPI/Swagger documentation with protected routes.\n\n## Installation\n\nChoose your preferred installation method:\n\n### Poetry (Recommended)\n```bash\npoetry add xapi-guard-middleware\n```\n\n### Pip\n```bash\npip install xapi-guard-middleware\n```\n\n## Quick Start\n\n```python\nfrom fastapi import FastAPI, Depends, APIRouter\nfrom xapi_guard_middleware.middleware import XAPIGuardMiddleware\n\napp = FastAPI(title=\"XAPI Guard Middleware Example\")\n\nguard = XAPIGuardMiddleware(x_api_key=\"DEN#3xTezZDo1nJg1pO$tIrzQ9A\")\n\n# Routers for different route groups\nadmin_router = APIRouter(dependencies=[Depends(guard.protect)])\nsettings_router = APIRouter(dependencies=[Depends(guard.protect)])\npublic_router = APIRouter()\n\n# General routes\n@app.get(\"/\", tags=[\"General\"])\nasync def root():\n    return {\"message\": \"Hello World\"}\n\n@app.get(\"/health\", tags=[\"General\"])\nasync def health():\n    return {\"status\": \"healthy\"}\n\n# Public routes\n@public_router.get(\"/public\", tags=[\"Public\"])\nasync def public():\n    return {\"message\": \"This is a public endpoint accessible to everyone.\"}\n\n# Admin routes\n@admin_router.get(\"/admin\", tags=[\"Admin\"])\nasync def admin():\n    return {\"message\": \"Welcome to the admin area!\"}\n\n# Settings routes\n@settings_router.get(\"/settings\", tags=[\"Settings\"])\nasync def settings():\n    return {\"message\": \"Settings page, accessible only to authorized users.\"}\n\n# Include the routers in the main app\napp.include_router(public_router)\napp.include_router(admin_router, prefix=\"/secure\")\napp.include_router(settings_router, prefix=\"/secure\")\n```\n\n### Making Requests\n\n```bash\n# Unauthorized request (missing API key)\ncurl -X GET http://localhost:8000/secure/admin\n# Response: {\"detail\": \"X-API-Key header missing\"}\n# Status code: 401\n\n# Unauthorized request (invalid API key)\ncurl -X GET http://localhost:8000/secure/admin -H \"X-API-Key: wrong-key\"\n# Response: {\"detail\": \"Invalid X-API-Key\"}\n# Status code: 403\n\n# Authorized request\ncurl -X GET http://localhost:8000/secure/admin -H \"X-API-Key: YOUR_API_KEY\"\n# Response: {\"message\": \"Welcome to the admin area!\"}\n# Status code: 200\n```\n\n## Demo\n\n```bash\ngit clone https://github.com/anqorithm/xapi-guard-middleware.git\ncd xapi-guard-middleware\npoetry install\npoetry run uvicorn app:app --reload\n```\n\n* The FastAPI app is protected by the XAPI Guard Middleware\n![image](./assets/1.png)\n\n* X-API-Key header is missing\n![image](./assets/2.png)\n\n* X-API-Key header is invalid\n![image](./assets/3.png)\n![image](./assets/4.png)\n\n* X-API-Key header is valid\n![image](./assets/5.png)\n![image](./assets/6.png)\n\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request.\n## Contributors\n\n- [Abdullah Alqahtani](https://github.com/anqorithm)\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "XAPI Guard is a FastAPI middleware that protects your API endpoints by validating X-API-Key header.",
    "version": "1.0.6",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9f352651f7b82c4d60bc68112a8301b454f5f2edecdb3cfbd1cf365ec202c948",
                "md5": "ce42b68a2276db478c0ff1f19a502dc7",
                "sha256": "6628c482c17076e2a7a2fddbae7602b36638b6dc61dc4996494487b1a95bfbe0"
            },
            "downloads": -1,
            "filename": "xapi_guard_middleware-1.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ce42b68a2276db478c0ff1f19a502dc7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.11",
            "size": 4743,
            "upload_time": "2025-02-07T17:12:31",
            "upload_time_iso_8601": "2025-02-07T17:12:31.208896Z",
            "url": "https://files.pythonhosted.org/packages/9f/35/2651f7b82c4d60bc68112a8301b454f5f2edecdb3cfbd1cf365ec202c948/xapi_guard_middleware-1.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2f0ea8d8a4eb77efcff34cdfb9b82a341fc61c66cc3b5b914028e3ffbc801237",
                "md5": "64bd8f21a055fd2078046e0595ebe164",
                "sha256": "ab3bc3c50296d28f433793946796376fd0885af431bfbbb86162c9fffbe55eab"
            },
            "downloads": -1,
            "filename": "xapi_guard_middleware-1.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "64bd8f21a055fd2078046e0595ebe164",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.11",
            "size": 3750,
            "upload_time": "2025-02-07T17:12:32",
            "upload_time_iso_8601": "2025-02-07T17:12:32.623668Z",
            "url": "https://files.pythonhosted.org/packages/2f/0e/a8d8a4eb77efcff34cdfb9b82a341fc61c66cc3b5b914028e3ffbc801237/xapi_guard_middleware-1.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-02-07 17:12:32",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "xapi-guard-middleware"
}
        
Elapsed time: 1.44112s