### Clone Repository and Setup Development Environment Source: https://github.com/justrach/turboapi/blob/main/README.md Clone the TurboAPI repository, navigate into the directory, install the specified Python version, build the Zig backend, install the project in development mode, set up pre-commit hooks, and run tests. ```bash git clone https://github.com/justrach/turboAPI.git cd turboAPI uv python install 3.14t python3.14t zig/build_turbonet.py --install # build Zig backend pip install -e ".[dev]" # install in dev mode make hooks # install pre-commit hook make test # verify everything works ``` -------------------------------- ### Custom Benchmark Server Setup Source: https://github.com/justrach/turboapi/blob/main/docs/BENCHMARKS.md Example of setting up a minimal TurboAPI application for custom benchmarking, disabling rate limiting for accurate measurements. ```python from turboapi import TurboAPI import time app = TurboAPI() app.configure_rate_limiting(enabled=False) # Disable for benchmarking @app.get("/test") def test_endpoint(): return {"status": "ok"} # Start server and run wrk or your preferred tool ``` -------------------------------- ### Build and Install TurboAPI from Source Source: https://github.com/justrach/turboapi/blob/main/README.md Clone the repository, install Python dependencies, build the Zig native backend, and install the Python package. This is the primary method for setting up the development environment. ```bash git clone https://github.com/justrach/turboAPI.git cd turboAPI # 1. Clone git clone https://github.com/justrach/turboAPI.git cd turboAPI # 2. Install free-threaded Python (if you don't have it) uv python install 3.14t # 3. Build the Zig native backend (dhi dependency fetched automatically) python3.14t zig/build_turbonet.py --install # 4. Install the Python package pip install -e ".[dev]" # 5. Run tests python -m pytest tests/ -p no:anchorpy \ --deselect tests/test_fastapi_parity.py::TestWebSocket -v ``` -------------------------------- ### Clone and Run TurboAPI with Docker Source: https://github.com/justrach/turboapi/blob/main/README.md Use this command to quickly set up and run TurboAPI using Docker. It handles building the Python and Zig components and starts the example application. ```bash git clone https://github.com/justrach/turboAPI.git cd turboAPI docker compose up ``` -------------------------------- ### Basic Metric Setup with Noop Initialization Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/metrics-0.0.0-W7G4eP2_AQBKsaql3dhLJ-pkf-RdP-zV3vflJy4N34jC/readme.md Demonstrates how to define a Metrics struct, initialize it to a noop state for safety, and provide functions for updating and initializing real metrics. This setup is safe for library developers and configurable for application developers. ```zig const m = @import("metrics"); // defaults to noop metrics, making this safe to use // whether or not initializeMetrics is called var metrics = m.initializeNoop(Metrics); const Metrics = struct { // counter can be a unsigned integer or floats hits: m.Counter(u32), // gauge can be an integer or float connected: m.Gauge(u16), }; // meant to be called within the application pub fn hit() void { metrics.hits.incr(); } // meant to be called within the application pub fn connected(value: u16) void { metrics.connected.set(value); } // meant to be called once on application startup pub fn initializeMetrics(comptime opts: m.RegistryOpts) !void { metrics = .{ .hits = m.Counter(u32).init("hits", .{}, opts), .connected = m.Gauge(u16).init("connected", .{}, opts), }; } // thread safe pub fn writeMetrics(writer: *std.io.Writer) !void { return m.write(&metrics, writer); } ``` -------------------------------- ### Drop-in Replacement Example Source: https://github.com/justrach/turboapi/blob/main/faster-boto3/socials/tweet3.md This example demonstrates the ease of integrating faster-boto3. It shows the 'before' and 'after' import statements and how to initialize S3 and DynamoDB clients, highlighting that the rest of the code remains unchanged. ```python # Before import boto3 # After import faster_boto3 as boto3 # Everything else stays the same s3 = boto3.client('s3') ddb = boto3.client('dynamodb') ``` -------------------------------- ### Networking Server Setup Source: https://github.com/justrach/turboapi/blob/main/docs/ZIG_0_16_MIGRATION.md Shows how to set up a network server using the native `std.Io.net` API in Zig 0.16. ```zig const ip = try std.Io.net.IpAddress.parse(host, port); var server = try ip.listen(runtime.io, .{ .reuse_address = true }); while (true) { const stream = try server.accept(runtime.io); // hand off stream } ``` -------------------------------- ### Install Python and TurboAPI Locally Source: https://github.com/justrach/turboapi/blob/main/README.md Instructions for installing the required free-threaded Python version and the TurboAPI library locally. This is an alternative to using Docker. ```bash # Install free-threaded Python uv python install 3.14t # Install turboapi pip install turboapi # Or build from source (see below) ``` -------------------------------- ### Install and Use Free-Threaded Python Source: https://github.com/justrach/turboapi/blob/main/README.md Install a free-threaded Python version using 'uv python install' and run your application with it. ```bash # Install free-threaded Python uv python install 3.14t python3.14t app.py ``` -------------------------------- ### Basic TurboAPI Application Setup Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/quickstart.html Initialize your application with TurboAPI and define a root endpoint and an item creation endpoint. ```python app = TurboAPI() @app.get("/") async def root(): return {"message": "Hello, World!"} @app.post("/items") async def create_item(name: str, price: float): return {"name": name, "price": price} ``` -------------------------------- ### Conn.begin Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Starts a new transaction. This is a convenience method that calls `execOpts` with the "begin" command. ```APIDOC ## Conn.begin ### Description Starts a new transaction. This is a convenience method that calls `execOpts` with the "begin" command. ### Signature `begin() !void` ``` -------------------------------- ### OpenTelemetry Tracing Setup Source: https://github.com/justrach/turboapi/blob/main/README.md Configure OpenTelemetry tracing by setting up a TracerProvider and an OTLPSpanExporter. This snippet demonstrates how to start a span for a specific request and add attributes to it. ```python from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter provider = TracerProvider() provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) trace.set_tracer_provider(provider) tracer = trace.get_tracer(__name__) app = TurboAPI() @app.get("/users/{user_id}") def get_user(user_id: int): with tracer.start_as_current_span("get_user") as span: span.set_attribute("user.id", user_id) user = db.get(user_id) return user.dict() ``` -------------------------------- ### Install TurboAPI Source: https://github.com/justrach/turboapi/blob/main/docs/README.md Use pip to install the TurboAPI package. ```bash pip install turboapi ``` -------------------------------- ### Install and Run wrk for Load Testing Source: https://github.com/justrach/turboapi/blob/main/tests/README.md These bash commands show how to install the 'wrk' load testing tool and then use it to test both TurboAPI and FastAPI endpoints. Adjust thread, connection, and duration parameters as needed. ```bash # Install wrk brew install wrk # macOS sudo apt install wrk # Ubuntu # Test TurboAPI wrk -t4 -c50 -d30s http://127.0.0.1:8080/benchmark/simple # Test FastAPI wrk -t4 -c50 -d30s http://127.0.0.1:8081/benchmark/simple ``` -------------------------------- ### Copy installation command to clipboard Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/index.html JavaScript event listener to copy the 'pip install turboapi' command to the clipboard and provide user feedback. ```javascript document.querySelector('.install-line span').addEventListener('click', function() { navigator.clipboard.writeText('pip install turboapi').catch(() => {}); const orig = this.textContent; this.textContent = 'copied!'; setTimeout(() => this.textContent = orig, 1500); }); ``` -------------------------------- ### Install TurboPG Source: https://github.com/justrach/turboapi/blob/main/python/turbopg/README.md Install the TurboPG package using pip. Optionally, install with psycopg2 fallback support. ```bash pip install turbopg # With psycopg2 fallback: pip install turbopg[psycopg2] ``` -------------------------------- ### Install Benchmark Dependencies Source: https://github.com/justrach/turboapi/blob/main/docs/BENCHMARKS.md Install necessary Python packages for running benchmarks, including libraries for making requests and asynchronous operations, as well as for FastAPI comparison. ```bash pip install requests aiohttp matplotlib # For FastAPI comparison pip install fastapi uvicorn ``` -------------------------------- ### Define TurboAPI Application with Endpoints Source: https://github.com/justrach/turboapi/blob/main/README.md A Python example demonstrating how to create a TurboAPI application, define data models using Pydantic, and set up GET and POST endpoints. ```python from turboapi import TurboAPI from dhi import BaseModel app = TurboAPI() class Item(BaseModel): name: str price: float quantity: int = 1 @app.get("/") def hello(): return {"message": "Hello World"} @app.get("/items/{item_id}") def get_item(item_id: int): return {"item_id": item_id, "name": "Widget"} @app.post("/items") def create_item(item: Item): return {"item": item.model_dump(), "created": True} if __name__ == "__main__": app.run() ``` -------------------------------- ### EC2 Describe Instances Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Example of describing EC2 instances using TurboBoto. This operation benefits from the Zig acceleration for faster retrieval of instance information. ```python from turboboto import EC2 ec2 = EC2() # Describe instances response = ec2.describe_instances() for reservation in response["Reservations"]: for instance in reservation["Instances"]: print(f"- Instance ID: {instance['InstanceId']}, State: {instance['State']['Name']}") ``` -------------------------------- ### Launch Postgres Database with Docker Compose Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Use this command to start the Postgres database required for testing. Ensure you are in the `tests/` directory. ```bash cd tests/ docker compose up ``` -------------------------------- ### Run pgbench Benchmark Source: https://github.com/justrach/turboapi/blob/main/benchmarks/pgbench/README.md Navigate to the pgbench directory and start the benchmark suite using Docker Compose. This command builds the necessary Docker images and runs the benchmark. ```bash cd benchmarks/pgbench docker compose up --build ``` -------------------------------- ### Run FastAPI Comparison Server Source: https://github.com/justrach/turboapi/blob/main/tests/README.md Starts the FastAPI server on port 8081. Use the 'benchmark' argument to run FastAPI benchmarks. ```bash python3 tests/fastapi_equivalent.py python3 tests/fastapi_equivalent.py benchmark ``` -------------------------------- ### Basic S3 List Objects Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Demonstrates how to list objects in an S3 bucket using TurboBoto. Ensure you have the necessary AWS credentials configured. ```python from turboboto import S3 s3 = S3() # List objects in a bucket response = s3.list_objects_v2(Bucket="my-bucket") if "Contents" in response: for obj in response["Contents"]: print(f"- {obj['Key']}") else: print("No objects found.") ``` -------------------------------- ### Install TurboAPI Python Package Source: https://github.com/justrach/turboapi/blob/main/CLAUDE.md Installs the TurboAPI Python package in development mode using uv. Includes development dependencies. ```bash # Install the Python package in dev mode uv pip install -e ".[dev]" ``` -------------------------------- ### Verify TurboAPI Installation Source: https://github.com/justrach/turboapi/blob/main/tests/README.md Use this Python command to quickly verify if the TurboAPI library has been installed correctly. It prints 'OK' if the import is successful. ```python python -c "import turboapi; print('OK')" ``` -------------------------------- ### S3 Download File Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Illustrates downloading a file from an S3 bucket using TurboBoto. This is efficient for retrieving multiple files or large datasets. ```python from turboboto import S3 s3 = S3() # Download a file response = s3.get_object(Bucket="my-bucket", Key="remote_file.txt") with open("downloaded_file.txt", "wb") as f: f.write(response["Body"].read()) print("File downloaded successfully.") ``` -------------------------------- ### Benchmark Comparison Report Example Output Source: https://github.com/justrach/turboapi/blob/main/tests/README.md Presents a sample output from the benchmark comparison script, detailing sequential and concurrent response times, and maximum sustainable RPS for TurboAPI versus FastAPI. ```text 📊 BENCHMARK COMPARISON REPORT ============================== 🎯 Endpoint: /benchmark/simple -------------------------- Sequential Response Time: TurboAPI: 0.45ms FastAPI: 2.31ms TurboAPI is 5.1x faster Concurrent Response Time: TurboAPI: 0.52ms FastAPI: 8.73ms TurboAPI is 16.8x faster Maximum Sustainable RPS: TurboAPI: 45,000 RPS FastAPI: 3,200 RPS TurboAPI delivers 14.1x higher throughput 🏆 OVERALL PERFORMANCE SUMMARY ============================== Average Sequential Latency Improvement: 4.2x Average Concurrent Latency Improvement: 12.8x Average Throughput Improvement: 18.5x ``` -------------------------------- ### Run TurboAPI Server Source: https://github.com/justrach/turboapi/blob/main/tests/README.md Starts the TurboAPI server on port 8080. Use the 'benchmark' argument to enable integrated benchmarks. ```bash python3 tests/test.py python3 tests/test.py benchmark ``` -------------------------------- ### Run TurboAPI with Docker Source: https://github.com/justrach/turboapi/blob/main/CLAUDE.md Starts the TurboAPI service using Docker Compose, building the necessary images. ```bash # Or just use Docker docker compose up --build ``` -------------------------------- ### Build TurboAPI Native Backend Source: https://github.com/justrach/turboapi/blob/main/CLAUDE.md Builds the Zig native backend for TurboAPI. It auto-detects Python and fetches dependencies via build.zig.zon. Use --install to install the built backend. ```bash # Build the Zig native backend (auto-detects Python, dhi fetched via build.zig.zon) python zig/build_turbonet.py --install ``` -------------------------------- ### S3 Upload File Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Shows how to upload a file to an S3 bucket with TurboBoto. This is useful for batch uploads or large files where performance is critical. ```python from turboboto import S3 s3 = S3() # Upload a file with open("local_file.txt", "rb") as f: s3.put_object(Bucket="my-bucket", Key="remote_file.txt", Body=f.read()) print("File uploaded successfully.") ``` -------------------------------- ### Run TypeScript Benchmarks Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/dhi-0.1.0-Fz3bnz2GAwD-QDhvUhwzx5RJ5Yu1q_eYivGu0JYlOrcZ/README.md Navigate to the JavaScript bindings directory, install dependencies using bun, and run the benchmark script to compare DHI against Zod in TypeScript. ```bash # TypeScript — dhi vs Zod 4 cd js-bindings && bun install && bun run benchmark-vs-zod.ts ``` -------------------------------- ### Calling CounterVec Metric Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/metrics-0.0.0-W7G4eP2_AQBKsaql3dhLJ-pkf-RdP-zV3vflJy4N34jC/readme.md Example of how to call a CounterVec metric with specific labels. Ensure the metrics file is imported. ```zig // import your metrics file const metrics = @import("metrics.zig"); metrics.hit(.{.status = 200, .path = "/about.txt"}); ``` -------------------------------- ### SQS Receive Message Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Shows how to receive messages from an SQS queue using TurboBoto. Efficient message retrieval is crucial for many applications. ```python from turboboto import SQS sqs = SQS() # Receive messages from a queue response = sqs.receive_message(QueueUrl="YOUR_QUEUE_URL", MaxNumberOfMessages=10) if 'Messages' in response: for message in response['Messages']: print(f"Received message: {message['Body']}") # Remember to delete the message after processing sqs.delete_message(QueueUrl="YOUR_QUEUE_URL", ReceiptHandle=message['ReceiptHandle']) else: print("No messages in the queue.") ``` -------------------------------- ### DynamoDB Put Item Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Shows how to put (insert or update) an item into a DynamoDB table using TurboBoto. Performance gains are expected for high-throughput scenarios. ```python from turboboto import DynamoDB db = DynamoDB() # Define the item to put item = { "id": {"S": "user123"}, "name": {"S": "John Doe"}, "age": {"N": "30"} } # Put the item into the table response = db.put_item(TableName="my-table", Item=item) print(f"Item put successfully. Response metadata: {response['ResponseMetadata']}") ``` -------------------------------- ### SQS Send Message Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Demonstrates sending a message to an SQS queue using TurboBoto. Optimized for high throughput message queuing. ```python from turboboto import SQS sqs = SQS() # Send a message to a queue response = sqs.send_message(QueueUrl="YOUR_QUEUE_URL", MessageBody="Hello from TurboBoto!") print(f"Message sent. Message ID: {response['MessageId']}") ``` -------------------------------- ### Lambda Invoke Function Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Demonstrates invoking a Lambda function asynchronously using TurboBoto. The Zig acceleration can speed up the invocation process. ```python from turboboto import Lambda lambda_client = Lambda() # Invoke a Lambda function asynchronously response = lambda_client.invoke(FunctionName="my-lambda-function", InvocationType="Event") print(f"Lambda invocation initiated. Status code: {response['StatusCode']}") ``` -------------------------------- ### Zig Code Block Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turbopg.html This snippet demonstrates a basic Zig code block with syntax highlighting for keywords, strings, and comments. ```zig const std = @import("std"); const kw = "keyword"; const str = "string"; const cmt = "// comment"; pub fn main() { std.debug.print("{s} {s} {s}\n", .{ kw, str, cmt, }); } ``` -------------------------------- ### CloudWatch Get Metric Data Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Example of retrieving metric data from CloudWatch using TurboBoto. This can be used for performance monitoring and analysis. ```python from turboboto import CloudWatch import datetime cloudwatch = CloudWatch() # Define time range end_time = datetime.datetime.utcnow() start_time = end_time - datetime.timedelta(hours=1) # Get metric data response = cloudwatch.get_metric_data( MetricDataQueries=[ { 'Id': 'm1', 'MetricStat': { 'Metric': { 'Namespace': 'AWS/EC2', 'MetricName': 'CPUUtilization', 'Dimensions': [ { 'Name': 'InstanceId', 'Value': 'i-0123456789abcdef0' }, ] }, 'Period': 300, 'Stat': 'Average' }, 'ReturnData': True }, ], StartTime=start_time, EndTime=end_time ) for result in response['MetricDataResults']: print(f"Timestamps: {result['Timestamps']}") print(f"Values: {result['Values']}") ``` -------------------------------- ### DynamoDB Get Item Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Illustrates retrieving a single item from a DynamoDB table using TurboBoto. This is optimized for low-latency access. ```python from turboboto import DynamoDB db = DynamoDB() # Get an item by its key response = db.get_item( TableName="my-table", Key={"id": {"S": "user123"}} ) item = response.get('Item') if item: print(f"Retrieved item: {item}") else: print("Item not found.") ``` -------------------------------- ### Run Python Benchmarks Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/dhi-0.1.0-Fz3bnz2GAwD-QDhvUhwzx5RJ5Yu1q_eYivGu0JYlOrcZ/README.md Clone the DHI repository, navigate to the Python bindings directory, install dependencies, and run the benchmark script to compare DHI against other Python validation libraries. ```bash # Python — full comparison (dhi vs msgspec vs msgspec-ext vs satya vs Pydantic) git clone https://github.com/justrach/dhi.git && cd dhi cd python-bindings pip install -e . pip install msgspec msgspec-ext 'pydantic[email]' satya python benchmarks/benchmark_vs_all.py ``` -------------------------------- ### Define a GET endpoint with TurboAPI Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/index.html Use the @app.get decorator to define routes. This example shows a route that accepts an integer path parameter. ```python app = TurboAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} ``` -------------------------------- ### Initializing and Executing a Prepared Statement Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Demonstrates the process of initializing a statement, preparing it with SQL and parameters, binding values, and executing it. Use `errdefer` for safe deinitialization. ```zig var stmt = try Stmt.init(conn, opts); errdefer stmt.deinit(); try stmt.prepare(sql, null); inline for (parameters) |param| { try stmt.bind(param); } return stmt.execute(); ``` -------------------------------- ### Basic TurboAPI Routing Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/docs.html Demonstrates basic routing setup in TurboAPI, supporting standard FastAPI route decorators for GET, POST, PUT, and DELETE methods. ```python from turboapi import TurboAPI app = TurboAPI() @app.get("/") async def root(): return {"status": "ok"} @app.get("/items/{item_id}") async def get_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q} @app.post("/items") async def create_item(item: Item): return item @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} @app.delete("/items/{item_id}") async def delete_item(item_id: int): return {"deleted": item_id} ``` -------------------------------- ### Run Zig Benchmarks Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/dhi-0.1.0-Fz3bnz2GAwD-QDhvUhwzx5RJ5Yu1q_eYivGu0JYlOrcZ/README.md Build the Zig project with the bench target and optimize for ReleaseFast to run the native Zig benchmarks. ```bash # Zig zig build bench -Doptimize=ReleaseFast ``` -------------------------------- ### Initialize pg Pool with TLS Enabled Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Demonstrates initializing a connection pool with TLS enabled. Use `.verify_full = null` for basic TLS or specify a path to a custom root certificate. ```zig var pool = try pg.Pool.init(allocator, .{ .connect = .{ .port = 5432, .host = "ip_or_hostname", .tls = .{.verify_full = null}}, .auth = .{ .... }, .size = 5, }); ``` -------------------------------- ### Verify TurboAPI Installation Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/docs.html Verify the installation of TurboAPI by checking its version using a Python one-liner. ```python python -c "import turboapi; print(turboapi.__version__)" ``` -------------------------------- ### Basic Usage of TurboAPI Core Router and HTTP Utilities Source: https://github.com/justrach/turboapi/blob/main/turboapi-core/README.md Demonstrates initializing a router, adding routes with path parameters and wildcards, finding routes, and using HTTP utility functions for percent decoding, query string parsing, status text retrieval, and date formatting. ```zig const core = @import("turboapi-core"); // Router var router = core.Router.init(allocator); defer router.deinit(); try router.addRoute("GET", "/", "index"); try router.addRoute("GET", "/users/{id}", "get_user"); try router.addRoute("POST", "/users", "create_user"); try router.addRoute("GET", "/files/*path", "serve_file"); // Lookup if (router.findRoute("GET", "/users/42")) |*match| { defer match.deinit(); // match.handler_key == "get_user" // match.params.get("id") == "42" } // HTTP utilities var buf: [256]u8 = undefined; const decoded = core.http.percentDecode("hello+world%21", &buf); // decoded == "hello world!" const val = core.http.queryStringGet("q=zig&page=2", "page"); // val == "2" const status = core.http.statusText(404); // status == "Not Found" var date_buf: [40]u8 = undefined; const date = core.http.formatHttpDate(&date_buf); // date == "Fri, 28 Mar 2026 05:00:00 GMT" ``` -------------------------------- ### Install dhi for TypeScript Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/dhi-0.1.0-Fz3bnz2GAwD-QDhvUhwzx5RJ5Yu1q_eYivGu0JYlOrcZ/README.md Install the dhi library for TypeScript. It supports Node.js 18+, Bun, and Deno. ```bash npm install dhi # TypeScript (Node 18+ / Bun / Deno) ``` -------------------------------- ### Install dhi for Python Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/dhi-0.1.0-Fz3bnz2GAwD-QDhvUhwzx5RJ5Yu1q_eYivGu0JYlOrcZ/README.md Install the dhi library for Python. Wheels are available for macOS arm64 and Linux x86_64. ```bash pip install dhi # Python (wheels for macOS arm64 + Linux x86_64) ``` -------------------------------- ### Initialize pg Pool using URI with SSL Mode Require Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Shows how to initialize a connection pool by parsing a PostgreSQL connection URI that includes `sslmode=require`. ```zig const uri = try std.Uri.parse("postgresql://user:password@hostname/DBNAME?sslmode=require"); var pool = try pg.Pool.initUri(allocator, uri, 10, 5_000); ``` -------------------------------- ### DynamoDB Scan Table Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Example of scanning a DynamoDB table using TurboBoto. While scans can be resource-intensive, TurboBoto aims to improve their execution speed. ```python from turboboto import DynamoDB db = DynamoDB() # Scan the table response = db.scan(TableName="my-table") print("Scanning results:") for item in response['Items']: print(f"- {item}") ``` -------------------------------- ### Recommended Deployment Architecture Source: https://github.com/justrach/turboapi/blob/main/docs/HTTP2.md Illustrates the recommended flow for handling HTTP/2 and HTTP/3 connections by terminating them at a reverse proxy before forwarding HTTP/1.1 requests to TurboAPI. ```text Client -> HTTPS / HTTP/2 or HTTP/3 at Caddy, nginx, Cloudflare, or another edge proxy -> HTTP/1.1 to TurboAPI on 127.0.0.1:8000 ``` -------------------------------- ### Run Benchmark Source: https://github.com/justrach/turboapi/blob/main/turboapi-core/README.md Execute the original benchmark for the project. This requires building the benchmark executable first. ```bash zig build-exe bench.zig -OReleaseFast -lc && ./bench ``` -------------------------------- ### Run Full Benchmark Suite Source: https://github.com/justrach/turboapi/blob/main/docs/BENCHMARKS.md Execute the complete set of TurboAPI benchmarks after setting up the environment, including enabling free-threading. ```bash # Set up environment source venv/bin/activate export PYTHON_GIL=0 # Enable free-threading # Run all benchmarks python benches/python_benchmark.py python tests/benchmark_comparison.py python benches/async_comparison_bench.py ``` -------------------------------- ### Switch to faster-boto3 Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html To use faster-boto3, simply change your import statement. No other configuration or setup is required. ```python # Before import boto3 # After — that's it import faster_boto3 as boto3 # Everything works exactly the same s3 = boto3.client('s3') s3.put_object(Bucket='my-bucket', Key='file.txt', Body=data) ddb = boto3.client('dynamodb') # works too ``` -------------------------------- ### Running TurboAPI Application Source: https://github.com/justrach/turboapi/blob/main/docs/HTTP2.md Command to start the TurboAPI application, which listens on the private interface 127.0.0.1:8000. ```bash python app.py # listens on 127.0.0.1:8000 ``` -------------------------------- ### Initialize and Use Buffer Pool Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/N-V-__8AAEGLAAB4JS8S1rWwdvXUTwnt7gRNthhJanWx4AvP/readme.md Initializes a pool of buffers, acquires a buffer from the pool, and ensures it is released back to the pool. ```zig const Pool = @import("string_builder").Pool; // Creates pool of 100 Buffers, each configured with a static buffer // of 10000 bytes var pool = try Pool.init(allocator, 100, 10000); var buf = try pool.acquire(); defer pool.release(buf); ``` -------------------------------- ### Switch Server Implementation Source: https://github.com/justrach/turboapi/blob/main/README.md Transition from using uvicorn to TurboAPI's built-in run method for improved performance. ```python # FastAPI way (still works) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) # TurboAPI way (20x faster) if __name__ == "__main__": app.run(host="0.0.0.0", port=8000) ``` -------------------------------- ### Initialize and use a connection pool Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/pg-0.0.0-Wp_7gYTxBgDOvvLXaKfiXksk9WArPQJWgY833oQjfk1y/readme.md Initializes a connection pool and executes a query, iterating over the results. Ensure to deinitialize the pool and result when done. ```zig var pool = try pg.Pool.init(allocator, .{ .size = 5, .connect = .{ .port = 5432, .host = "127.0.0.1", }, .auth = .{ .username = "postgres", .database = "postgres", .password = "postgres", .timeout = 10_000, } }); defer pool.deinit(); var result = try pool.query("select id, name from users where power > $1", .{9000}); defer result.deinit(); while (try result.next()) |row| { const id = try row.get(i32, 0); // this is only valid until the next call to next(), deinit() or drain() const name = try row.get([]u8, 1); } ``` -------------------------------- ### Initialize and Use Zig Buffer Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/N-V-__8AAEGLAAB4JS8S1rWwdvXUTwnt7gRNthhJanWx4AvP/readme.md Initializes a buffer with a static capacity and demonstrates writing bytes and strings, truncating, and accessing the length and string representation. ```zig const Buffer = @import("buffer").Buffer; // Starts off with a static buffer of 100 bytes // If you go over this, memory will be dynamically allocated // It's like calling ensureTotalCapacity on an ArrrayList, but // those 100 bytes (aka the static portion of the buffer) are // re-used when pooling is used var buf = try Buffer.init(allocator, 100); try buf.writeByte('o'); try buf.write("ver 9000!1"); buf.truncate(1); buf.len(); // 10 buf.string(); // "over 9000!" ``` -------------------------------- ### Run Driver-only Benchmark Source: https://github.com/justrach/turboapi/blob/main/benchmarks/README.md Navigate to the pgbench directory and run the benchmark using Docker Compose. This measures raw query throughput and decode cost without an HTTP layer. ```bash cd benchmarks/pgbench docker compose up --build --abort-on-container-exit pgbench ``` -------------------------------- ### Add Middleware Source: https://github.com/justrach/turboapi/blob/main/CHANGELOG.md Integrate middleware for cross-cutting concerns like CORS. This example shows adding a Zig-native CORS middleware. ```python app.add_middleware(CORSMiddleware, ...) ``` -------------------------------- ### Sync Handler for CPU-bound Work Source: https://github.com/justrach/turboapi/blob/main/docs/ASYNC_HANDLERS.md Use standard `def` functions for CPU-bound tasks. This example demonstrates a simple computation. ```python import asyncio import aiohttp # Assuming 'app' is a TurboAPI application instance @app.get("/compute") def compute(): # Pure computation - sync is faster result = sum(i * i for i in range(1000)) return {"result": result} ``` -------------------------------- ### Bug Fix - PyJWT Lazy Loading Source: https://github.com/justrach/turboapi/blob/main/CHANGELOG.md Lazy load the PyJWT library to prevent import errors in environments where PyJWT is not installed. ```python PyJWT lazy-loaded so turboapi imports without it ``` -------------------------------- ### S3 Delete Object Example Source: https://github.com/justrach/turboapi/blob/main/frontend/dist/turboboto.html Demonstrates deleting a single object from an S3 bucket using TurboBoto. This operation is optimized for speed. ```python from turboboto import S3 s3 = S3() # Delete an object s3.delete_object(Bucket="my-bucket", Key="object_to_delete.txt") print("Object deleted successfully.") ``` -------------------------------- ### Migrating Build System Compile Steps Source: https://github.com/justrach/turboapi/blob/main/docs/migration-0.15.2-to-0.16.md Illustrates the changes in how include paths, system libraries, and C source files are added in the Zig build system between versions 0.15.2 and 0.16. The primary change involves moving these configurations to `root_module`. ```zig // 0.15 lib.addIncludePath(.{ .cwd_relative = path }); lib.linkSystemLibrary("foo"); lib.addCSourceFile(.{ .file = b.path("shim.c"), .flags = &.{}}); // 0.16 lib.root_module.addIncludePath(.{ .cwd_relative = path }); lib.root_module.linkSystemLibrary("foo", .{}); lib.root_module.addCSourceFile(.{ .file = b.path("shim.c"), .flags = &.{}}); ``` -------------------------------- ### Initialize Database Connection Source: https://github.com/justrach/turboapi/blob/main/python/turbopg/README.md Connect to a PostgreSQL database using a connection string and specify the connection pool size. ```python from turbopg import Database db = Database("postgres://user:pass@localhost/mydb", pool_size=16) ``` -------------------------------- ### Use Buffer Views for Message Length Prefixes Source: https://github.com/justrach/turboapi/blob/main/zig/zig-pkg/N-V-__8AAEGLAAB4JS8S1rWwdvXUTwnt7gRNthhJanWx4AvP/readme.md Demonstrates using buffer views to reserve space for a length prefix, write message content, and then fill the reserved space with the calculated length. ```zig var buf = try Buffer.init(allocator, 100); // skip 4 bytes, reserving a "view" to the start of the skipped location var view = buf.skip(4); try buf.write("hello world"); try buf.writeByte('!'); // fill in those first 4 bytes with the lenght (which we now know.) view.writeU32Little(@intCast(buf.len())); ``` -------------------------------- ### Run Continuous Fuzzing Source: https://github.com/justrach/turboapi/blob/main/turboapi-core/README.md Start continuous fuzzing to test the project indefinitely. This is useful for uncovering edge cases and potential bugs. ```bash zig build test --fuzz ```