{"id":20423574,"url":"https://github.com/lsfratel/restcraft","last_synced_at":"2025-09-24T07:32:12.430Z","repository":{"id":232425564,"uuid":"784328285","full_name":"lsfratel/restcraft","owner":"lsfratel","description":"RestCraft is a lightweight WSGI framework for Python.","archived":false,"fork":false,"pushed_at":"2024-11-28T03:50:52.000Z","size":190,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-14T20:37:11.676Z","etag":null,"topics":["bottlepy","django","flask","python","restcraft","web-framework","wsgi","wsgi-framework"],"latest_commit_sha":null,"homepage":"","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/lsfratel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-04-09T16:25:28.000Z","updated_at":"2024-11-28T03:46:26.000Z","dependencies_parsed_at":"2024-04-14T16:29:23.654Z","dependency_job_id":"e6754afe-123d-4a42-9414-7b23b6f57109","html_url":"https://github.com/lsfratel/restcraft","commit_stats":null,"previous_names":["lsfratel/restipy"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsfratel%2Frestcraft","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsfratel%2Frestcraft/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsfratel%2Frestcraft/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsfratel%2Frestcraft/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lsfratel","download_url":"https://codeload.github.com/lsfratel/restcraft/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234054879,"owners_count":18772389,"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":["bottlepy","django","flask","python","restcraft","web-framework","wsgi","wsgi-framework"],"created_at":"2024-11-15T07:06:57.062Z","updated_at":"2025-09-24T07:32:06.913Z","avatar_url":"https://github.com/lsfratel.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# RestCraft\n\nRestCraft is a lightweight, modular framework designed to build modern web applications in Python. It provides essential tools and components to manage HTTP requests, responses, routing, and middleware, allowing you to focus on building features without being overwhelmed by boilerplate code.\n\n### Key Features\n\n- **Zero External Dependencies**: RestCraft is built entirely with Python's standard library, ensuring a minimal footprint and maximum compatibility.\n- **Powerful Routing System**: Support for dynamic and static routes, route merging, and modular blueprints for better organization.\n- **Request and Response Handling**: A clean and extensible API to manage HTTP requests, responses, cookies, and headers.\n- **Pluggable Architecture**: Add plugins to extend functionality with fine-grained control over their application.\n- **Built-in Middleware for CORS**: Enable Cross-Origin Resource Sharing with a simple plugin.\n- **Exception Handling**: Centralized error handling with customizable exception responses.\n\nWhether you're building a simple API or a large-scale application, RestCraft gives you the flexibility and control you need while staying lightweight and dependency-free.\n\n## Installation\n\nTo install **RestCraft**, just pip install:\n\n```bash\npip install restcraft\n```\n\n## Getting Started\n\nHere’s a quick example to set up and run a simple **RestCraft** application:\n\n```python\nfrom restcraft import RestCraft, Router, JSONResponse\nfrom restcraft.views import metadata\n\nfrom .config import configuration\n\n# Define your views\nclass HelloWorldView:\n    @metadata(methods=[\"GET\"])\n    def get(self):\n        return JSONResponse({\"message\": \"Hello, World!\"})\n\n# Set up the application\napp = RestCraft(config=configuration)\n\n# Set up the router\nrouter = Router()\nrouter.add_route(\"/hello\", HelloWorldView())\napp.register_router(router)\n\n# Run the application using a WSGI server\nif __name__ == \"__main__\":\n    from wsgiref.simple_server import make_server\n    server = make_server(\"127.0.0.1\", 8000, app)\n    print(\"Serving on http://127.0.0.1:8000\")\n    server.serve_forever()\n```\n\n## Core Concepts\n\n### Routes\n\nRestCraft provides a powerful routing system to map URL paths to specific views. The `Router` class allows you to register routes, handle dynamic parameters, and merge routers for modular and reusable routing logic.\n\n#### Adding Routes\n\nTo add a route, use the `add_route` method. Specify the path and the corresponding view object or class:\n\n```python\nfrom restcraft.http.router import Router\nfrom restcraft.http.response import JSONResponse\nfrom restcraft.views import metadata\n\nclass MyView:\n    @metadata(methods=[\"GET\"])\n    def hello(self):\n        return JSONResponse({\"message\": \"Hello, World!\"})\n\nrouter = Router()\nrouter.add_route(\"/hello\", MyView())\n```\n\n#### Dynamic Routes\n\nDynamic segments in paths are defined with a `\u003c` prefix and `\u003e` suffix. Dynamic routes allow you to capture parts of the URL and pass them as parameters to the handler:\n\n```python\nclass UserView:\n    @metadata(methods=[\"GET\"])\n    def get_user(self, id):\n        return JSONResponse({\"user_id\": id})\n\nrouter.add_route(\"/user/\u003cid\u003e\", UserView())\nrouter.add_route(r\"/user/\u003cid:\\d+\u003e\", UserView())\n\n# Example:\n# GET /user/42 -\u003e {\"user_id\": \"42\"}\n```\n\n#### Merging Routers\n\nThe `merge` function allows you to combine multiple routers into a single router. This enables modular routing, similar to blueprints in other frameworks, making it easy to organize your application by grouping related routes.\n\n```python\n# Define a \"users\" module\nusers_router = Router(prefix=\"/users\")\n\nclass UserView:\n    @metadata(methods=[\"GET\"])\n    def list_users(self):\n        return JSONResponse({\"users\": []})\n\n    @metadata(methods=[\"POST\"])\n    def create_user(self):\n        return JSONResponse({\"message\": \"User created\"})\n\nusers_router.add_route(\"/\", UserView())\n\n# Define a \"products\" module\nproducts_router = Router(prefix=\"/products\")\n\nclass ProductView:\n    @metadata(methods=[\"GET\"])\n    def list_products(self):\n        return JSONResponse({\"products\": []})\n\nproducts_router.add_route(\"/\", ProductView())\n\n# Merge modules into the main router\napp_router = Router()\napp_router.merge(users_router)\napp_router.merge(products_router)\n\n# Example:\n# GET /users -\u003e {\"users\": []}\n# GET /products -\u003e {\"products\": []}\n```\n\n### Request Handling\n\nAccess request properties like headers, query parameters, JSON payloads, forms, and file uploads:\n\n```python\nfrom restcraft.http import request\n\nclass UserView:\n    @metadata(methods=[\"POST\"])\n    def create(self):\n        data = request.json\n        return JSONResponse({\"received\": data})\n```\n\n### Plugins\n\nExtend functionality using plugins. Plugins in RestCraft are middleware-like components that can modify the behavior of request handlers. Each plugin can be selectively applied to specific methods by using the `metadata` decorator.\n\n#### Using Plugins\n\nTo register a plugin, use the `register_plugin` method of the `RestCraft` application:\n\n```python\nfrom restcraft.contrib.plugins.cors_plugin import CORSPlugin\n\nplugin = CORSPlugin(allow_origins=[\"http://example.com\"])\napp.register_plugin(plugin)\n```\n\n#### Controlling Plugin Execution with Metadata\n\nThe `metadata` decorator allows you to specify which plugins should run (or be excluded) for a particular method. By default, all plugins run on all methods unless specified otherwise.\n\n- **Include Plugins**: List plugin names to explicitly allow them.\n- **Exclude Plugins**: Prefix the plugin name with `-` to exclude it.\n\nHere’s an example:\n\n```python\nfrom restcraft.http.response import JSONResponse\nfrom restcraft.views import metadata\n\nclass MyView:\n    # Allow all plugins (default behavior)\n    @metadata(methods=[\"GET\"])\n    def all_plugins_allowed(self):\n        return JSONResponse({\"message\": \"All plugins are allowed\"})\n\n    # Only allow 'cors_plugin' to run\n    @metadata(methods=[\"POST\"], plugins=[\"cors_plugin\"])\n    def only_cors_plugin(self):\n        return JSONResponse({\"message\": \"Only CORS plugin will run\"})\n\n    # Exclude 'auth_plugin'\n    @metadata(methods=[\"DELETE\"], plugins=[\"...\", \"-auth_plugin\"])\n    def exclude_auth_plugin(self):\n        return JSONResponse({\"message\": \"All plugins except 'auth_plugin' will run\"})\n```\n\n#### Writing Your Own Plugin\n\nTo create a custom plugin, subclass the `Plugin` class and implement the `before_handler` or `before_route` method:\n\n```python\nfrom restcraft.plugin import Plugin\n\nclass CustomHeaderPlugin(Plugin):\n    name = \"custom_header_plugin\"\n\n    def before_handler(self, handler, metadata):\n        def wrapper(*args, **kwargs):\n            response = handler(*args, **kwargs)\n            response.headers[\"X-Custom-Header\"] = \"My Custom Value\"\n            return response\n        return wrapper\n```\n\nRegister your plugin with the application:\n\n```python\nplugin = CustomHeaderPlugin()\napp.register_plugin(plugin)\n```\n\n#### Plugin Execution Order\n\nPlugins are applied in the order they are registered in the application. To control execution order, register plugins in the desired sequence:\n\n```python\napp.register_plugin(PluginA())\napp.register_plugin(PluginB())\n```\n\n## File Uploads\n\nRestCraft handles file uploads efficiently, writing large files to disk-backed temporary storage. Here's how you can access uploaded files:\n\n```python\nclass FileUploadView:\n    @metadata(methods=[\"POST\"])\n    def upload(self):\n        file_data = request.files.get(\"file\")\n        return JSONResponse({\n            \"filename\": file_data[\"filename\"],\n            \"content_type\": file_data[\"content_type\"],\n        })\n```\n\n## Cookies\n\nRestCraft includes a powerful and flexible cookie management system inspired by [Remix.run](https://remix.run). With RestCraft, you can easily create, parse, sign, and validate cookies, enabling secure state management for your web applications.\n\n### Key Features\n\n- **Serialization and Parsing**: Effortlessly serialize Python objects into cookies and parse them back into Python objects.\n- **Signed Cookies**: Use secret keys to sign cookies, ensuring their integrity and protecting against tampering.\n- **Expiration and Max-Age**: Automatically manage cookie expiration with built-in support for `Expires` and `Max-Age` attributes.\n- **Secure Defaults**: Cookies are configured to be `HttpOnly` and `Secure` by default, ensuring they are protected from client-side scripts and transmitted only over HTTPS.\n\n### Example Usage\n\n#### Creating and Serializing a Cookie\n\n```python\nfrom restcraft.http import Cookie\n\n# Create a new cookie with secure options\ncookie = Cookie(\"user_session\", options={\"secrets\": [\"my_secret_key\"], \"secure\": True})\n\nclass MyView:\n\n    @metadata(methods=[\"GET\"])\n    def list(self):\n        # read\n        user_info = cookie.parse(request.headers[\"cookie\"])\n\n        # set\n        return JSONResponse(data, headers={\"Set-Cookie\": cookie.serialize(user_info, overrides={\"max_age\": 60})})\n```\n\n## Custom Exception Handling\n\nDefine custom exception handlers for your application:\n\n```python\nfrom restcraft.exceptions import RestCraftException\n\n@app.register_exception(RestCraftException)\ndef handle_restcraft_exception(exc):\n    return JSONResponse({\"error\": exc.message}, status=exc.status)\n```\n\n## Contributing\n\nContributions are welcome! If you'd like to improve RestCraft, follow these steps:\n\n1. Fork the repository.\n2. Create a new branch.\n3. Make your changes and write tests.\n4. Submit a pull request.\n\n## License\n\nThis project is licensed under the MIT License. See the `LICENSE` file for details.\n\n## Acknowledgements\n\nSpecial thanks to all contributors and the Python community for inspiring this project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flsfratel%2Frestcraft","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flsfratel%2Frestcraft","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flsfratel%2Frestcraft/lists"}