A lightweight, flexible API routing library for JavaScript that provides a simple and extensible way to define and manage API Endpoints.
- Simple
APIandEndpointclass structure - Easy route and method matching
- Flexible endpoint handler execution
- Supports dynamic API routing
This example is taken from a Full Working Example
Defining an API
import{Api,Endpoint}from'simple-api-router';constAPI=newApi("/api/");API.addEndpoint(newEndpoint("time","GET",(req,res)=>{returnSTATE.respondWithContent(res,Date.now().toString(),STATE.TEXT_HTML);}));constHTTPS_SERVER=createServerHTTPS(STATE.loadDefaultSecureContext(),(req,res)=>{if(API.checkFindExecute(req,res)){return;}
...
})...Calling an API
fetch("/api/time").then((response)=>response.json().then((time)=>console.log(time)));new Api(apiRoute): Create a new API with a base route
addEndpoint(endpoint): Add an endpoint to the APIcheckRoute(url): Check if a URL matches the API's base routefindEndpoint(endpointPath): Find an endpoint matching a given pathfindEndpointCheckMethod(req): Find an endpoint and verify its HTTP methodcheckFindExecute(req, res): Attempt to execute the handler for a matching endpoint
new Endpoint(path, method, handler): Create a new endpoint
checkMethod(method): Verify the HTTP methodexecuteHandler(req, res): Execute the endpoint's handlerexecuteHandlerArgs(req, res, ...args): Execute the handler with additional arguments
- The
Apiclass manages a collection of endpoints for a specific route prefix Endpointinstances define specific path, HTTP method, and handler combinationscheckFindExecutemethod provides a convenient way to route and handle requests