Documentation
¶
Overview ¶
Package api extracts HTTP endpoints from source: the routes a service exposes, and the handler behind each one.
Why this is framework-specific, and why that is the honest design ¶
There is no language-level concept of "an HTTP endpoint". Every framework invents its own spelling — a Java annotation, a Go method call on a router, a Python decorator, a JavaScript member call — and the only way to find them is to know the framework. That makes this Tier-3 work by the project's own definition: real value, per-framework cost, and a coverage story that must be stated rather than implied.
The alternative, matching anything that looks like a URL path, produces endpoints from log format strings and documentation comments. An invented endpoint is worse than a missing one: it appears in an API surface report as a route that does not exist.
What is covered ¶
Spring (Java), net/http and the chi/gin/echo family (Go), FastAPI, Flask and Django urlconfs (Python), Express and NestJS controllers (JavaScript/TypeScript). Coverage is reported by SupportedFrameworks so `doctor` can state it rather than leaving a user to infer it from an empty result.
NOT covered, and deliberately: OpenAPI documents, GraphQL schemas, gRPC service definitions, and API-gateway configuration. Each is a real discovery source from spec §21 and each is a separate body of work; claiming them by half-implementing them would be the overclaim this codebase is built to avoid.
Confidence ¶
An annotation or a router registration is an explicit, unambiguous statement by the author, so a route found this way is ConfidenceHigh. Nothing here is ever exact: exact is reserved for facts a compiler proved, and no compiler checked that this string is a route. A path assembled at run time is reported with its literal part and a lower confidence, because a partially-known route is still worth knowing about.
Index ¶
- Constants
- func GoModulePath(gomod string) string
- func GoPackageDir(importPath string, modules map[string]string) (string, bool)
- func JoinRoutePath(prefix, path string) string
- func PyLiteralTable(src []byte, name string) (string, bool)
- func ResolveJSModulePath(importerPath, modImport string, sortedFiles []string) string
- type Call
- type Client
- type Framework
- type GoRouteSite
- type GoRouterCall
- type GoRouterFile
- type GoRouterFunc
- type GoRouterVar
- type JSImport
- type JSMount
- type JSRouters
- type PyFactory
- type PyFactoryCall
- type PyImport
- type PyMount
- type PyRouters
- type PyTableLoop
- type Route
Constants ¶
const RuntimeRouteDoc = "route registered at run time: its path is built from values the source does not state"
RuntimeRouteDoc marks an endpoint whose path is built from a value known only when the code runs: a loop over a table that is not a literal, or a function argument no call states. The path is reported as written.
const RuntimeRouteResolvedDoc = "route registered at run time: path read from the values its registration is given"
RuntimeRouteResolvedDoc marks such an endpoint once a pass that sees the whole run has read the values (an imported literal table, a factory's call arguments) and named it after the path it is served at.
Variables ¶
This section is empty.
Functions ¶
func GoModulePath ¶
GoModulePath reads the module path of a go.mod file.
func GoPackageDir ¶
GoPackageDir is the directory of an import path inside the repository, given the repository's Go modules (module path -> directory). ok is false for a package outside every module, the standard library and dependencies.
func JoinRoutePath ¶
JoinRoutePath composes a mount prefix with a route path.
func PyLiteralTable ¶
PyLiteralTable returns the literal text a module binds name to at module level, when that is a literal table (read by another file's loop).
func ResolveJSModulePath ¶
ResolveJSModulePath finds the file a relative import names. sortedFiles must be sorted. A package import, or an alias such as "@/routes", is outside what can be resolved from the import alone and returns "".
TypeScript compiled to ES modules imports "./users.js" for users.ts, so a .js specifier also tries the TypeScript sources.
Types ¶
type Call ¶
type Call struct {
// Method is the HTTP verb, uppercased, where the syntax states it. Empty
// means the call states no verb this scan could read — a Go request built
// from a variable, or a fetch whose options object was not closed within
// the lines examined. It is reported as "ANY" rather than guessed at.
Method string
// Path is the LITERAL part of the target, as written. It is not normalised
// and not completed: for a dynamic target it holds the constant prefix and
// nothing more, and it is empty when nothing at all was literal.
Path string
// Caller is the name of the declaration whose body contains the call. Empty
// when the call sits outside every declaration this scan could see.
//
// It is a bare name, not an FQN, because this package has no symbol table.
// See attributeCalls: a caller that HAS one should prefer it.
Caller string
// Client is the convention that matched.
Client Client
// Line is the 1-based line the call was written on.
Line int
// Confidence reflects how certain the extraction is, never whether the call
// succeeds at run time.
Confidence model.Confidence
// Dynamic marks a target assembled rather than literal. Path then holds the
// literal prefix, which may be empty.
Dynamic bool
}
Call is one discovered outbound HTTP request.
func ExtractCalls ¶
ExtractCalls finds every outbound HTTP call in one file.
Same trade as Extract, and the same reason: the constructs are line-local and syntactically distinctive, so a scan gets them right without a per-language query set. Where a call is spread across lines, the parts on later lines are not read, and the result is an unresolved path rather than a wrong one.
type Client ¶
type Client string
Client identifies which calling convention matched, so a report can say how a call was found rather than presenting all calls as equally certain.
func SupportedClients ¶
func SupportedClients() []Client
SupportedClients is the coverage statement for outbound calls, and is read the same way SupportedFrameworks is: "no calls found" means either that this file makes none, or that it uses a client not in this list, and a user must be able to tell those apart.
type Framework ¶
type Framework string
Framework identifies which convention matched, so a report can say how a route was found rather than presenting all routes as equally certain.
const ( FrameworkSpring Framework = "spring" FrameworkGoHTTP Framework = "go-http" FrameworkGoChi Framework = "go-router" FrameworkFastAPI Framework = "fastapi" FrameworkFlask Framework = "flask" FrameworkDjango Framework = "django" FrameworkExpress Framework = "express" FrameworkNest Framework = "nest" FrameworkNext Framework = "nextjs" FrameworkCSharpMinimal Framework = "csharp-minimal" FrameworkRustActix Framework = "rust-actix" FrameworkRustAxum Framework = "rust-axum" )
func SupportedFrameworks ¶
func SupportedFrameworks() []Framework
SupportedFrameworks is the coverage statement. `graphlume doctor` prints it so "no endpoints found" can be read correctly: it means either that the service exposes none, or that it uses a framework not in this list, and a user must be able to tell those apart.
type GoRouteSite ¶
type GoRouteSite struct {
Func string
Var GoRouterVar
}
GoRouteSite is where a route is registered.
type GoRouterCall ¶
type GoRouterCall struct {
// Qual is the name before the function's: a package (users.Register),
// a value (h.Register), or the last field of a chain
// (deps.MerchantAck.Mount gives "MerchantAck"). "" for a call in the
// same package.
Qual string
Func string
// Mounted is true for Mount: the callee RETURNS the router it fills.
Mounted bool
// Arg is the router the callee's routes end up under.
Arg GoRouterVar
Line int
}
GoRouterCall hands a router to a function: `pkg.Register(api)`, `r.Route("/x", pkg.Routes)`, or mounts what a function returns: `r.Mount("/x", pkg.Routes())`.
type GoRouterFile ¶
type GoRouterFile struct {
Package string
// Imports maps the name a file uses for a package to its import path.
Imports map[string]string
Funcs map[string]*GoRouterFunc
// Routes maps a route registration's line (1-based, as Route.Line) to the
// function it is in and the router it is registered on.
Routes map[int]GoRouteSite
}
GoRouterFile is what one Go file says about its routers.
func GoRouters ¶
func GoRouters(src []byte) GoRouterFile
GoRouters reads one Go file's router functions, route sites and calls.
type GoRouterFunc ¶
type GoRouterFunc struct {
Name string
// Recv is a method's receiver type without the pointer ("" for a
// function). Methods are keyed Recv+"."+Name in GoRouterFile.Funcs:
// several handler types in one package each have a Mount.
Recv string
// Param is the parameter that receives a router, "" when none does.
Param string
// Returns is the local router variable the function returns, "" when it
// returns none.
Returns string
// Calls are the places this function hands a router to another one.
Calls []GoRouterCall
}
GoRouterFunc is one top-level function or method.
func (*GoRouterFunc) Key ¶
func (f *GoRouterFunc) Key() string
Key is how GoRouterFile.Funcs and GoRouteSite.Func name the function: "Type.Method" for a method, the name for a function.
type GoRouterVar ¶
GoRouterVar is a router expression reduced to the router it was derived from (Root: a parameter or a local router) and the prefix added on the way.
type JSImport ¶
JSImport is one name an import or require binds. Name is the export it names; empty for the module's default export or the whole module.
type JSMount ¶
type JSMount struct {
// Parent is the app or router the child is mounted on.
Parent string
// Child is the mounted router as written: `users`, `routes.users`. Empty
// when the router is required inline, and then ChildModule is set.
Child string
// ChildModule is the module of `app.use('/x', require('./x'))`.
ChildModule string
Prefix string
Line int
}
JSMount is one `parent.use('/prefix', ..., child)` call.
type JSRouters ¶
type JSRouters struct {
Mounts []JSMount
// Imports maps each local name to what it was imported as.
Imports map[string]JSImport
// Prefixes is the prefix each router variable carries within the file,
// from mounts in the same file.
Prefixes map[string]string
// Receivers maps a route call's line (1-based, as Route.Line) to the
// router variable it is called on.
Receivers map[int]string
// Default is the variable the module exports as its default (or as
// module.exports), "" when the file does not say.
Default string
// Exports maps an exported name to the local variable it exports.
Exports map[string]string
}
JSRouters is what one JS/TS file says about its Express routers.
func ExpressRouters ¶
ExpressRouters reads one JS/TS file's imports, exports, route receivers and app.use mounts.
func (JSRouters) ResolveMountTarget ¶
ResolveMountTarget turns a mount into the module that declares the router and the export it names there ("" for the default export). ok is false for a router the imports do not explain, which includes one declared in the mounting file itself (Extract has applied that prefix).
type PyFactory ¶
type PyFactory struct {
Name string
// Line is the def's line, 1-based.
Line int
// Router is the variable its routes are declared on.
Router string
// Returns is true for a factory that builds Router itself and returns it,
// false for one that declares routes on a Router parameter.
Returns bool
// Prefix is the prefix= its own APIRouter(...) is built with, as written;
// "" when there is none.
Prefix string
// contains filtered or unexported fields
}
PyFactory is a module-level function that declares routes on a router it builds and returns, or on a router it is passed.
type PyFactoryCall ¶
type PyFactoryCall struct {
// Callee is the function as written: `build_router`, `approvals.build_router`.
Callee string
Args []string
// Line is the call's first line, 1-based.
Line int
// Parent is the router or app an inline call is mounted on:
// `parent.include_router(build_router(...), prefix=...)`.
Parent string
// Prefix is that include_router's own prefix=, "" when there is none.
Prefix string
// Bound is the variable a call's result is assigned to: `x = build_router()`.
Bound string
// Wrapper is set for a call found as the first argument of another call
// that is mounted: `p.include_router(with_deps(build_router(...), ...))`.
// The wrapper is assumed to return the router it is given, which is not
// proven, so the routes are graded medium.
Wrapper string
// Names are the string constants (and, in a loop over a literal table,
// the row's values) in scope at the call, to evaluate its arguments.
Names map[string]string
}
PyFactoryCall is one call of a function that may be a router factory.
type PyImport ¶
PyImport is one name bound by an import statement: `from Module import Name`, or `import Module` when Name is empty. Module keeps the leading dots of a relative import.
type PyMount ¶
type PyMount struct {
// Parent is the router or app the child is mounted on, a variable of the
// mounting file.
Parent string
// Child is the mounted router as written: `users.router`, `users_router`.
Child string
// Prefix is the call's prefix= or url_prefix=, "" when there is none.
Prefix string
Line int
}
PyMount is one include_router or register_blueprint call.
type PyRouters ¶
type PyRouters struct {
// Prefixes is the prefix each router variable carries within the file:
// its own declaration's, and that of any mount in the same file.
Prefixes map[string]string
// Mounts are the file's include_router and register_blueprint calls.
Mounts []PyMount
// Receivers maps a route decorator's or add_api_route call's line
// (1-based, as Route.Line) to the router variable it is called on.
Receivers map[int]string
// Imports maps each name the file's imports bind to what it names.
Imports map[string]PyImport
// Consts maps each module-level name bound to a string literal.
Consts map[string]string
// Factories are the file's router factories; FactoryCalls the calls that
// may invoke one, here or in another file.
Factories []PyFactory
FactoryCalls []PyFactoryCall
// TableLoops are the loops that register routes over a table this file
// does not define.
TableLoops []PyTableLoop
}
PyRouters is what one Python file says about its routers.
func PythonRouters ¶
PythonRouters reads one Python file's routers, mounts and imports.
func (PyRouters) ResolveMountTarget ¶
ResolveMountTarget turns a mount's child expression into the module that declares the router and the router's variable name there, using the mounting file's imports. ok is false for a name the imports do not explain, which includes a router declared in the mounting file itself (Extract has already applied that prefix).
type PyTableLoop ¶
type PyTableLoop struct {
// Table is the name the iterable reads, as written: `DATA_SETS`,
// `registry.DATA_SETS`.
Table string
// Line is the loop's header line, 1-based.
Line int
}
PyTableLoop is a module-level loop that registers routes over a table this file does not define: one it imports, or one it names through a module.
type Route ¶
type Route struct {
// Method is the HTTP verb, uppercased. Empty means the framework registered
// a handler for every method (Spring's bare @RequestMapping, Express's
// app.all), which is reported as "ANY" rather than guessed at.
Method string
// Path is the route as written, including the framework's parameter syntax.
// It is NOT normalised across frameworks: `/users/{id}`, `/users/:id` and
// `/users/<id>` are how each is actually written, and rewriting them would
// make the report disagree with the source a reader is about to open.
Path string
// Handler is the function or method name the route dispatches to, where
// the framework's syntax makes it recoverable.
Handler string
// Middlewares is the ordered list of middleware handler names associated
// with this route.
Middlewares []string
// Framework is the convention that matched.
Framework Framework
// Line is the 1-based line the route was declared on.
Line int
// Confidence reflects how certain the extraction is, never how correct the
// route is at run time.
Confidence model.Confidence
// Dynamic marks a path that is assembled rather than literal. The literal
// part is still reported.
Dynamic bool
// Router is the router variable the route is declared on, where the
// framework names one (Python: `@users.get`, `users.add_api_route`). Two
// routers in one file may each declare "GET /", and are served apart.
Router string
// Runtime marks a route registered with a path built from a value known
// only when the code runs: a loop over a table that is not a literal, a
// function argument. The path is reported as written.
Runtime bool
}
Route is one discovered HTTP endpoint.
func ExpandPyFactory ¶
func ExpandPyFactory(src []byte, name string, args []string, callerNames map[string]string) (routes []Route, routerArg string, ok bool)
ExpandPyFactory returns the routes one call of a factory declares, with the call's arguments bound: paths carry the factory router's own prefix, and any path built from a parameter takes the argument the call passes. routerArg is, for a factory that declares routes on a parameter, the caller's expression for that parameter. ok is false when the call does not say which router it fills, or passes a prefix not built from literals.
func Extract ¶
Extract finds every route in one file.
Takes the source text rather than a syntax tree. That is a real trade and worth naming: a tree would be more precise, but it would need a per-language query set maintained against six grammars, and the constructs here are line-local and syntactically distinctive enough that a scan gets them right. The gate against false positives is that every pattern requires the framework's own spelling — an annotation, a router method call — not a bare string that looks like a path.
func ExtractPythonWithTables ¶
ExtractPythonWithTables extracts a Python file's routes with tables the file reads from other modules bound: extra maps a table's name as the file writes it (`DATA_SETS`, `registry.DATA_SETS`) to its literal text.