Web Framework Integration

Integrate Tauq with your web applications for efficient data transfer and configuration.

Express.js (Node.js)

Tauq Middleware

// middleware/tauq.js
import { parse, stringify } from 'tauq';

// Parse Tauq request bodies
export function tauqParser(req, res, next) {
  if (req.headers['content-type'] === 'application/tauq') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        req.body = parse(body);
        next();
      } catch (err) {
        res.status(400).json({ error: 'Invalid Tauq' });
      }
    });
  } else {
    next();
  }
}

// Respond with Tauq
export function sendTauq(res, data) {
  res.setHeader('Content-Type', 'application/tauq');
  res.send(stringify(data));
}

Usage in Routes

import express from 'express';
import { tauqParser, sendTauq } from './middleware/tauq.js';

const app = express();
app.use(tauqParser);

// Accept Tauq or JSON
app.post('/api/users', (req, res) => {
  const users = req.body; // Parsed from Tauq or JSON
  // Process users...
  res.json({ created: users.length });
});

// Respond with Tauq for token efficiency
app.get('/api/users', async (req, res) => {
  const users = await db.getUsers();

  // Check Accept header
  if (req.accepts('application/tauq')) {
    sendTauq(res, users);
  } else {
    res.json(users);
  }
});

app.listen(3000);

FastAPI (Python)

Custom Request/Response

# app.py
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
import tauq

app = FastAPI()

class TauqResponse(Response):
    media_type = "application/tauq"

    def render(self, content) -> bytes:
        return tauq.dumps(content).encode()

@app.middleware("http")
async def tauq_middleware(request: Request, call_next):
    # Parse Tauq request bodies
    if request.headers.get("content-type") == "application/tauq":
        body = await request.body()
        request.state.parsed_body = tauq.loads(body.decode())

    response = await call_next(request)
    return response

@app.post("/api/data")
async def receive_data(request: Request):
    data = getattr(request.state, 'parsed_body', await request.json())
    return {"received": len(data)}

@app.get("/api/users", response_class=TauqResponse)
async def get_users():
    users = [
        {"id": 1, "name": "Alice", "email": "alice@example.com"},
        {"id": 2, "name": "Bob", "email": "bob@example.com"},
    ]
    return users

Content Negotiation

from fastapi import Header
from typing import Optional

@app.get("/api/users")
async def get_users(accept: Optional[str] = Header(default="application/json")):
    users = await fetch_users()

    if "application/tauq" in accept:
        return TauqResponse(content=users)
    return JSONResponse(content=users)

Actix Web (Rust)

Tauq Extractor

use actix_web::{web, App, HttpServer, HttpResponse, FromRequest};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct User {
    id: u64,
    name: String,
    email: String,
}

// Custom Tauq extractor
struct Tauq<T>(T);

impl<T: serde::de::DeserializeOwned> FromRequest for Tauq<T> {
    // ... implementation details
}

// Tauq responder
fn tauq_response<T: Serialize>(data: &T) -> HttpResponse {
    match tauq::to_string(data) {
        Ok(body) => HttpResponse::Ok()
            .content_type("application/tauq")
            .body(body),
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

#[actix_web::get("/users")]
async fn get_users() -> HttpResponse {
    let users = vec![
        User { id: 1, name: "Alice".into(), email: "alice@example.com".into() },
        User { id: 2, name: "Bob".into(), email: "bob@example.com".into() },
    ];
    tauq_response(&users)
}

#[actix_web::post("/users")]
async fn create_user(Tauq(user): Tauq<User>) -> HttpResponse {
    // user is parsed from Tauq body
    HttpResponse::Created().json(user)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_users)
            .service(create_user)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Configuration Loading

Load Config at Startup

// config.tqn
server {
  host 0.0.0.0
  port 8080
  workers 4
}

database {
  url "postgres://localhost/myapp"
  pool_size 10
}

features {
  rate_limiting true
  caching true
  metrics true
}

Node.js Config Loader

// config.js
import { load } from 'tauq';

const env = process.env.NODE_ENV || 'development';
const config = await load(`config/${env}.tqn`);

export default config;

// server.js
import config from './config.js';
import express from 'express';

const app = express();

app.listen(config.server.port, config.server.host, () => {
  console.log(`Server running on ${config.server.host}:${config.server.port}`);
});

Best Practices

Use Content Negotiation

Support both JSON and Tauq via Accept/Content-Type headers. Let clients choose.

Default to JSON for APIs

Keep JSON as default for compatibility. Offer Tauq as an opt-in for token-sensitive clients.

Use Tauq for AI Endpoints

Endpoints that feed data to LLMs benefit most from Tauq's token efficiency.

Cache Converted Data

If converting at runtime, cache the Tauq output to avoid repeated serialization.

View Language Bindings

Full documentation for each language's Tauq library.