Front-end interface code generation method, device and equipment based on interface description specification
Patent Information
- Application Number
- CN202610287664.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-03-10
- Publication Date
- 2026-07-24
AI Technical Summary
In existing technologies, front-end development requires manually writing interface code, which is inefficient, error-prone, inconsistent with documentation and code, and has high maintenance costs. Especially in microservice architectures with a large number of interfaces and complex parameters, it is difficult to achieve efficient and accurate interface calls.
By parsing the structured data of the interface description specification, type definition files and interface service files are generated, interface call functions are automatically generated, and code inspection and formatting tools are used to ensure the standardization and consistency of the code, realizing the fully automatic conversion from interface documents to front-end code.
It greatly improves development efficiency, reduces the error rate of manual coding, ensures consistency between documentation and code, provides type safety guarantees, and improves the structural standardization and maintainability of code.
Smart Images

Figure CN122450441A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of front-end development technology, and in particular to a method, apparatus and device for generating front-end interface code based on an interface description specification. Background Technology
[0002] With the rapid development of internet technology, microservice architecture and front-end / back-end separation development models have become the industry mainstream. In this model, front-end development teams frequently need to interface with back-end APIs (Application Programming Interfaces). In the traditional front-end development process, after obtaining the interface description specification documents provided by the back-end (such as Swagger documentation), front-end developers need to manually write front-end code to call these interfaces.
[0003] However, this development model with manual intervention has many drawbacks: First, manually writing front-end API code is extremely inefficient. In enterprise applications, there are often hundreds of APIs with complex parameters. Developers need to repeatedly write boilerplate code such as API paths, request methods, and parameter definitions, which consumes a lot of development time.
[0004] Second, manual coding is prone to errors. Developers may misread field names, omit parameters, or write incorrect paths. Furthermore, due to the lack of automated type validation, these errors often only become apparent at runtime or even after deployment, increasing debugging costs.
[0005] Third, maintenance costs are high. When the backend interface changes, frontend developers need to reread the documentation and manually modify the code. If updates are not timely or are missed, it can easily lead to frontend-backend integration failures.
[0006] Fourth, there is a discrepancy between the documentation and the code. The API documentation is separated from the actual calling code. As the project iterates, the documentation often lags behind the code, making it difficult for subsequent maintainers to obtain accurate API information. Summary of the Invention
[0007] This application provides a method, apparatus, and device for generating front-end interface code based on interface description specifications, in order to solve the problems of low efficiency, inconsistency between documentation and code, error susceptibility, and high maintenance costs caused by manual coding in the prior art.
[0008] To address the aforementioned technical problems, this application adopts the following technical solution: providing a front-end interface code generation method based on interface description specifications, the method comprising: Obtain and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes classification tags. Based on the data model definition, a type definition file is generated, and based on the category tags, a corresponding interface service file is generated; Iterate through the interface information, generate each interface call function, and write the interface call function into the corresponding interface service file; The type definition file and the interface service file are formatted to obtain the front-end interface code.
[0009] In one optional embodiment of this application, the interface information further includes an interface description, parameter information, and a request method; The step of traversing the interface information and generating the interface call function includes: Based on the interface description and parameter information, generate function comments; Based on the parameter information and the preset exclusion parameter list, the function parameter list is obtained; Based on the request method and the function parameter list, a function body is generated; wherein, if both query parameters and request body parameters exist in the function parameter list, the function body contains a custom path concatenation function; The function comment, the function parameter list, and the function body are concatenated to obtain the interface call function.
[0010] In one optional embodiment of this application, the interface information further includes response information; Iterate through the interface information and generate the interface call function, which also includes: The return type is determined based on the response information; Add the return type as a generic parameter to the request method call in the function body.
[0011] In one optional embodiment of this application, the request method is a Hypertext Transfer Protocol request method; Before generating the function body based on the request method and the function parameter list, the process further includes: Obtain the mapping table between the preset Hypertext Transfer Protocol request methods and the front-end request method names; The mapping table is searched based on the Hypertext Transfer Protocol request method to determine the name of the front-end request method to be called.
[0012] In one optional embodiment of this application, generating a type definition file based on the data model definition includes: Extract the data model from the data model definition and identify the data type of the data model; the data type includes at least reference type, array type, enumeration type and object type; Based on the data type, corresponding type definition statements are generated, wherein reference types generate type reference statements, array types generate array format definition statements, object types generate interface definition statements, and enumeration types generate union type definition statements; Process the optional attributes in the data model, and add optional identifiers to non-mandatory attributes; The type definition file is generated based on all generated type definition statements.
[0013] In one optional embodiment of this application, the step of formatting the type definition file and the interface service file to obtain the front-end interface code includes: The code inspection tool is invoked to automatically repair the type definition file and the interface service file; Use a code formatting tool to format the repaired type definition file and interface service file; The formatted type definition file is post-processed to replace empty object types with arbitrary types, and the front-end interface code is obtained by combining it with the formatted interface service file.
[0014] In an optional embodiment of this application, writing the interface call function into the corresponding interface service file includes: The target interface service file is determined based on the classification tags in the currently traversed interface information; Check if a function with the same name as the generated interface call function already exists in the target interface service file; If it exists, skip writing the current interface call function; If it does not exist, the current interface call function will be written into the target interface service file.
[0015] To address the aforementioned technical problems, another technical solution adopted in this application is: providing a front-end interface code generation device based on an interface description specification, the device comprising: The parsing module is used to acquire and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes classification tags. The first generation module is used to generate a type definition file based on the data model definition and to generate a corresponding interface service file based on the category label; The second generation module is used to traverse each of the interface information, generate each interface call function, and write the interface call function into the corresponding interface service file; The formatting module is used to format the type definition file and the interface service file to obtain the front-end interface code.
[0016] To solve the above-mentioned technical problems, another technical solution adopted in this application is: to provide a computer device, including a memory, a processor and a computer program stored in the memory, characterized in that the processor executes the computer program to implement the steps of the above-mentioned front-end interface code generation method based on interface description specification.
[0017] To solve the above-mentioned technical problems, another technical solution adopted in this application is: to provide a storage medium on which a computer program is stored, characterized in that the computer program, when executed by a processor, implements the steps of the above-mentioned front-end interface code generation method based on the interface description specification.
[0018] The beneficial effects of this application are as follows: Unlike existing technologies, this application discloses a method, apparatus, and device for generating front-end interface code based on interface description specifications. This method automatically generates type definition files and interface service files based on category tags by acquiring and parsing the structured data of the interface description specifications. This achieves fully automatic conversion from interface documentation to front-end code, greatly improving development efficiency and reducing the error rate of manual coding. Generating code from the same data source as the structured data of the interface description specifications ensures a high degree of consistency between documentation and code. The automatically generated type definition files provide complete type safety guarantees for the front-end project, effectively avoiding compile-time type errors. Simultaneously, the use of category tags enables modular code management, and combined with final code formatting, ensures the structural standardization and maintainability of the generated code. Attached Figure Description
[0019] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort, wherein: Figure 1 This is a flowchart illustrating an embodiment of the front-end interface code generation method based on the interface description specification provided in this application; Figure 2 This is a schematic diagram of an embodiment of the front-end interface code generation device based on the interface description specification provided in this application; Figure 3 This is a schematic diagram of the structure of an embodiment of the storage medium provided in this application; Figure 4 This is a schematic diagram of the structure of an embodiment of the computer device provided in this application. Detailed Implementation
[0020] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of the embodiments. Based on the embodiments of this application, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the scope of protection of this application.
[0021] The terms "first," "second," and "third" used in the embodiments of this application are for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of indicated technical features. Thus, a feature defined as "first," "second," or "third" may explicitly or implicitly include at least one of that feature. In the description of this application, "multiple" means at least two, such as two, three, etc., unless otherwise explicitly specified. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion. For example, a process, method, system, product, or device that includes a series of steps or units is not limited to the listed steps or units, but may optionally include steps or units not listed, or may optionally include other steps or units inherent to these processes, methods, products, or devices.
[0022] In this document, the term "embodiment" means that a particular feature, structure, or characteristic described in connection with an embodiment may be included in at least one embodiment of this application. The appearance of this phrase in various places throughout the specification does not necessarily refer to the same embodiment, nor is it a mutually exclusive, independent, or alternative embodiment. It will be explicitly and implicitly understood by those skilled in the art that the embodiments described herein can be combined with other embodiments.
[0023] This application provides a front-end interface code generation method based on interface description specifications. (See attached document.) Figure 1 , Figure 1 This is a flowchart illustrating an embodiment of the file renaming method based on file content provided in this application. This file renaming method based on file content is preferably applied in the front-end engineering build process in a Node.js environment and can be triggered by script commands.
[0024] In an optional embodiment, before performing the code generation steps S10 to S40 below, environment setup and initialization configuration are required. The specific process is as follows: First, in your Node.js project environment, install the necessary dependencies. Execute the installation command in the command-line terminal to install the core packages for generating type definitions (such as swagger-2-ts-file) and toolkits for code style checks (such as eslint, prettier, etc.).
[0025] Secondly, create a script file (e.g., script / api-2-serve.js) in the project root directory and configure the framework's runtime parameters in that file. Specific configuration details include: 1) Configure the list of excluded parameters, for example, set it to ['Authorization', 'accountId']. The framework will automatically filter out these authentication or public parameters when generating functions to avoid redundant parameters in the function signature.
[0026] 2) Configure a mapping table between the Hypertext Transfer Protocol request method and the frontend request method name. For example, configure the mapping rules as: GET -> getData, POST -> postData, PUT -> putData, DELETE -> deleteData.
[0027] After completing the above configuration, call the run method provided by the framework to start the generation process, passing in the URL address of the interface description specification and the expected type file name (e.g. dev-meta.ts), thereby triggering the subsequent code generation steps.
[0028] The front-end interface code generation method based on the interface description specification provided in this application includes: S10: Obtain and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes category tags.
[0029] In step S10, the original interface definition data is obtained from the data source through an automated data acquisition and parsing mechanism, and then transformed into a structured object that can be recognized and processed by a computer program.
[0030] In one optional embodiment, the interface description specification is preferably the industry-standard Swagger specification or OpenAPI specification. This optional embodiment mainly uses the Swagger specification as an example. Since this specification is usually stored in JSON or YAML format and deployed on a backend server, it needs to be obtained through network requests. Specifically, first, the user-configured Uniform Resource Locator (URL) address for the interface document is read. Then, a GET request is initiated to this address based on HyperText Transfer Protocol Secure (HTTPS) to download the raw data of the interface description specification.
[0031] To address the instability of the network environment, this optional embodiment also introduces a robust fault-tolerance mechanism. Specifically, it includes: 1) Timeout control: Preset a request timeout threshold (e.g., 10 seconds). If no server response is received within the specified timeout threshold, the current request will be automatically terminated to avoid process blocking.
[0032] 2) Automatic retry: If a request fails due to network jitter or other reasons, automatic retry logic will be triggered. Preferably, an exponential backoff algorithm can be used for retries (e.g., retrying at intervals of 1s, 2s, or 4s) to ensure that data can still be successfully acquired during brief network failures.
[0033] 3) Data Validation: Upon successful receipt of response data, a preliminary validation of the data format is performed. If the data is in compressed format, it is decompressed; if it is in YAML format, it is converted to a JSON object. Further checks are conducted to ensure the JSON object contains the necessary fields required by the API description specification (such as the OpenAPI version number, paths field, etc.). If validation fails, a clear exception message is thrown, prompting the user to check the validity of the API documentation, thereby preventing invalid data from entering subsequent processing steps.
[0034] Through the above fault tolerance mechanism, complete and structured interface description data can be reliably obtained, providing a solid data foundation for subsequent parsing work.
[0035] After obtaining the raw JSON data, the core parsing phase begins. This involves traversing each node of the JSON object and performing in-depth extraction and transformation based on two core dimensions: interface information and data model definition.
[0036] 1) Extraction of interface information.
[0037] Iterate through the `paths` objects in the structured data, which contain the definitions of all API interfaces. For each interface path, perform the following extraction operations: Basic information extraction: Extract the request method of the interface (such as GET, POST, PUT, and DELETE). Also extract the summary and description fields of the interface, collectively referred to as the interface description. This information will later be converted into function comments in the code.
[0038] Category Tag Determination: Read the tags array for each interface method. Tags are typically used to categorize interfaces for business purposes (e.g., "User Management," "Order Service"). In this optional embodiment, the first element of the tags array can be extracted as the category tag for that interface by default. This category tag serves as the basis for subsequently generating the corresponding interface service file name and for modular categorization.
[0039] Parameter Information Extraction: Identify the specific location of the parameters (in attribute) and categorize them into path parameters, query parameters, request header parameters, and request body parameters. Specifically, read the raw information and extract the name, description, and data type definition for each parameter. In particular, read the parameter's required attribute to determine if it is mandatory; this attribute information will be retained in the interface information for use in subsequent code generation. If the parameter type is a reference type (i.e., containing a $ref field), parse the data model name that the reference points to, so as to establish the association between the parameter and the type definition in subsequent code generation.
[0040] Response Information Extraction: Parse the `responses` object, focusing on extracting the definition of a successful response with an HTTP status code of 200. By parsing the response body's schema, obtain the interface's returned data structure information, i.e., the response information. This information will be used to determine the function's return type. If a binary stream (`application / octet-stream`) is detected, record the corresponding identifier for subsequent special handling.
[0041] 2) Extraction of data model definition.
[0042] In addition to the interface information, the data model definition also needs to be extracted to prepare for the subsequent generation of type definition files. Locate the components / schemas (OpenAPI 3.0) or definitions (Swagger 2.0) node and perform the following operations: Model traversal: Traverse all data model names and their corresponding schema objects defined under this node.
[0043] Structured storage: The definition of each data model (including attribute lists, type structures, enumeration values, etc.) is converted into a structured object in memory. For example, for a model of an object type, all attribute names and their corresponding types are extracted; for a model of an array type, the element types are extracted.
[0044] Dependency relationship building: During the extraction process, if it is found that an internal property of a model references another model (i.e., there is a nested reference), this reference relationship is recorded to provide a basis for generating the correct type import statement later.
[0045] Through the above parsing process, the original interface description specification data is transformed into two clear sets of in-memory data structures: one is a set of interface information containing category tags, parameter information, request methods, response information, etc., and the other is a set of data model definitions containing all data model structure information. These two sets of data structures together constitute the direct input source for the subsequent code generation steps.
[0046] Unlike existing technologies that separate interface documentation from code, which can easily lead to inconsistencies, this application establishes a single data source principle by directly obtaining structured data from authoritative interface description specifications, ensuring consistency between interface documentation and code. When the backend interface changes, simply re-execute this step to obtain the latest specification data and trigger the subsequent generation process to synchronously update the frontend code, effectively solving the problem of version discrepancies between documentation and code in traditional development.
[0047] S20: Generate type definition files based on data model definitions, and generate corresponding interface service files based on category tags.
[0048] This step S20 includes two parallel processing steps: first, converting the abstract data model definition into a type definition file that conforms to TypeScript syntax to provide type safety for subsequent code; second, creating corresponding interface service files based on business category tags to build a modular container for the code.
[0049] In an optional embodiment, step S20 above further includes: S21: Extract the data model from the data model definition and identify the data type of the data model; the data type includes at least reference type, array type, enumeration type and object type.
[0050] Iterate through the data model definition set constructed in step S10. For each data model definition in the set (i.e., the schema object in Swagger), perform a deep parsing operation to identify its core data type. The specific data type identification logic is as follows: Check the type field. If it is object, it is identified as an object type; if it is array, it is identified as an array type.
[0051] Check if an enum field exists; if it does, identify it as an enumeration type.
[0052] Check if the $ref or originalRef field exists. If it does, it is identified as a reference type, which points to another data model definition.
[0053] The above identification process lays the foundation for the subsequent generation of specific TypeScript syntax.
[0054] S22: Generate corresponding type definition statements based on data types, where reference types generate type reference statements, array types generate array format definition statements, object types generate interface definition statements, and enumeration types generate union type definition statements.
[0055] Based on the data types identified in step S21, a differentiated conversion strategy is used to generate corresponding TypeScript code statements. The specific processing for each data type is as follows: Object type handling: If the data is identified as an object type, an interface definition statement is generated. Specifically, the properties attribute of the data model is parsed, all property definitions are traversed, and a TypeScript interface declaration is generated. For example, for an object model named UserInfo, the structure `export interface UserInfo { ...}` is generated.
[0056] Reference type handling: If a reference type is identified, a type reference statement is generated. The reference path (e.g., # / components / schemas / User) is parsed, the target is extracted as the name of the data model, and this name is directly referenced in the current property definition to ensure accurate mapping of dependencies between data models.
[0057] Furthermore, during the process of parsing reference paths to extract the target data model name, the extracted names can be cleaned. Because interface description specifications (especially Swagger 2.0) may contain special characters (such as "«", "»", etc.) in reference names when handling complex types like generics, these characters do not conform to TypeScript identifier naming conventions. Therefore, special characters in reference type names can be automatically removed using regular expression matching or string replacement algorithms, ensuring that the generated type reference names are all valid TypeScript identifiers and avoiding compilation errors caused by illegal naming.
[0058] Array type handling: If the element is identified as an array, an array format definition statement is generated. The `items` attribute is further parsed to determine the element type, generating an array (e.g., Array). <t>Or a type definition in the form of T[].
[0059] Enumeration type handling: If the enumeration type is identified, a union type definition statement is generated. All enumeration values in the enum array are extracted and connected using a vertical bar (|) to generate a union type of the form 'ACTIVE' | 'INACTIVE', providing stricter type constraints than regular enumerations.
[0060] S23: Process optional attributes in the data model and add optional identifiers to non-required attributes.
[0061] When the data type is an object, the requirement of properties is handled synchronously during the generation of the interface definition statement. The `required` array list in the data model definition is read, which contains the names of all required properties. For the currently processed property, if its name does not exist in the `required` list, it is considered a non-required property. For such properties, an optional identifier (i.e., a question mark "?" in TypeScript syntax) is added after the property name in the generated type definition statement. For example, if the property `nickname` is non-required, `nickname?: string` is generated. This process ensures that the generated type definition is completely consistent with the validation rules of the backend interface.
[0062] S24: Generate a type definition file based on all generated type definition statements.
[0063] Summarize and concatenate all interface definitions, type aliases, and other type definition statements generated in steps S21-S22 above. Add necessary comments (such as generation time, file description, etc.) to the beginning of the file to construct the complete file content. Finally, write this content to the type definition file (e.g., dev-meta.ts) in the project's default path. The type definition file will serve as the type basis for subsequent interface call function generation, providing complete type safety for the entire front-end project.
[0064] In step S20, to avoid piling all interface functions into a single file and to improve code maintainability, the interfaces are divided into different service files according to business categories. The specific implementation process is as follows: 1) Tag Collection and Deduplication: Traverse the interface information set obtained in step S10 and extract the category tags for all interfaces. Perform deduplication on the extracted tags to obtain the list of service files to be generated.
[0065] 2) File creation and initialization: For each unique category tag, perform the following file generation operations: Determine the filename: Generate the corresponding filename based on the category tag. For example, if the tag is user-controller, then the file user-controller.ts will be generated. The file is usually stored in the project's default API directory (such as src / api).
[0066] Check if the file exists: Before creating the file, check if a file with the same name already exists in the target path. If the file already exists, it will not be overwritten, and any user-defined modifications will be preserved; if the file does not exist, a new file will be created.
[0067] Generate file header information: Write a header comment in the newly created file, including information such as author, generation time, and file description.
[0068] Generating import statements: To ensure the subsequent generated API functions can function correctly, dependencies need to be injected in advance at the file header, including generating type import statements and request method import statements. Specifically, the data models that may be involved under this category tag are parsed, generating statements to import types from the type definition file (e.g., `import { UserInfo} from '. / dev-meta';`); and generating statements to import HTTP methods from the project's encapsulated request utility module, such as `import {getData, postData, putData, deleteData} from '@ / utils / fetch';`. These import statements provide the necessary runtime support for generating the function body in the subsequent step S30.
[0069] Unlike existing technologies that lack type safety guarantees and cannot detect API call errors at compile time, this application establishes a solid type system foundation for front-end projects by generating type definition files. Complete TypeScript type definitions enable developers to receive accurate intelligent code completion during the coding phase and automatically detect parameter type errors or mismatched response data structures at compile time, significantly improving code robustness and type safety. Furthermore, creating independent service files based on business category tags avoids piling up all API code in a single file, resulting in a clear and highly modular code structure that greatly improves readability and facilitates subsequent maintenance and expansion.
[0070] S30: Traverse the information of each interface, generate the calling function of each interface, and write the calling function of the interface into the corresponding interface service file.
[0071] In step S30, the parsed interface metadata is converted into executable TypeScript function code. By traversing the set of interface information extracted in step S10, a corresponding interface call function is generated for each interface and archived into the corresponding service file.
[0072] In an optional embodiment, step S30 above further includes: S31: Generate function comments based on interface descriptions and parameter information.
[0073] The API description (such as the `summary` field in the Swagger specification) is read from the current API information and used as the main comment for the function. Simultaneously, the parameter information is iterated, and a corresponding parameter description tag (e.g., `@param`) is generated for each parameter. The API description and parameter descriptions are then combined into a function comment string conforming to JSDoc specifications through string concatenation, providing developers with clear code hints.
[0074] S32: Based on the parameter information and the preset exclusion parameter list, obtain the function parameter list.
[0075] The parameter information parsed in step S10 is read and compared with a pre-defined list of excluded parameters. If a parameter name exists in the exclusion list (such as common parameters like Authorization and token), it is removed to avoid redundant parameters in the generated function signature. For the retained parameters, they are sorted according to their required status: required parameters are listed first, and optional parameters are listed last with an optional identifier (such as a question mark "?"). Finally, the processed parameter names are concatenated with the type definitions to generate a function parameter list string that conforms to TypeScript syntax.
[0076] S33: Generate a function body based on the request method and function parameter list; if both query parameters and request body parameters exist in the function parameter list, the function body contains a custom path concatenation function.
[0077] In step S33, the specific implementation process for generating the function body is as follows: 1) Determine the front-end request method name.
[0078] In an optional embodiment, the request method is a Hypertext Transfer Protocol request method (HTTP Method, such as GET, POST, etc.); before generating the function body based on the request method and the function parameter list, the method further includes: Obtain the mapping table between the preset Hypertext Transfer Protocol request methods and the front-end request method names; The mapping table is looked up based on the Hypertext Transfer Protocol request method to determine the name of the front-end request method to be called.
[0079] In this optional embodiment, a pre-defined mapping table between Hypertext Transfer Protocol (HTTP) request methods and frontend request method names is obtained. Based on the current interface's request method (e.g., GET, POST), the mapping table is searched to determine the actual frontend request method name to be invoked. For example, if the mapping table specifies a correspondence between GET -> getData and POST -> postData, the invocation name will be determined according to this relationship.
[0080] 2) Determine the return type.
[0081] In an optional embodiment, the interface information further includes response information; traversing each interface information and generating each interface call function further includes: Determine the return type based on the response information; Add the return type as a generic parameter to the request method call in the function body.
[0082] In this optional embodiment, the response information in the interface information is parsed to determine the returned data structure of the interface. This return type is then used as a generic parameter and added to the type parameter of the aforementioned front-end request method call (e.g., postData). <returntype>(...)) to ensure the type safety of the returned data.
[0083] 3) Generate the calling logic and construct the request calling code inside the function body.
[0084] In one optional embodiment, the interface path can be format-converted before constructing the request call code within the function body. Specifically, path parameter placeholders conforming to the interface description specification (such as {id}, {userId}, etc.) in the interface path are identified. Using string substitution techniques, these placeholders are converted into interpolated formats of TypeScript template strings (such as ${id}, ${userId}). For example, / api / user / {id} is converted to / api / user / ${id}. The converted path string can be directly embedded in the TypeScript code, dynamically concatenating the actual parameter values at function runtime to accurately construct the request URL.
[0085] During this process, special branch decisions are made: If both query parameters and request body parameters exist in the function parameter list, a call statement containing a custom path concatenation function is generated. Specifically, code of the form `methodName(withParam(path, queryParams), body)` is generated. This custom path concatenation function is responsible for serializing the query parameters and appending them to the URL path, thereby adapting to the parameter passing rules of the underlying request library.
[0086] If query parameters and request body parameters do not exist simultaneously, a regular call statement is generated, directly passing the path or parameter object.
[0087] In an optional embodiment, during the generation of the calling statement, the following special parameters can also be appended based on parameter classification and response information: Request header parameter handling: If the current interface contains request header parameters, the request header configuration parameters are appended to the generated request method call statement. Specifically, a boolean flag (such as true) and an object literal containing the request header field (such as { headerName: headerValue}) are added to the end of the parameter list of the function call to ensure that the request header information can be correctly passed to the underlying request tool.
[0088] Binary stream response handling: If the response information indicates that the interface return type is a binary stream (such as application / octet-stream), then append a response type identifier parameter (such as the string 'blob') to the request method call. This parameter instructs the underlying HTTP client to process the response data as a binary stream to meet the needs of file download or non-text data transmission.
[0089] S34: Concatenate the function comments, function parameter list, and function body to obtain the interface call function.
[0090] Using string concatenation techniques and following TypeScript syntax rules, the function comments, function parameter lists (as function signatures), and function bodies generated in steps S31-S33 are combined to generate a complete `export const` declaration statement, forming the final source code for the interface call function.
[0091] In step S30, after generating the interface call function for each interface, the interface call function must also be written into the corresponding interface service file.
[0092] In an optional embodiment, writing the interface call function into the corresponding interface service file includes: The target interface service file is determined based on the category tags in the currently traversed interface information; Check if a function with the same name as the generated interface call function already exists in the target interface service file; If it exists, skip writing the current interface call function; If it does not exist, the current interface call function will be written into the target interface service file.
[0093] Specifically, based on the category tags in the currently traversed interface information, the target interface service file is determined. Before writing, it is checked whether a function with the same name as the generated interface call function already exists in the target interface service file. If it exists, the writing of the current interface call function is skipped to protect existing custom code and support incremental updates; if it does not exist, the current interface call function is appended to the target interface service file.
[0094] Unlike existing technologies that involve the tedious process of manually writing interface paths, parameter definitions, and request logic, and which often result in spelling errors and missing parameters, this application automatically converts the parsed interface metadata into executable TypeScript function code, reducing manual coding workload by over 90% and significantly improving development efficiency. The automatically generated code based on structured data ensures the accuracy of interface paths, parameter names, and types, effectively avoiding basic errors that occur during manual coding. It also supports flexible configurations such as parameter filtering and request method mapping, adapting to the specific needs of different projects. Special processing logic for complex scenarios such as path parameter conversion and binary stream responses ensures the practicality and completeness of the generated code. Furthermore, the pre-writing check mechanism avoids overwriting existing code, supports incremental updates, and reduces the cost of repetitive work. The generated function call method is intuitive and concise, reducing the learning curve for developers and allowing for direct use.
[0095] S40: Format the type definition file and interface service file to obtain the front-end interface code.
[0096] In this step S40, a series of post-processing operations are performed on the automatically generated original code files (type definition files and interface service files) to eliminate non-standard formatting issues that occur during code generation, improve code quality, and ensure that the final generated front-end interface code conforms to the project coding standards and has good readability.
[0097] In an optional embodiment, step S40 above further includes: S41: Call the code inspection tool to automatically repair the type definition file and interface service file.
[0098] The generated type definition files and interface service files are scanned using static code analysis tools (such as ESLint). Syntax errors, style violations, and other issues are automatically detected and fixed using the tool's built-in auto-repair function, resulting in repaired type definition files and interface service files. For example, missing semicolons are automatically added, quotation mark types are adjusted, and indentation is corrected to ensure the code conforms to preset syntax rules and coding standards.
[0099] S42: Call the code formatting tool to format the repaired type definition files and interface service files.
[0100] After the code is repaired by the code inspection tool, a code formatting tool (such as Prettier) is used to uniformly format the contents of the repaired type definition files and interface service files. Based on the preset configuration file, details such as code indentation style, line break rules, and whitespace usage are uniformly processed to ensure that the generated code style is consistent, making it easier for developers to read and maintain.
[0101] S43: Post-process the formatted type definition file, replace empty object types with arbitrary types, and combine with the formatted interface service file to obtain the front-end interface code.
[0102] Specific semantic optimizations are performed on the type definition files. Because some interfaces may return data structures that are not explicitly defined in the interface description specification, empty object types (i.e., "{}") may appear in the generated TypeScript types. This can lead to overly strict type checking or issues that don't fit the actual use case in development. Therefore, this step iterates through the type definition files, replacing all empty object types with any type from TypeScript to improve code flexibility and avoid potential type errors. Finally, the formatted and post-processed type definition files, along with the interface service files, are used as the final front-end interface code output, completing the entire code generation process.
[0103] By using code inspection and formatting tools for automatic repair and standardized formatting, step S40 eliminates potential formatting issues in automatically generated code, ensuring that the final front-end interface code conforms to project coding standards and maintains a consistent style. This not only improves the static quality of the code but also avoids repetitive manual adjustments to code formatting by developers, further guaranteeing high-quality and highly readable generated code.
[0104] After executing steps S10 to S40 above, the corresponding TypeScript API interface code will be generated in the project's preset path (e.g., src / api). The generated front-end interface code fully complies with standard TypeScript syntax and common functional programming styles, and the interface call method is intuitive and easy to understand. Developers do not need to learn specific framework APIs or complex configuration rules; they can simply import and use the generated interface functions like calling ordinary functions. This low-intrusion design allows new developers joining the team to get started quickly and focus on implementing business logic.
[0105] This application provides a front-end interface code generation device based on the interface description specification, see reference. Figure 2 , Figure 2 This is a schematic diagram of an embodiment of the front-end interface code generation device based on the interface description specification provided in this application. The front-end interface code generation device based on the interface description specification includes: Parsing module 10 is used to acquire and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes classification tags. The first generation module 20 is used to generate a type definition file based on the data model definition and to generate a corresponding interface service file based on the classification label; The second generation module 30 is used to traverse each of the interface information, generate each interface call function, and write the interface call function into the corresponding interface service file; The formatting module 40 is used to format the type definition file and the interface service file to obtain the front-end interface code.
[0106] In an optional embodiment, the interface information further includes an interface description, parameter information, and a request method; The second generation module 30 further includes: Based on the interface description and parameter information, generate function comments; Based on the parameter information and the preset exclusion parameter list, the function parameter list is obtained; Based on the request method and the function parameter list, a function body is generated; wherein, if both query parameters and request body parameters exist in the function parameter list, the function body contains a custom path concatenation function; The function comment, the function parameter list, and the function body are concatenated to obtain the interface call function.
[0107] In an optional embodiment, the interface information further includes response information; The second generation module 30 further includes: The return type is determined based on the response information; Add the return type as a generic parameter to the request method call in the function body.
[0108] In one optional embodiment, the request method is a Hypertext Transfer Protocol (HTTP) request method; Before generating the function body based on the request method and the function parameter list, the process further includes: Obtain the mapping table between the preset Hypertext Transfer Protocol request methods and the front-end request method names; The mapping table is searched based on the Hypertext Transfer Protocol request method to determine the name of the front-end request method to be called.
[0109] In an optional embodiment, the first generation module 20 further includes: Extract the data model from the data model definition and identify the data type of the data model; the data type includes at least reference type, array type, enumeration type and object type; Based on the data type, corresponding type definition statements are generated, wherein reference types generate type reference statements, array types generate array format definition statements, object types generate interface definition statements, and enumeration types generate union type definition statements; Process the optional attributes in the data model, and add optional identifiers to non-mandatory attributes; The type definition file is generated based on all generated type definition statements.
[0110] In an optional embodiment, the formatting module 40 further includes: The code inspection tool is invoked to automatically repair the type definition file and the interface service file; Use a code formatting tool to format the repaired type definition file and interface service file; The formatted type definition file is post-processed to replace empty object types with arbitrary types, and the front-end interface code is obtained by combining it with the formatted interface service file.
[0111] In an optional embodiment, the second generation module 30 further includes: The target interface service file is determined based on the classification tags in the currently traversed interface information; Check if a function with the same name as the generated interface call function already exists in the target interface service file; If it exists, skip writing the current interface call function; If it does not exist, the current interface call function will be written into the target interface service file.
[0112] Since the embodiments of the device part correspond to the embodiments of the above method, the description of the front-end interface code generation device based on the interface description specification provided in this application is based on the above method embodiments. This application will not repeat the description here, as it has the same beneficial effects as the above-described front-end interface code generation method based on the interface description specification.
[0113] See Figure 3 , Figure 3 This is a schematic diagram of an embodiment of the storage medium provided in this application.
[0114] The storage medium 300 stores program data 310, which, when executed by the processor, implements, as follows: Figure 1 The steps described are for generating front-end interface code based on the interface description specification.
[0115] The program data 310 is stored in a storage medium 300 and includes several instructions for causing a network device (which may be a router, personal computer, server, or other network device) or processor to execute all or part of the steps of the methods described in the various embodiments of this application.
[0116] Optionally, the storage medium 300 can be any medium capable of storing program data, such as a USB flash drive, portable hard drive, read-only memory (ROM), random access memory (RAM), disk, or optical disc.
[0117] See Figure 4 , Figure 4 This is a schematic diagram of the structure of an embodiment of the computer device provided in this application.
[0118] The device 400 includes a processor 420 and a memory 410 connected to each other. The memory 410 stores a computer program. When the processor 420 executes the computer program, it implements the steps of the front-end interface code generation method based on the interface description specification described above.
[0119] The various embodiments in this specification are described in a progressive manner. Similar or identical parts between embodiments can be referred to interchangeably. Each embodiment focuses on its differences from other embodiments. In particular, the storage medium embodiments and computer device embodiments are basically similar to the method embodiments, so the descriptions are relatively simple; relevant parts can be referred to the descriptions of the method embodiments.
[0120] This application can be used in a wide range of general-purpose or special-purpose computing system environments or configurations. For example: personal computers, handheld or portable devices, tablet devices, multiprocessor systems, microprocessor-based systems, network PCs, minicomputers, distributed computing environments including any of the above systems or devices, etc.
[0121] In the several embodiments provided in this application, it should be understood that the disclosed methods and devices can be implemented in other ways. For example, the device embodiments described above are merely illustrative; multiple units or components may be combined or integrated into another system, or some features may be omitted or not performed.
[0122] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment, depending on actual needs.
[0123] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0124] The above description is merely an embodiment of this application and does not limit the patent scope of this application. Any equivalent structural or procedural transformations made using the content of this application's specification and drawings, or direct or indirect applications in other related technical fields, are similarly included within the patent protection scope of this application.< / returntype> < / t>
Claims
1. A method for generating front-end interface code based on interface description specifications, characterized in that, include: Obtain and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes classification tags. Based on the data model definition, a type definition file is generated, and based on the category tags, a corresponding interface service file is generated; Iterate through the interface information, generate each interface call function, and write the interface call function into the corresponding interface service file; The type definition file and the interface service file are formatted to obtain the front-end interface code.
2. The front-end interface code generation method based on interface description specifications according to claim 1, characterized in that, The interface information also includes an interface description, parameter information, and request method; The step of traversing the interface information and generating the interface call function includes: Based on the interface description and parameter information, generate function comments; Based on the parameter information and the preset exclusion parameter list, the function parameter list is obtained; Based on the request method and the function parameter list, a function body is generated; wherein, if both query parameters and request body parameters exist in the function parameter list, the function body contains a custom path concatenation function; The function comment, the function parameter list, and the function body are concatenated to obtain the interface call function.
3. The front-end interface code generation method based on interface description specifications according to claim 2, characterized in that, The interface information also includes response information; Iterate through the interface information and generate the interface call function, which also includes: The return type is determined based on the response information; Add the return type as a generic parameter to the request method call in the function body.
4. The front-end interface code generation method based on interface description specifications according to claim 2, characterized in that, The request method is the Hypertext Transfer Protocol (HTP) request method. Before generating the function body based on the request method and the function parameter list, the process further includes: Obtain the mapping table between the preset Hypertext Transfer Protocol request methods and the front-end request method names; The mapping table is searched based on the Hypertext Transfer Protocol request method to determine the name of the front-end request method to be called.
5. The front-end interface code generation method based on interface description specifications according to claim 1, characterized in that, The step of generating a type definition file based on the data model definition includes: Extract the data model from the data model definition and identify the data type of the data model; the data type includes at least reference type, array type, enumeration type and object type; Based on the data type, corresponding type definition statements are generated, wherein reference types generate type reference statements, array types generate array format definition statements, object types generate interface definition statements, and enumeration types generate union type definition statements; Process the optional attributes in the data model, and add optional identifiers to non-mandatory attributes; The type definition file is generated based on all generated type definition statements.
6. The front-end interface code generation method based on interface description specifications according to claim 1, characterized in that, The step of formatting the type definition file and the interface service file to obtain the front-end interface code includes: The code inspection tool is invoked to automatically repair the type definition file and the interface service file; Use a code formatting tool to format the repaired type definition file and interface service file; The formatted type definition file is post-processed to replace empty object types with arbitrary types, and the front-end interface code is obtained by combining it with the formatted interface service file.
7. The front-end interface code generation method based on interface description specifications according to claim 1, characterized in that, The step of writing the interface call function into the corresponding interface service file includes: The target interface service file is determined based on the classification tags in the currently traversed interface information; Check if a function with the same name as the generated interface call function already exists in the target interface service file; If it exists, skip writing the current interface call function; If it does not exist, the current interface call function will be written into the target interface service file.
8. A front-end interface code generation device based on an interface description specification, characterized in that, include: The parsing module is used to acquire and parse the structured data of the interface description specification to obtain the interface information and data model definition corresponding to each interface. The interface information includes classification tags. The first generation module is used to generate a type definition file based on the data model definition and to generate a corresponding interface service file based on the category label; The second generation module is used to traverse each of the interface information, generate each interface call function, and write the interface call function into the corresponding interface service file; The formatting module is used to format the type definition file and the interface service file to obtain the front-end interface code.
9. A computer device, comprising a memory, a processor, and a computer program stored in the memory, characterized in that, The processor executes the computer program to implement the steps of the front-end interface code generation method based on the interface description specification as described in any one of claims 1-7.
10. A storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the front-end interface code generation method based on the interface description specification as described in any one of claims 1-7.