### Nim SSR Server Setup Source: https://github.com/hapticx/happyx/wiki/Home This snippet demonstrates how to set up a basic Server-Side Rendering (SSR) server using the HappyX framework in Nim. It defines a route '/' that returns a simple 'Hello, world!' message. Ensure the HappyX framework is installed and configured. ```nim serve "127.0.0.1", 5000: "/": "Hello, world!" ``` -------------------------------- ### Nim: SPA Minimal Example with HappyX Source: https://github.com/hapticx/happyx/blob/master/README.md This snippet demonstrates the minimal setup for a Single Page Application (SPA) using the HappyX framework in Nim. It defines a basic route for the root path '/'. This example assumes the 'app' module is configured for SPA routing. ```nim import happyx appRoutes "app": "/": "Hello, world!" ``` -------------------------------- ### Install HappyX Python Package Source: https://github.com/hapticx/happyx/blob/master/bindings/python/README.md Installs the HappyX Python library using pip. This command fetches and installs the latest stable version from the Python Package Index (PyPI). ```bash pip install happyx ``` -------------------------------- ### Basic GET Endpoint Example Source: https://context7.com/hapticx/happyx/llms.txt A simple GET endpoint that returns JSON data. ```APIDOC ## GET /api/data ### Description This endpoint returns a predefined JSON response containing a list of integers. ### Method GET ### Endpoint /api/data ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (array) - A list of integers. #### Response Example ```json { "data": [ 1, 2, 3, 4, 5 ] } ``` ``` -------------------------------- ### Nim - Basic SSR Server with GET Route Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates how to create a basic HTTP server using HappyX in Nim, handling GET requests with plain text responses and path parameters. ```APIDOC ## GET / ### Description Handles a GET request to the root path and returns a simple "Hello, world!" message. ### Method GET ### Endpoint / ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **string**: "Hello, world!" #### Response Example "Hello, world!" ## GET /user/{id:int} ### Description Handles GET requests to user-specific paths, accepting an integer user ID as a path parameter and returning user information. ### Method GET ### Endpoint /user/{id:int} ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the user. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **object**: { "user_id": "integer", "message": "string" } #### Response Example { "user_id": 123, "message": "User found" } ## GET /search ### Description Handles GET requests to the search path, accepting a query parameter 'q' and returning search results. ### Method GET ### Endpoint /search ### Parameters #### Path Parameters None #### Query Parameters - **q** (string) - Optional - The search query. ### Request Example None ### Response #### Success Response (200) - **string**: "Search results" #### Response Example "Search results" ``` -------------------------------- ### Basic SSR Server with GET Route (Nim) Source: https://context7.com/hapticx/happyx/llms.txt This snippet demonstrates how to create a basic HTTP server using Nim with the HappyX framework. It handles GET requests, including routes with path parameters and query parameters. ```nim import happyx serve "127.0.0.1", 5000: get "/": "Hello, world!" get "/user/{id:int}": # Access path parameter return {"user_id": id, "message": "User found"} get "/search": # Access query parameters echo query("q", "") return "Search results" ``` -------------------------------- ### Nim Sub-Application Mounting Example Source: https://context7.com/hapticx/happyx/llms.txt Illustrates mounting modular sub-applications at different URL paths in Nim. This is useful for organizing larger applications into manageable parts, each with its own routing context. Sub-applications can be mounted under prefixes like '/settings' or '/api'. ```nim import happyx # Create main application serve "127.0.0.1", 5000: get "/": "Main application" # Create settings sub-application mount "/settings": get "/": "Settings home" get "/profile": "User profile settings" post "/update": echo requestBody return {"status": "updated"} # Create API sub-application mount "/api": get "/users": return %*[ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ] get "/users/{id:int}": return {"id": id, "name": "User " & $id} ``` -------------------------------- ### Python Server with HTTP Methods (Python) Source: https://context7.com/hapticx/happyx/llms.txt This example shows how to build a REST API using Python bindings for the HappyX framework. It covers defining endpoints for various HTTP methods (GET, POST) and returning different response types like JSON, HTML, and files. ```python from happyx import Server, JsonResponse, HtmlResponse, FileResponse app = Server('127.0.0.1', 5000) @app.get('/') def home(): return "Hello world!" @app.get('/json') def json_resp(): return JsonResponse( {'key': 'value', 'arr': [1, 2, 3, 4, 5]}, status_code=200, headers={'X-Custom-Header': 'value'} ) @app.post('/create') def create_item(): return JsonResponse({'status': 'created', 'id': 123}, status_code=201) @app.get('/html') def html_resp(): return HtmlResponse( '

HTML Response!

', status_code=200 ) @app.get('/file') def file_resp(): return FileResponse('my_cool_icon.png') app.start() ``` -------------------------------- ### Nim Static File Serving Example Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates serving static files and assets from filesystem directories in Nim. The `staticDir` directive allows mapping URL prefixes to local directories, enabling the application to serve HTML, CSS, JavaScript, and images directly. ```nim import happyx serve "127.0.0.1", 5000: # Serve all files from public directory staticDir "/static": "public" # Serve files with specific extensions only staticDir "/assets": "assets" # Optional: filter by extensions get "/": """ """ ``` -------------------------------- ### Nim: SSR Minimal Example with HappyX Source: https://github.com/hapticx/happyx/blob/master/README.md This snippet shows the basic configuration for Server-Side Rendering (SSR) with the HappyX framework in Nim. It sets up a server to listen on '127.0.0.1:5000' and defines a route for the root path '/' that returns 'Hello, world!'. ```nim import happyx serve "127.0.0.1", 5000: "/": "Hello, world!" ``` -------------------------------- ### HTTP Methods: GET - FastAPI and HappyX Source: https://github.com/hapticx/happyx/wiki/HappyX-for-FastAPI-Programmers Demonstrates how to define a root GET endpoint using FastAPI and HappyX. Both frameworks allow simple definition of HTTP methods for routing requests. FastAPI uses decorators, while HappyX uses a DSL-like syntax. ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return "Hello, world!" ``` ```nim import happyx serve "127.0.0.1", 5000: get "/": return "Hello, world!" ``` -------------------------------- ### Python - Server with HTTP Methods Source: https://context7.com/hapticx/happyx/llms.txt Illustrates creating REST API endpoints with various HTTP methods (GET, POST) using HappyX Python bindings, including JSON, HTML, and file responses. ```APIDOC ## GET / ### Description Handles GET requests to the root path and returns a "Hello world!" string. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **string**: "Hello world!" #### Response Example "Hello world!" ## GET /json ### Description Handles GET requests to the `/json` endpoint, returning a JSON response with a specific structure and custom headers. ### Method GET ### Endpoint /json ### Parameters None ### Request Example None ### Response #### Success Response (200) - **object**: { "key": "string", "arr": "array of integers" } - **headers**: { "X-Custom-Header": "string" } #### Response Example { "key": "value", "arr": [1, 2, 3, 4, 5] } ## POST /create ### Description Handles POST requests to the `/create` endpoint, returning a JSON response indicating successful creation with a status code of 201. ### Method POST ### Endpoint /create ### Parameters None ### Request Example None ### Response #### Success Response (201) - **object**: { "status": "string", "id": "integer" } #### Response Example { "status": "created", "id": 123 } ## GET /html ### Description Handles GET requests to the `/html` endpoint, returning an HTML response. ### Method GET ### Endpoint /html ### Parameters None ### Request Example None ### Response #### Success Response (200) - **string**: "

HTML Response!

" #### Response Example "

HTML Response!

" ## GET /file ### Description Handles GET requests to the `/file` endpoint, returning the content of a specified file. ### Method GET ### Endpoint /file ### Parameters None ### Request Example None ### Response #### Success Response (200) - **file**: "my_cool_icon.png" #### Response Example (Content of my_cool_icon.png) ``` -------------------------------- ### WebSocket Communication (Java) Source: https://context7.com/hapticx/happyx/llms.txt Implement WebSocket handlers in Java with connection state management. This example demonstrates how to interact with WebSocket connections and send responses. ```java import com.hapticx.*; import com.hapticx.data.*; public class WebSocketApp { public static void main(String[] args) { Server s = new Server(); s.websocket("/ws", ws -> { if (ws.getState() == WSConnection.State.OPEN) { System.out.println("Data: " + ws.getData()); if (ws.getData().equals("close")) { ws.send("Goodbye!"); ws.close(); } else { ws.send("Hello from Java!"); } } else if (ws.getState() == WSConnection.State.CONNECT) { System.out.println("Client connected"); } }); s.start(); } } ``` -------------------------------- ### WebSocket Communication (Node.js/TypeScript) Source: https://context7.com/hapticx/happyx/llms.txt Handle WebSocket connections and manage state in Node.js/TypeScript applications. This example shows how to respond to different WebSocket states and send messages. ```typescript import { Server, WebSocketClient, WSState } from "happyx"; const app = new Server("127.0.0.1", 5000); app.ws("/ws", (ws: WebSocketClient) => { if (ws.state === WSState.OPEN) { console.log(`Received: ${ws.data}`); if (ws.data === "close") { ws.sendText("Goodbye!"); ws.close(); } else { ws.sendText("Hello from server!"); } } else if (ws.state === WSState.CONNECT) { console.log("New client connected"); } else if (ws.state === WSState.CLOSE) { console.log("Client disconnected"); } }); app.ws("/chat", (ws: WebSocketClient) => { if (ws.state === WSState.OPEN) { let message = JSON.parse(ws.data); ws.sendJson({ echo: message, timestamp: Date.now() }); } }); app.start(); ``` -------------------------------- ### Nim SPA Routing Setup Source: https://github.com/hapticx/happyx/wiki/Home This snippet illustrates how to configure routing for a Single-Page Application (SPA) using the HappyX framework in Nim. It defines an application route named 'app' with a base route '/' that returns 'Hello, world!'. This is typically used for client-side routing. ```nim appRoutes "app": "/": "Hello, world!" ``` -------------------------------- ### WebSocket Communication (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Implement real-time bidirectional communication using WebSockets in Nim. This example demonstrates handling client connections, disconnections, receiving messages, broadcasting, and error handling for JSON parsing. ```nim import happyx type Msg = object text: string fromId: int serve "127.0.0.1", 5123: wsConnect: echo "Client connected" wsDisconnect: echo "Client disconnected" ws "/listen": try: echo wsData let message = wsData.parseJson().to(Msg) # Broadcast to all connected clients for connection in wsConnections: if connection.readyState == Open: await connection.send $(%*{ "response": { "text": message.text, "fromId": message.fromId } }) except JsonParsingError: await wsClient.send $(%*{ "response": "failure" }) ws "/echo": echo "Received: ", wsData await wsClient.send("Echo: " & wsData) ``` -------------------------------- ### Basic HappyX SPA Routing Source: https://github.com/hapticx/happyx/wiki/SPA This snippet demonstrates the fundamental routing setup for a HappyX Single Page Application. It defines a route for the root path ('/') that renders a 'Hello, world!' message. The `appRoutes` function takes the ID of the root element in the HTML as its argument. ```nim import happyx appRoutes("app"): # "app" is id of application root element in HTML "/": "Hello, world!" ``` -------------------------------- ### Java Server with Response Types (Java) Source: https://context7.com/hapticx/happyx/llms.txt This Java code demonstrates building HTTP servers with HappyX, focusing on strongly-typed request and response handling. It shows how to define GET endpoints and return various response types including custom responses, HTML, and files. ```java import com.hapticx.*; import com.hapticx.data.*; import com.hapticx.response.*; public class Application { public static void main(String[] args) { Server s = new Server(); s.get("/", req -> { System.out.println(req.getPath()); return "Hello from Java!"; }); s.get("/user{userId:int}", req -> { System.out.println(req.getPath()); System.out.println(req.getParams().get("userId").getInt() + 10); for (Query q : req.getQueries()) { System.out.println(q); } for (HttpHeader h : req.getHeaders()) { System.out.println(h); } return "User data"; }); s.get("/base", req -> { HttpHeaders headers = new HttpHeaders(); headers.add(new HttpHeader("X-Custom-Header", "Value")); return new BaseResponse( "Custom response", 401, headers ); }); s.get("/html", req -> { HttpHeaders headers = new HttpHeaders(); headers.add(new HttpHeader("Content-Type", "text/html")); return new HtmlResponse( "

Page Not Found

", 404, headers ); }); s.get("/file", req -> { return new FileResponse("/path/to/file.png"); }); s.start(); } } ``` -------------------------------- ### Python Middleware Example Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates chaining middleware functions in Python for handling cross-cutting concerns like authentication and logging. Middleware intercepts requests before they reach the route handler. It can modify the request, perform checks, or return a response directly. ```python from happyx import Server, JsonResponse app = Server('127.0.0.1', 5000) def auth_middleware(req): if 'Authorization' not in req.headers: return JsonResponse({'error': 'Unauthorized'}, status_code=401) # Continue processing return None def logging_middleware(req): print(f"[{req.method}] {req.path}") return None @app.middleware def global_middleware(req): if len(req.body) > 10000: return JsonResponse({'error': 'Request too large'}, status_code=413) return None @app.get('/protected') def protected_route(req): result = auth_middleware(req) if result: return result return JsonResponse({'data': 'Protected content'}) @app.notfound def not_found(req): return JsonResponse({'error': 'Not found', 'path': req.path}, status_code=404) app.start() ``` -------------------------------- ### Python CORS Configuration Example Source: https://context7.com/hapticx/happyx/llms.txt Configures CORS policies for cross-domain requests in Python. This allows specifying which origins, HTTP methods, and headers are permitted, as well as whether credentials should be included in requests, enhancing security and flexibility for APIs. ```python from happyx import Server, reg_cors, JsonResponse # Configure CORS globally reg_cors( allow_origins=['https://example.com', 'https://app.example.com'], allow_methods=['GET', 'POST', 'PUT', 'DELETE'], allow_headers=['Content-Type', 'Authorization'], credentials=True ) ``` -------------------------------- ### Node.js/TypeScript Server with Path Parameters (TypeScript) Source: https://context7.com/hapticx/happyx/llms.txt This snippet illustrates building Express-like HTTP servers using TypeScript with HappyX. It demonstrates handling GET and POST requests, accessing path parameters, query parameters, headers, and request bodies with type safety. ```typescript import { Server, Request } from "happyx"; const app = new Server("127.0.0.1", 5000); app.get("/", (req: Request) => { return "Hello, world!"; }); app.get("/user/{userId:int}", (req: Request) => { console.log(req.path); console.log(req.params.userId + 10); // Access queries console.log("Queries:"); for (let key in req.queries) { console.log(`${key}: ${req.queries[key]}`); } // Access headers console.log("HTTP Headers:"); for (let key in req.headers) { console.log(`${key}: ${req.headers[key]}`); } return "Hello, world!"; }); app.post("/data", (req: Request) => { console.log(req.body); req.answerJson({status: "received", data: JSON.parse(req.body)}); return null; }); app.start(); ``` -------------------------------- ### Nim CORS Configuration Example Source: https://context7.com/hapticx/happyx/llms.txt Enables Cross-Origin Resource Sharing (CORS) for API endpoints in Nim. This configuration allows web applications from different domains to access your API resources by setting specific origins, headers, methods, and credential options. ```nim import happyx regCORS: origins: "*" headers: "*" methods: "*" credentials: true serve "127.0.0.1", 5000: get "/api/data": return %*{ "data": [1, 2, 3, 4, 5] } post "/api/submit": return {"status": "ok"} ``` -------------------------------- ### HappyX Basic Hello World Server Source: https://github.com/hapticx/happyx/blob/master/bindings/python/README.md A minimal HappyX application demonstrating a basic 'Hello World!' response. It initializes a server and defines a route for the root URL ('/'). The server listens on localhost:5000 by default. ```python from happyx import Server app = Server('127.0.0.1', 5000) # host and port are optional params @app.get('/') def home(): return "Hello world!" app.start() ``` -------------------------------- ### Root Endpoint Source: https://github.com/hapticx/happyx/wiki/HappyX-for-FastAPI-Programmers Documentation for the root endpoint ('/') which returns a 'Hello, world!' message. ```APIDOC ## GET / ### Description Returns a 'Hello, world!' message. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **message** (string) - A greeting message. #### Response Example ```json { "message": "Hello, world!" } ``` ``` -------------------------------- ### Node.js/TypeScript - Server with Path Parameters Source: https://context7.com/hapticx/happyx/llms.txt Shows how to build Express-like HTTP servers in Node.js/TypeScript using HappyX, demonstrating path parameters, query parameters, and request body handling. ```APIDOC ## GET / ### Description Handles GET requests to the root path and returns a "Hello, world!" string. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **string**: "Hello, world!" #### Response Example "Hello, world!" ## GET /user/{userId:int} ### Description Handles GET requests to user paths with an integer `userId` path parameter. It logs path, parameters, queries, and headers, then returns a "Hello, world!" string. ### Method GET ### Endpoint /user/{userId:int} ### Parameters #### Path Parameters - **userId** (int) - Required - The ID of the user. #### Query Parameters - **any** (string) - Optional - Any query parameters can be passed. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string**: "Hello, world!" #### Response Example "Hello, world!" ## POST /data ### Description Handles POST requests to the `/data` endpoint, logs the request body, and responds with a JSON object confirming receipt of the data. ### Method POST ### Endpoint /data ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **any** (object) - Required - The data to be sent in the request body. ### Request Example ```json { "key": "value" } ``` ### Response #### Success Response (200) - **object**: { "status": "string", "data": "object" } #### Response Example { "status": "received", "data": { "key": "value" } } ``` -------------------------------- ### Java and Node.js Sub-Application Mounting Source: https://context7.com/hapticx/happyx/llms.txt Shows how to mount modular sub-applications with independent routing contexts in Java and Node.js. This approach helps in structuring large applications by breaking them down into smaller, distinct parts, each managed by its own Server instance. ```java import com.hapticx.*; public class MountedApp { public static void main(String[] args) { Server main = new Server(); Server api = new Server(); Server admin = new Server(); main.get("/", req -> "Main app"); api.get("/", req -> "API home"); api.get("/users", req -> "[{\"id\": 1}, {\"id\": 2}]"); admin.get("/", req -> "Admin panel"); admin.get("/settings", req -> "Settings"); main.mount("/api", api); main.mount("/admin", admin); main.start(); } } ``` ```typescript import { Server, Request } from "happyx"; const main = new Server("127.0.0.1", 5000); const api = new Server(); const admin = new Server(); main.get("/", (req: Request) => "Main app"); api.get("/", (req: Request) => "API home"); api.get("/users", (req: Request) => { return [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}]; }); admin.get("/", (req: Request) => "Admin panel"); admin.get("/settings", (req: Request) => "Admin settings"); main.mount("/api", api); main.mount("/admin", admin); main.start(); ``` -------------------------------- ### Create User Endpoint Source: https://github.com/hapticx/happyx/wiki/HappyX-for-FastAPI-Programmers Documentation for creating a new user with username and age, using request models. ```APIDOC ## POST /user ### Description Creates a new user with the provided username and age. ### Method POST ### Endpoint /user ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **age** (integer) - Required - The age of the new user. ### Request Example ```json { "username": "john_doe", "age": 30 } ``` ### Response #### Success Response (200) - **response** (object) - Contains user details. - **id** (integer) - The ID of the newly created user. - **username** (string) - The username of the new user. #### Response Example ```json { "response": { "id": 0, "username": "john_doe" } } ``` ``` -------------------------------- ### Java - Server with Response Types Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates building HTTP servers in Java using HappyX, showcasing various response types like plain text, JSON, HTML, and file responses, along with parameter and header access. ```APIDOC ## GET / ### Description Handles GET requests to the root path, logs the request path, and returns a plain text "Hello from Java!" message. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **string**: "Hello from Java!" #### Response Example "Hello from Java!" ## GET /user/{userId:int} ### Description Handles GET requests to user paths with an integer `userId` path parameter. It logs the path, accesses and logs query parameters and headers, and returns a "User data" string. ### Method GET ### Endpoint /user/{userId:int} ### Parameters #### Path Parameters - **userId** (int) - Required - The ID of the user. #### Query Parameters - **any** (object) - Optional - Query parameters are available as a list of Query objects. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string**: "User data" #### Response Example "User data" ## GET /base ### Description Handles GET requests to the `/base` endpoint, returning a custom response with a specified status code (401) and custom headers. ### Method GET ### Endpoint /base ### Parameters None ### Request Example None ### Response #### Success Response (401) - **object**: { "message": "string", "statusCode": "integer", "headers": "object" } #### Response Example { "message": "Custom response", "statusCode": 401, "headers": { "X-Custom-Header": "Value" } } ## GET /html ### Description Handles GET requests to the `/html` endpoint, returning an HTML response with a 404 status code and a Content-Type header set to text/html. ### Method GET ### Endpoint /html ### Parameters None ### Request Example None ### Response #### Success Response (404) - **string**: "

Page Not Found

" - **headers**: { "Content-Type": "text/html" } #### Response Example "

Page Not Found

" ## GET /file ### Description Handles GET requests to the `/file` endpoint, returning the content of a specified file. ### Method GET ### Endpoint /file ### Parameters None ### Request Example None ### Response #### Success Response (200) - **file**: "/path/to/file.png" #### Response Example (Content of /path/to/file.png) ``` -------------------------------- ### Python and Node.js Static File Serving Source: https://context7.com/hapticx/happyx/llms.txt Configures static file serving by mapping URL paths to directories in Python and Node.js. The `static()` method allows specifying a URL prefix and the corresponding local directory, with optional filtering by file extensions. ```python from happyx import Server app = Server('127.0.0.1', 5000) # Serve files from ./public at /static URL app.static('/static', './public') # Serve assets with specific extensions app.static('/assets', './assets', extensions=['.css', '.js', '.png', '.jpg']) @app.get('/') def home(): return '' app.start() ``` ```typescript import { Server, Request } from "happyx"; const app = new Server("127.0.0.1", 5000); app.static("/static", "./public"); app.static("/assets", "./assets"); app.get("/", (req: Request) => { return ''; }); app.start(); ``` -------------------------------- ### HappyX Response Types (JSON, HTML, File) Source: https://github.com/hapticx/happyx/blob/master/bindings/python/README.md Demonstrates how to use HappyX to return different response types: JSON, HTML, and files. This includes creating `JsonResponse`, `HtmlResponse`, and `FileResponse` objects. The server is initialized without specific host/port, using defaults. ```python from happyx import Server, JsonResponse, HtmlResponse, FileResponse app = Server() @app.get('/json') def json_resp(): return JsonResponse( {'key': 'value', 'arr': [1, 2, 3, 4, 5]}, status_code=200 # also available headers: dict param ) @app.get('/html') def html_resp(): return HtmlResponse( '

HTML Response!

', status_code=200 # also available headers: dict param ) @app.get('/file') def file_resp(): return FileResponse('my_cool_icon.png') app.start() ``` -------------------------------- ### WebSocket Communication (Java) Source: https://context7.com/hapticx/happyx/llms.txt Explains how to implement WebSocket handlers in Java, including managing connection states. ```APIDOC ## WebSocket Endpoint /ws ### Description This endpoint handles WebSocket connections in Java. It logs connection events and allows clients to send messages. It can also close the connection based on client input. ### Method WebSocket ### Endpoint /ws ### Parameters #### Connection States - **WSConnection.State.OPEN**: The WebSocket connection is established and active. - **WSConnection.State.CONNECT**: A client is attempting to establish a connection. #### Message Handling - **ws.getData()**: Retrieves the data sent by the client. - **ws.send(message)**: Sends a text message to the client. - **ws.close()**: Closes the WebSocket connection. ### Request Example (Client sends text) ``` Java WebSocket Test ``` ### Response - **Server Message** (string) - A greeting message from the server or a "Goodbye!" if the client sends "close". ### Response Example (Standard) ``` Hello from Java! ``` ### Response Example (On receiving "close") ``` Goodbye! ``` ``` -------------------------------- ### WebSocket Communication (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Details on implementing real-time bidirectional communication using WebSockets in Nim. ```APIDOC ## WebSocket Endpoint /listen ### Description This WebSocket endpoint allows clients to send messages, which are then broadcast to all connected clients. It also handles JSON parsing and potential errors. ### Method WebSocket ### Endpoint /listen ### Parameters #### Connection Event - **wsConnect**: Triggered when a client connects. - **wsDisconnect**: Triggered when a client disconnects. #### Message Handling - **wsData**: The incoming message data from the client. Expected to be a JSON string that can be parsed into a `Msg` object. ### Request Example (Client sends JSON) ```json { "text": "Hello everyone!", "fromId": 789 } ``` ### Response #### Success Response (Broadcasted) - **response** (object) - **text** (string) - The received message text. - **fromId** (integer) - The ID of the sender. #### Error Response - **response** (string) - "failure" if JSON parsing fails. #### Response Example (Broadcasted) ```json { "response": { "text": "Hello everyone!", "fromId": 789 } } ``` #### Response Example (Error) ```json { "response": "failure" } ``` ## WebSocket Endpoint /echo ### Description This WebSocket endpoint echoes back any message received from the client. ### Method WebSocket ### Endpoint /echo ### Parameters #### Message Handling - **wsData**: The incoming message string from the client. ### Request Example (Client sends text) ``` Some data to echo ``` ### Response - **Echoed Message** (string) - The received message prefixed with "Echo: ". ### Response Example ``` Echo: Some data to echo ``` ``` -------------------------------- ### WebSocket Communication (Node.js/TypeScript) Source: https://context7.com/hapticx/happyx/llms.txt Guidance on handling WebSocket connections with state management in Node.js/TypeScript. ```APIDOC ## WebSocket Endpoint /ws ### Description Handles general WebSocket connections, logging connection events and allowing clients to send text messages. Supports closing the connection. ### Method WebSocket ### Endpoint /ws ### Parameters #### Connection States - **WSState.OPEN**: The WebSocket connection is open and ready for communication. - **WSState.CONNECT**: A new client is attempting to connect. - **WSState.CLOSE**: The WebSocket connection has been closed. #### Message Handling - **ws.data**: The incoming message data from the client. - **ws.sendText(message)**: Sends a text message to the client. - **ws.close()**: Closes the WebSocket connection. ### Request Example (Client sends text) ``` Hello WebSocket! ``` ### Response - **Server Message** (string) - A greeting message from the server or a "Goodbye!" if the client sent "close". ### Response Example (Standard) ``` Hello from server! ``` ### Response Example (On receiving "close") ``` Goodbye! ``` ## WebSocket Endpoint /chat ### Description This WebSocket endpoint is specifically for chat functionality, expecting JSON messages and echoing them back with a timestamp. ### Method WebSocket ### Endpoint /chat ### Parameters #### Message Handling - **ws.data**: The incoming message data from the client, expected to be a JSON string. - **ws.sendJson(data)**: Sends a JSON object to the client. ### Request Example (Client sends JSON) ```json { "message": "How are you?" } ``` ### Response #### Success Response - **echo** (object) - The echoed JSON message received from the client. - **timestamp** (integer) - The server's current timestamp when the message was processed. #### Response Example ```json { "echo": { "message": "How are you?" }, "timestamp": 1678886400000 } ``` ``` -------------------------------- ### Path Parameters: User ID - FastAPI and HappyX Source: https://github.com/hapticx/happyx/wiki/HappyX-for-FastAPI-Programmers Illustrates how to capture path parameters, specifically a user ID, in FastAPI and HappyX. FastAPI uses type hints with path parameters, while HappyX uses a similar syntax with explicit type specification. ```python @app.get("/user/{id}") def get_user_by_id(id: int): return {"response": id} ``` ```nim get "/user/{id:int}": return {"response": id} ``` -------------------------------- ### Middleware and Route Filtering (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Details how to add middleware for request preprocessing, authentication, and global error handling in Nim. ```APIDOC ## Middleware for Request Body Size Check ### Description This middleware intercepts incoming requests and checks if the request body size exceeds 4096 bytes. If it does, it returns a 400 Bad Request error. ### Method All (Applied globally before route handlers) ### Endpoint N/A (Applies to all routes) ### Parameters #### Request Context - **req.body**: The raw body of the incoming request. ### Logic - If `req.body.len > 4096`, set `statusCode` to 400 and return an error response. ### Response Example (Error) ```json { "response": "error", "error_code": 3, "error": "request length too long (> 4096)" } ``` ## Middleware for Custom Header and Logging ### Description This middleware adds a custom `X-Powered-By` header to all responses and logs the path of each incoming request. ### Method All (Applied globally before route handlers) ### Endpoint N/A (Applies to all routes) ### Parameters #### Request Context - **req.headers**: The headers of the incoming request. - **req.path**: The path of the incoming request. ### Logic - Sets `req.headers["X-Powered-By"] = "HappyX"`. - Logs `"Processing: " + req.path` to the console. ## GET /protected ### Description This endpoint is protected and requires an `Authorization` header for access. It returns protected content if authentication is successful. ### Method GET ### Endpoint /protected ### Parameters #### Request Headers - **Authorization** (string) - Required - Authentication token or credentials. ### Response #### Success Response (200) - **data** (string) - The protected content. #### Error Response (401) - **error** (string) - "Unauthorized" ### Response Example (Success) ```json { "data": "Protected content" } ``` ### Response Example (Error) ```json { "error": "Unauthorized" } ``` ## GET / ### Description This is the root endpoint that returns a simple "Home" message. ### Method GET ### Endpoint / ### Response #### Success Response (200) - (string) - "Home" ## Custom 404 Handler (notfound) ### Description This handler is invoked when no other route matches the incoming request, returning a custom 404 Not Found response. ### Method All unmatched routes ### Endpoint N/A ### Parameters #### Request Context - **req.path**: The path of the unmatched request. ### Response #### Not Found Response (404) - **error** (string) - "Route not found" - **path** (string) - The requested path that was not found. ### Response Example ```json { "error": "Route not found", "path": "/nonexistent/path" } ``` ``` -------------------------------- ### Custom Path Parameters (Node.js) Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates how to register and use custom path parameter types with validation and parsing logic in Node.js. ```APIDOC ## Custom Path Parameters (Node.js) ### Description Define custom parameter types with validation and parsing logic. ### Method GET ### Endpoint `/message/{q:query}` ### Parameters #### Path Parameters - **q** (query) - Custom type 'query' matching `[^:]+:\S+`, parsed into an object with 'key' and 'value'. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "None" } ``` ### Response #### Success Response (200) - **body** (string) - A string indicating the processed query parameter. #### Response Example ``` Query: example = value ``` ``` -------------------------------- ### Request Models: User Data - FastAPI and HappyX Source: https://github.com/hapticx/happyx/wiki/HappyX-for-FastAPI-Programmers Shows how to define and use request models for handling incoming data, such as user information, in FastAPI and HappyX. FastAPI leverages Pydantic for model definition, while HappyX provides built-in support for JSON, XML, form-data, and x-www-form-urlencoded. ```python from pydantic import BaseModel from fastapi import FastAPI class User(BaseModel): username: str age: int app = FastAPI() @app.post("/") def create_user(user: User): # create user return {"response": { "id": 0, "username": user.username }} ``` ```nim import happyx model User: username: string age: int serve "127.0.0.1", 5000: post "/[user:User]": # create user return {"response": { "id": 0, "username": user.username }} ``` -------------------------------- ### Custom Path Parameter Types (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates how to register and use custom path parameter types with regex patterns and converters in Nim. ```APIDOC ## Custom Path Parameters (Nim) ### Description Register custom path parameter types with regex patterns and converters. ### Method GET ### Endpoint - `/search/{q:query}` - `/item/{id:int}` ### Parameters #### Path Parameters - **q** (query) - Custom type 'query' matching `[^:]+:\S+`. - **id** (int) - Built-in integer type. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "None" } ``` ### Response #### Success Response (200) - **query** (object) - Contains 'key' and 'value' from the parsed query parameter. - **item_id** (integer) - The parsed integer ID from the path. #### Response Example ```json { "query": "example_key", "result": "example_value" } ``` ```json { "item_id": 123 } ``` ``` -------------------------------- ### Custom Path Parameters (Java) Source: https://context7.com/hapticx/happyx/llms.txt Demonstrates how to register and use custom path parameter types with validation and parsing logic in Java. ```APIDOC ## Custom Path Parameters (Java) ### Description Define custom parameter types with validation and parsing logic. ### Method GET ### Endpoint `/message/{q:query}` ### Parameters #### Path Parameters - **q** (query) - Custom type 'query' matching `[^:]+:\S+`, parsed into a `Query` object with 'key' and 'value'. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "None" } ``` ### Response #### Success Response (200) - **body** (string) - A string indicating the processed query parameter. #### Response Example ``` Query processed ``` ``` -------------------------------- ### Request Models (Python) Source: https://context7.com/hapticx/happyx/llms.txt Shows how to use metaclass-based request models in Python for automatic request body parsing. ```APIDOC ## POST /user ### Description This endpoint accepts user data in the request body and uses the `User` model for automatic parsing. ### Method POST ### Endpoint /user ### Parameters #### Request Body - **username** (string) - Required - The username of the user. - **age** (integer) - Required - The age of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "username": "jane_doe", "age": 25, "email": "jane.doe@example.com" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request. - **user** (object) - A dictionary representation of the parsed user object. #### Response Example ```json { "status": "created", "user": { "username": "jane_doe", "age": 25, "email": "jane.doe@example.com" } } ``` ## POST /message ### Description This endpoint accepts message data in the request body and uses the `Message` model for automatic parsing. ### Method POST ### Endpoint /message ### Parameters #### Request Body - **text** (string) - Required - The content of the message. - **fromId** (integer) - Required - The ID of the sender. ### Request Example ```json { "text": "Hi there!", "fromId": 456 } ``` ### Response #### Success Response (200) - **received** (string) - The received message text. - **from** (integer) - The ID of the sender. #### Response Example ```json { "received": "Hi there!", "from": 456 } ``` ``` -------------------------------- ### Serving Static Assets with HappyX Source: https://github.com/hapticx/happyx/wiki/SPA This snippet shows how to serve static assets, such as images, within a HappyX SPA. It uses the `tImg` component to render an image located in the `public` folder. Assets placed in the `public` directory are served directly by the web server. ```nim import happyx appRoutes("app"): "/": tImg(src = "public/hello.png") ``` -------------------------------- ### Route Decorators (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Applies built-in decorators for rate limiting, caching, and authentication in Nim. ```APIDOC ## Route Decorators (Nim) ### Description Apply built-in decorators for authentication, caching, and rate limiting. ### Method GET ### Endpoint - `/api/data` - `/expensive` - `/protected` - `/modern` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "None" } ``` ### Response #### Success Response (200) - **data** (string) - Response for the rate-limited endpoint. - **body** (any) - Response from an expensive computation (cached). - **message** (string) - Response for the protected endpoint. - **body** (string) - Response for modern browsers. #### Response Example ```json { "data": "Rate limited endpoint" } ``` ```json { "message": "Authenticated content" } ``` ``` Modern browsers only ``` ``` -------------------------------- ### Route Decorators for Rate Limiting and Caching (Nim) Source: https://context7.com/hapticx/happyx/llms.txt Applies built-in route decorators in Nim for common cross-cutting concerns. Includes rate limiting, caching, authentication, and user agent filtering. ```nim import happyx serve "127.0.0.1", 5000: # Rate limit: 100 requests per minute @rateLimit(100, 60) get "/api/data": return {"data": "Rate limited endpoint"} # Cache response for 300 seconds @cached(300) get "/expensive": # Expensive computation let result = computeExpensiveData() return result # Basic authentication @auth("username", "password") get "/protected": return {"message": "Authenticated content"} # User agent filtering @userAgent(["Chrome", "Firefox"]) get "/modern": return "Modern browsers only" ``` -------------------------------- ### Compiling Nim to JavaScript for HappyX Source: https://github.com/hapticx/happyx/wiki/SPA This command demonstrates how to compile Nim code into JavaScript for use in a web browser. The `nim js` command takes the source Nim file (`main.nim`) as input and produces the corresponding JavaScript output. ```bash nim js main ```