{"id":26604193,"url":"https://github.com/sc4rfurry/apifrom","last_synced_at":"2025-03-23T19:28:42.539Z","repository":{"id":282052383,"uuid":"946300552","full_name":"sc4rfurry/apifrom","owner":"sc4rfurry","description":"APIFromAnything is a production-grade Python library that transforms ordinary Python functions into fully-functional REST API endpoints using a decorator-based approach.","archived":false,"fork":false,"pushed_at":"2025-03-12T14:20:30.000Z","size":476,"stargazers_count":1,"open_issues_count":6,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-12T15:27:51.696Z","etag":null,"topics":["api","async","framework","rest","web"],"latest_commit_sha":null,"homepage":"https://sc4rfurry.github.io/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sc4rfurry.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/contributing.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"docs/security.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-10T23:34:34.000Z","updated_at":"2025-03-12T14:20:34.000Z","dependencies_parsed_at":"2025-03-12T15:38:11.896Z","dependency_job_id":null,"html_url":"https://github.com/sc4rfurry/apifrom","commit_stats":null,"previous_names":["sc4rfurry/apifrom"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sc4rfurry%2Fapifrom","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sc4rfurry%2Fapifrom/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sc4rfurry%2Fapifrom/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sc4rfurry%2Fapifrom/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sc4rfurry","download_url":"https://codeload.github.com/sc4rfurry/apifrom/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245156977,"owners_count":20569948,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","async","framework","rest","web"],"created_at":"2025-03-23T19:28:41.827Z","updated_at":"2025-03-23T19:28:42.513Z","avatar_url":"https://github.com/sc4rfurry.png","language":"Python","readme":"# 🚀 APIFromAnything\r\n\r\n\u003cdiv align=\"center\"\u003e\r\n\r\n[![PyPI version](https://img.shields.io/badge/pypi-v1.0.0-blue.svg)](https://pypi.org/project/apifrom/)\r\n[![Documentation Status](https://readthedocs.org/projects/apifrom/badge/?version=latest)](https://apifrom.readthedocs.io/en/latest/?badge=latest)\r\n[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)\r\n[![Python Versions](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue)](https://pypi.org/project/apifrom/)\r\n\r\n**Transform Python functions into powerful API endpoints with minimal code changes**\r\n\r\n[Documentation](https://apifrom.readthedocs.io/) | [Quick Start](#-quick-start) | [Examples](#-examples) | [Contributing](#-contributing)\r\n\r\n![CodeQL](https://github.com/sc4rfurry/apifrom/workflows/CodeQL/badge.svg)\r\n![Dependency Review](https://github.com/sc4rfurry/apifrom/workflows/Dependency%20Review/badge.svg)\r\n\r\n\u003c/div\u003e\r\n\r\n## 🔍 Overview\r\n\r\nAPIFromAnything is a powerful Python framework that transforms regular Python functions into fully-featured API endpoints with minimal code changes. It's designed to simplify API development while providing enterprise-grade features like middleware support, security, performance optimizations, and monitoring.\r\n\r\nWhether you're building a simple microservice or a complex API backend, APIFromAnything provides the tools you need to get up and running quickly without sacrificing flexibility or performance.\r\n\r\n## ✨ Key Features\r\n\r\n### Core Functionality\r\n- **🔄 Simple API Creation**: Transform any Python function into an API endpoint with a single decorator\r\n- **⚡ Full Async Support**: Native support for async/await throughout the entire framework\r\n- **🧩 Extensible Architecture**: Modular design allows for easy customization and extension\r\n\r\n### Middleware \u0026 Processing\r\n- **🔄 Middleware System**: Comprehensive middleware architecture for request/response processing\r\n- **🔄 Request/Response Hooks**: Customize request handling and response generation\r\n- **📦 Content Negotiation**: Automatic content type negotiation and serialization\r\n\r\n### Security Features\r\n- **🔒 Authentication**: JWT, API key, Basic auth, OAuth2 support built-in\r\n- **🛡️ Protection**: CORS, CSRF, XSS protection mechanisms\r\n- **🔐 Security Headers**: CSP, HSTS, and other security headers\r\n- **🔍 Rate Limiting**: Configurable rate limiting to prevent abuse\r\n\r\n### Performance Optimizations\r\n- **⚡ Caching**: Multi-level caching system (memory, Redis, file)\r\n- **🔌 Connection Pooling**: Efficient database and HTTP connection management\r\n- **🔄 Request Coalescing**: Combine duplicate requests to reduce load\r\n- **📦 Batch Processing**: Process multiple requests efficiently\r\n\r\n### Documentation \u0026 Monitoring\r\n- **📚 API Docs**: Automatic OpenAPI documentation generation\r\n- **📊 Metrics**: Built-in metrics collection with Prometheus integration\r\n- **📈 Monitoring**: Grafana dashboards for visualization\r\n- **🚨 Alerting**: Pre-configured alerts for common issues\r\n\r\n## 📥 Installation\r\n\r\n### Using pip (Recommended)\r\n\r\n```bash\r\npip install apifrom\r\n```\r\n\r\n### Using Poetry\r\n\r\n```bash\r\npoetry add apifrom\r\n```\r\n\r\n### From Source\r\n\r\n```bash\r\ngit clone https://github.com/sc4rfurry/apifrom.git\r\ncd apifrom\r\npip install -e .\r\n```\r\n\r\n## 🚀 Quick Start\r\n\r\n### Basic API\r\n\r\n```python\r\nfrom apifrom import API\r\n\r\napp = API()\r\n\r\n@app.api(\"/hello/{name}\")\r\ndef hello(name: str):\r\n    return {\"message\": f\"Hello, {name}!\"}\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n### Async API\r\n\r\n```python\r\nfrom apifrom import API\r\n\r\napp = API()\r\n\r\n@app.api(\"/hello/{name}\")\r\nasync def hello(name: str):\r\n    # Async operations can be performed here\r\n    return {\"message\": f\"Hello, {name}!\"}\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n### With Middleware\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.middleware import CORSMiddleware, LoggingMiddleware\r\n\r\napp = API()\r\n\r\n# Add middleware\r\napp.add_middleware(CORSMiddleware, allow_origins=[\"*\"])\r\napp.add_middleware(LoggingMiddleware)\r\n\r\n@app.api(\"/hello/{name}\")\r\nasync def hello(name: str):\r\n    return {\"message\": f\"Hello, {name}!\"}\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n## 📝 Examples\r\n\r\n### RESTful API\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.security import JWTAuth\r\n\r\napp = API()\r\nauth = JWTAuth(secret_key=\"your-secret-key\")\r\n\r\n# User database (in-memory for example)\r\nusers = {}\r\n\r\n@app.api(\"/users\", methods=[\"POST\"])\r\nasync def create_user(username: str, email: str, password: str):\r\n    user_id = len(users) + 1\r\n    users[user_id] = {\"id\": user_id, \"username\": username, \"email\": email}\r\n    return {\"id\": user_id, \"username\": username, \"email\": email}\r\n\r\n@app.api(\"/users/{user_id}\", methods=[\"GET\"])\r\n@auth.requires_auth\r\nasync def get_user(user_id: int):\r\n    if user_id not in users:\r\n        return {\"error\": \"User not found\"}, 404\r\n    return users[user_id]\r\n\r\n@app.api(\"/users\", methods=[\"GET\"])\r\n@auth.requires_auth\r\nasync def list_users():\r\n    return list(users.values())\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n### With Caching\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.cache import MemoryCache\r\n\r\napp = API()\r\ncache = MemoryCache()\r\n\r\n@app.api(\"/expensive-operation\")\r\n@cache.cached(ttl=300)  # Cache for 5 minutes\r\nasync def expensive_operation():\r\n    # Simulate expensive operation\r\n    import time\r\n    time.sleep(2)\r\n    return {\"result\": \"This was expensive to calculate\"}\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n### With Database\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.db import Database\r\n\r\napp = API()\r\ndb = Database(\"sqlite:///app.db\")\r\n\r\n@app.api(\"/posts\", methods=[\"GET\"])\r\nasync def get_posts():\r\n    async with db.connection() as conn:\r\n        posts = await conn.fetch(\"SELECT * FROM posts\")\r\n    return {\"posts\": posts}\r\n\r\n@app.api(\"/posts\", methods=[\"POST\"])\r\nasync def create_post(title: str, content: str):\r\n    async with db.connection() as conn:\r\n        post_id = await conn.execute(\r\n            \"INSERT INTO posts (title, content) VALUES (?, ?)\",\r\n            title, content\r\n        )\r\n    return {\"id\": post_id, \"title\": title, \"content\": content}\r\n\r\nif __name__ == \"__main__\":\r\n    app.run()\r\n```\r\n\r\n### Example Directory\r\n\r\nThe project includes a comprehensive set of examples in the `examples/` directory:\r\n\r\n| Example | Description |\r\n|---------|-------------|\r\n| `simple_api.py` | Basic API with simple endpoints |\r\n| `async_api.py` | Demonstrates async/await functionality |\r\n| `combined_example.py` | Comprehensive example with multiple features |\r\n| `security_api.py` | Shows various security features |\r\n| `web_decorator_example_updated.py` | Demonstrates the web decorator for HTML endpoints |\r\n| `database_api.py` | Database integration example |\r\n| `cached_api.py` | Caching implementation |\r\n| `cors_api.py` | CORS middleware usage |\r\n| `csrf_protected_api.py` | CSRF protection |\r\n| `rate_limited_api.py` | Rate limiting functionality |\r\n| `monitoring_api.py` | Metrics and monitoring |\r\n| `serverless_api.py` | Serverless deployment |\r\n| `vercel_serverless_api.py` | Vercel-specific deployment |\r\n| `netlify_functions_api.py` | Netlify-specific deployment |\r\n| `file_upload_api.py` | File upload handling |\r\n| `error_handling_api.py` | Error handling and validation |\r\n| `pagination_api.py` | Pagination implementation |\r\n| `batch_processing_api.py` | Batch processing for performance |\r\n| `advanced_caching_api.py` | Advanced caching strategies |\r\n| `plugin_api.py` | Plugin system usage |\r\n| `advanced_plugin_api.py` | Advanced plugin development |\r\n\r\nTo run any example:\r\n\r\n```bash\r\n# Navigate to the examples directory\r\ncd examples\r\n\r\n# Run an example\r\npython simple_api.py\r\n```\r\n\r\n## 🏗️ Architecture\r\n\r\nAPIFromAnything follows a modular architecture designed for flexibility and extensibility:\r\n\r\n```\r\n┌─────────────────────────────────────────────────────────┐\r\n│                      APIFromAnything                     │\r\n├─────────────┬─────────────┬───────────────┬─────────────┤\r\n│   Routing   │  Middleware │   Security    │ Performance │\r\n├─────────────┼─────────────┼───────────────┼─────────────┤\r\n│ HTTP Server │   Database  │ Documentation │  Monitoring │\r\n└─────────────┴─────────────┴───────────────┴─────────────┘\r\n```\r\n\r\n- **Core**: The central component that manages the application lifecycle\r\n- **Routing**: Maps URLs to handler functions\r\n- **Middleware**: Processes requests and responses\r\n- **Security**: Handles authentication, authorization, and protection\r\n- **Performance**: Optimizes API performance\r\n- **HTTP Server**: Manages HTTP connections\r\n- **Database**: Provides database connectivity\r\n- **Documentation**: Generates API documentation\r\n- **Monitoring**: Collects and exposes metrics\r\n\r\n## 🔄 Middleware\r\n\r\nAPIFromAnything includes a comprehensive middleware system:\r\n\r\n| Middleware | Description |\r\n|------------|-------------|\r\n| `CORSMiddleware` | Handles Cross-Origin Resource Sharing |\r\n| `CSRFMiddleware` | Protects against Cross-Site Request Forgery |\r\n| `SecurityHeadersMiddleware` | Adds security headers to responses |\r\n| `RateLimitingMiddleware` | Limits request rates |\r\n| `CacheMiddleware` | Caches responses |\r\n| `LoggingMiddleware` | Logs requests and responses |\r\n| `CompressionMiddleware` | Compresses response data |\r\n| `AuthenticationMiddleware` | Handles authentication |\r\n\r\nExample:\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.middleware import CORSMiddleware, SecurityHeadersMiddleware\r\n\r\napp = API()\r\napp.add_middleware(CORSMiddleware, allow_origins=[\"https://example.com\"])\r\napp.add_middleware(SecurityHeadersMiddleware)\r\n```\r\n\r\n## 🔒 Security\r\n\r\nAPIFromAnything provides comprehensive security features:\r\n\r\n### Authentication\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.security import JWTAuth\r\n\r\napp = API()\r\nauth = JWTAuth(secret_key=\"your-secret-key\")\r\n\r\n@app.api(\"/protected\")\r\n@auth.requires_auth\r\nasync def protected():\r\n    return {\"message\": \"This is protected\"}\r\n```\r\n\r\n### CORS Protection\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.middleware import CORSMiddleware\r\n\r\napp = API()\r\napp.add_middleware(CORSMiddleware, \r\n                  allow_origins=[\"https://example.com\"],\r\n                  allow_methods=[\"GET\", \"POST\"],\r\n                  allow_headers=[\"Content-Type\", \"Authorization\"])\r\n```\r\n\r\n### Rate Limiting\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.middleware import RateLimitingMiddleware\r\n\r\napp = API()\r\napp.add_middleware(RateLimitingMiddleware, \r\n                  limit=100,\r\n                  period=60,  # 100 requests per minute\r\n                  key_func=lambda request: request.client.host)\r\n```\r\n\r\n## ⚡ Performance\r\n\r\nAPIFromAnything includes several performance optimization features:\r\n\r\n### Caching\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.cache import RedisCache\r\n\r\napp = API()\r\ncache = RedisCache(url=\"redis://localhost:6379/0\")\r\n\r\n@app.api(\"/expensive-operation\")\r\n@cache.cached(ttl=300)  # Cache for 5 minutes\r\nasync def expensive_operation():\r\n    # Expensive operation here\r\n    return {\"result\": \"Expensive calculation\"}\r\n```\r\n\r\n### Connection Pooling\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.db import Database\r\n\r\napp = API()\r\ndb = Database(\"postgresql://user:password@localhost/db\",\r\n             min_size=5,\r\n             max_size=20)\r\n\r\n@app.api(\"/users\")\r\nasync def get_users():\r\n    async with db.connection() as conn:\r\n        # Connection is taken from the pool\r\n        users = await conn.fetch(\"SELECT * FROM users\")\r\n    # Connection is returned to the pool\r\n    return {\"users\": users}\r\n```\r\n\r\n### Request Coalescing\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.performance import coalesce_requests\r\n\r\napp = API()\r\n\r\n@app.api(\"/data/{id}\")\r\n@coalesce_requests\r\nasync def get_data(id: str):\r\n    # If multiple requests for the same ID arrive simultaneously,\r\n    # only one database query will be executed\r\n    # and the result will be shared among all requests\r\n    return {\"data\": f\"Data for {id}\"}\r\n```\r\n\r\n## 📊 Monitoring\r\n\r\nAPIFromAnything includes built-in monitoring capabilities:\r\n\r\n### Prometheus Metrics\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.monitoring import setup_monitoring\r\n\r\napp = API()\r\nsetup_monitoring(app)\r\n\r\n# Metrics will be available at /metrics\r\n```\r\n\r\n### Custom Metrics\r\n\r\n```python\r\nfrom apifrom import API\r\nfrom apifrom.monitoring import Counter, Histogram\r\n\r\napp = API()\r\n\r\n# Define custom metrics\r\nrequest_counter = Counter(\"app_requests_total\", \"Total requests\")\r\nrequest_latency = Histogram(\"app_request_latency_seconds\", \"Request latency\")\r\n\r\n@app.api(\"/hello\")\r\nasync def hello():\r\n    # Increment counter\r\n    request_counter.inc()\r\n    \r\n    # Measure latency\r\n    with request_latency.time():\r\n        # Your code here\r\n        return {\"message\": \"Hello, World!\"}\r\n```\r\n\r\n## 🚀 Deployment\r\n\r\n### GitHub Actions\r\n\r\nThis project includes GitHub Actions workflows for continuous integration and deployment:\r\n\r\n- **Python Package**: Tests the code and publishes the package to PyPI when a new tag is pushed\r\n- **Documentation**: Builds and deploys the documentation to GitHub Pages\r\n- **ReadTheDocs**: Triggers a build on ReadTheDocs when documentation files are updated\r\n\r\nTo set up these workflows:\r\n\r\n1. Push your code to a GitHub repository\r\n2. Set up the necessary secrets in your repository settings:\r\n   - `PYPI_API_TOKEN`: API token for publishing to PyPI\r\n\r\nFor detailed instructions, see the [GitHub and ReadTheDocs Deployment Guide](https://apifrom.readthedocs.io/en/latest/github_deployment/).\r\n\r\n### Serverless\r\n\r\n#### AWS Lambda\r\n\r\n```python\r\n# handler.py\r\nfrom apifrom import API\r\nfrom apifrom.adapters import LambdaAdapter\r\n\r\napp = API()\r\n\r\n@app.api(\"/hello/{name}\")\r\nasync def hello(name: str):\r\n    return {\"message\": f\"Hello, {name}!\"}\r\n\r\n# Lambda handler\r\nhandler = LambdaAdapter(app).handler\r\n```\r\n\r\n#### Vercel\r\n\r\n```python\r\n# api/index.py\r\nfrom apifrom import API\r\nfrom apifrom.adapters import VercelAdapter\r\n\r\napp = API()\r\n\r\n@app.api(\"/hello/{name}\")\r\nasync def hello(name: str):\r\n    return {\"message\": f\"Hello, {name}!\"}\r\n\r\n# Vercel handler\r\nhandler = VercelAdapter(app).handler\r\n```\r\n\r\n## 📚 Documentation\r\n\r\nFor full documentation, visit [apifrom.readthedocs.io](https://apifrom.readthedocs.io/en/latest/).\r\n\r\nThe documentation includes:\r\n\r\n- **Getting Started Guide**: Quick introduction to APIFromAnything\r\n- **Core Concepts**: Detailed explanation of the framework's architecture\r\n- **API Reference**: Complete reference for all classes and functions\r\n- **Middleware Guide**: How to use and create middleware\r\n- **Security Guide**: How to secure your API\r\n- **Performance Guide**: How to optimize your API's performance\r\n- **Deployment Guide**: How to deploy your API to various platforms\r\n- **Examples**: Comprehensive examples for common use cases\r\n\r\n## 👥 Contributing\r\n\r\nContributions are welcome! Please feel free to submit a Pull Request.\r\n\r\n### Development Setup\r\n\r\n```bash\r\n# Clone the repository\r\ngit clone https://github.com/sc4rfurry/apifrom.git\r\ncd apifrom\r\n\r\n# Install dependencies\r\npip install -e \".[dev]\"\r\n\r\n# Run tests\r\npytest\r\n```\r\n\r\n### Code Style\r\n\r\nWe use [Black](https://github.com/psf/black) for code formatting and [isort](https://github.com/PyCQA/isort) for import sorting:\r\n\r\n```bash\r\n# Format code\r\nblack .\r\n\r\n# Sort imports\r\nisort .\r\n```\r\n\r\n### Testing\r\n\r\nWe use [pytest](https://docs.pytest.org/) for testing:\r\n\r\n```bash\r\n# Run all tests\r\npytest\r\n\r\n# Run tests with coverage\r\npytest --cov=apifrom\r\n\r\n# Run specific tests\r\npytest tests/test_api.py\r\n```\r\n\r\n## 📄 License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n---\r\n\r\n\u003cdiv align=\"center\"\u003e\r\n  \u003cp\u003eMade with ❤️ by the sc4rfurry\u003c/p\u003e\r\n  \u003cp\u003e\r\n    \u003ca href=\"https://github.com/sc4rfurry/apifrom\"\u003eGitHub\u003c/a\u003e •\r\n    \u003ca href=\"https://pypi.org/project/apifrom/\"\u003ePyPI\u003c/a\u003e •\r\n    \u003ca href=\"https://apifrom.readthedocs.io/en/latest/\"\u003eDocumentation\u003c/a\u003e\r\n  \u003c/p\u003e\r\n\u003c/div\u003e\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsc4rfurry%2Fapifrom","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsc4rfurry%2Fapifrom","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsc4rfurry%2Fapifrom/lists"}