{"id":14131918,"url":"https://github.com/hasssanezzz/PyMicroHTTP","last_synced_at":"2025-08-04T11:32:45.559Z","repository":{"id":252604346,"uuid":"840906817","full_name":"hasssanezzz/PyMicroHTTP","owner":"hasssanezzz","description":"A minimal speedrun project, HTTP server from scratch.","archived":false,"fork":false,"pushed_at":"2024-08-14T13:43:17.000Z","size":31,"stargazers_count":32,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-25T09:42:11.157Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://pypi.org/project/pymicrohttp","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hasssanezzz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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,"publiccode":null,"codemeta":null}},"created_at":"2024-08-11T03:53:27.000Z","updated_at":"2025-07-12T23:59:22.000Z","dependencies_parsed_at":"2024-08-11T06:35:55.311Z","dependency_job_id":null,"html_url":"https://github.com/hasssanezzz/PyMicroHTTP","commit_stats":null,"previous_names":["hasssanezzz/http-from-scratch","hasssanezzz/pymicrohttp"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/hasssanezzz/PyMicroHTTP","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hasssanezzz%2FPyMicroHTTP","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hasssanezzz%2FPyMicroHTTP/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hasssanezzz%2FPyMicroHTTP/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hasssanezzz%2FPyMicroHTTP/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hasssanezzz","download_url":"https://codeload.github.com/hasssanezzz/PyMicroHTTP/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hasssanezzz%2FPyMicroHTTP/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268689336,"owners_count":24291075,"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","status":"online","status_checked_at":"2025-08-04T02:00:09.867Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2024-08-16T03:00:32.502Z","updated_at":"2025-08-04T11:32:45.133Z","avatar_url":"https://github.com/hasssanezzz.png","language":"Python","funding_links":[],"categories":["Projects"],"sub_categories":["Web Frameworks"],"readme":"# PyMicroHTTP\n\nPyMicroHTTP is a lightweight, flexible HTTP framework built from scratch in Python. It provides a simple way to create HTTP services without heavy external dependencies, making it ideal for learning purposes or small projects.\n\n__NOTE: this is a toy project and not production ready.__\n\n## Content Table\n\n### PyMicroHTTP\n\n* **[PyMicroHTTP](#pymicrohttp)**\n    * What is PyMicroHTTP? (Introduction)\n    * **[Features](#features)** (List of functionalities)\n    * **[Installation](#installation)** (How to install)\n    * **[Quick Start](#quick-start)** (Getting started example)\n        * Running the example\n    * **[Routing](#routing)** (Defining routes)\n        * Basic Routing Syntax\n        * **[Path Parameters](#path-parameters)** (Accessing dynamic parts of the URL)\n        * **[Query Parameters](#query-parameters)** (Accessing data after the '?' in the URL)\n    * **[Request Object](#request-object)** (Understanding the request data)\n        * Available properties in the request object\n        * Accessing headers, path parameters, query parameters, body and verb\n    * **[Response Handling](#response-handling)** (Sending data back to the client)\n        * Returning dictionaries (converted to JSON)\n        * Returning strings\n        * Returning custom status codes and headers\n    * **[Middleware](#middleware)** (Adding custom logic before request handling)\n        * Creating middleware functions\n        * **[Before all](#before-all)** (Running middleware before every request)\n        * **[Middleware chaining](#middleware-chaining)**\n    * **[Running the Server](#running-the-server)** (Starting the server)\n    * **[Contributing](#contributing)** (How to contribute to the project)\n\n## Features\n\n- Built on raw TCP sockets\n- Routing with HTTP verb and path matching\n- Middleware support with easy chaining\n- JSON response handling\n- Zero external dependencies\n\n## Installation\n\nYou can install the package via pip:\n```\n$ pip install pymicrohttp\n```\n\n## Quick Start\n\nHere's a simple example to get you started:\n\n```python\nfrom pymicrohttp.server import Server\n\ns = Server()\n\n@s.register('GET /hello')\ndef hello(request):\n    return {\"message\": \"Hello, World!\"}\n\n@s.register('GET /hello/:name')\ndef hello_name(request):\n    name = request['params'].get('name')\n    return {\"message\": f\"Hello, {name}!\"}\n\n\nif __name__ == \"__main__\":\n    s.start_server(port=8080)\n```\n\nRun this script, and you'll have a server running on `http://localhost:8080`. Access it with:\n\n```\ncurl http://localhost:8080/hello\n```\n\n## Routing\n\nRoutes are defined using the `@s.register` decorator:\n\n```python\n@s.register('GET /ping')\ndef ping_handler(request):\n    return \"pong\"\n```\n\nFollowing this syntax:\n```\nVERB /\u003cPATH\u003e\n```\n### Supported verbs:\n- `*`: to match any verb\n- GET\n- POST\n- PUT\n- PATCH\n- DELETE\n- HEAD\n- OPTIONS\n\nWith a signle space separating between the verb and the request path.\n\nExample:\n\n```python\n@s.register('POST /login')\ndef login_handler(request):\n    try:\n        body = json.loads(request['body'])\n        if 'username' not in body or 'password' not in body:\n            # do somthing\n    except:\n        return { 'error': 'invalid data' }\n```\n\n### Path parameters\n\nYou can declare dynamic path params using a colon, for example:\n```\nGET /users/:group/:channel\n```\nTo read these params you can access them via the request object:\n```py\n@s.register('GET /users/:group/:channel')\ndef handler(request):\n    ...\n    group = request['params']['group']\n    channel = request['params']['channel']\n    ...\n```\n\n### Query parameters\nYou can read query parameters via the request obejct:\n```py\n@s.register('GET /products')\ndef handler(request):\n    ...\n    name = request['query'].get('name', '')\n    category = request['query'].get('category', 'shoes')\n    ...\n```\nNote that it is better to use `.get(key, default_value)` because query params are optional and may not exist, and accessing them without the `.get()` method may result in key errors.\n\n## Request Object\n\nThe request object is a dict containing these key and value:\n```\n{\n    'verb':    ...\n    'path':    ...\n    'body':    ...\n    'headers': ... # { 'key': 'value' }\n    'params':  ... # { 'key': 'value' }\n    'query':   ... # { 'key': 'value' }\n}\n```\n\nYou can access it via the handler:\n```py\n@s.register('* /ping')\ndef ping_handler(request):\n    # accessing request headers\n    if 'double' in request['headers']:\n        return \"pong-pong\"\n    return \"pong\"\n```\n\nExamples:\n\n1. Accessing headers:\n    ```py\n    # say hello\n    s.register('GET /hello/:name')\n    def hello(request):\n        name = request['params']['name']\n        return \"Hello \" + name\n    ```\n\n1. Accessing dynamic path params:\n    ```py\n    # say hello `n` times\n    s.register('GET /hello/:name/:n')\n    def hello(request):\n        name, n = request['params']['name'], request['params']['n']\n        return \"Hello \" * int(n) + name\n    ```\n\n1. Accessing query params:\n    ```py\n    # say hello `n` times\n    # read n from query params\n    # with default value of 3\n    s.register('GET /hello/:name')\n    def hello(request):\n        name = request['params']['name']\n        n = request['query'].get('n', 3)\n        return \"Hello \" * n + name\n    ```\n\n## Response Handling\n\nThe framework supports different types of responses:\n\n1. Dictionary (automatically converted to JSON):\n   ```python\n   return {\"key\": \"value\"}\n   ```\n\n2. String:\n   ```python\n   return \"Hello, World!\"\n   ```\n\n3. Tuple for custom status codes and headers:\n   ```python\n   return \"Not Found\", 404\n   # or\n   return \"Created\", 201, {\"Location\": \"/resource/1\"}\n   ```\n\n\n## Middleware\nMiddleware functions can be used to add functionality to your routes:\n\n```python\ndef log_middleware(next):\n    def handler(request):\n        print(f\"Request: {request['verb']} {request['path']}\")\n        return next(request)\n    return handler\n\n@s.register('GET /logged', log_middleware)\ndef logged_route(request):\n    return {\"message\": \"This is a logged route\"}\n```\n\n### Before all\n\nIf you want to run a middleware before every single request you can use the `s.beforeAll()` decorator:\n```py\n@s.beforeAll()\ndef logger(next):\n    def handler(request):\n        verb, path = request['verb'], request['path']\n        print(f'{datetime.datetime.now()} {verb} {path}')\n        return next(request)\n    return handler\n```\n\n### Middleware chaining\nYou can chain multiple middlwares together\n```py\ndef log_middleware(next):\n    def handler(request):\n        # do your logging logic here\n        return next(request)\n    return handler\n\ndef auth_middleware(next):\n    def handler(request):\n        # do your auth logic here\n        return next(request)\n    return handler\n\n@s.register('GET /protected', [log_middleware, auth_middleware])\ndef protected_route(request):\n    return {\"message\": \"This is a protected route\"}\n```\n\n## Running the Server\n\nTo run the server:\n\n```python\nif __name__ == \"__main__\":\n    s = Server()\n    # Register your routes here\n    s.start_server(port=8080)\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhasssanezzz%2FPyMicroHTTP","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhasssanezzz%2FPyMicroHTTP","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhasssanezzz%2FPyMicroHTTP/lists"}