System and method for generating http request code based on interface document

By using a system and methodology based on interface documentation, clear and standardized HTTP request code is generated, solving the problems of frequent changes in interface documentation fields and high code error rates. This achieves efficient and automated interface request code generation and standardization checks, improving development efficiency and code quality.

CN114816356BActive Publication Date: 2025-11-11DAERGUAN DATA (CHENGDU) CO LTD
View PDF 3 Cites 0 Cited by

Patent Information

Application Number
CN202210301824.7
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2022-03-25
Publication Date
2025-11-11
Estimated Expiration
2042-03-25

AI Technical Summary

Technical Problem

Existing technologies suffer from frequent changes in interface documentation fields that require manual updates when generating HTTP request code. The interface input/output parameter model is cumbersome to define, resulting in a high error rate. Furthermore, the generated code structure is unclear and lacks standardization checks, leading to low development efficiency.

Method used

This paper provides a system and method for generating HTTP request code based on interface documentation. The system generates clear and standardized HTTP request code by recursively parsing the abstract syntax tree through modules for interface documentation generation and storage, JSON tree conversion, interface identification, models array generation, services array generation, model file generation, service file generation, api.module file generation, and HTTP request code generation.

Benefits of technology

It generates well-structured and standardized HTTP request code, reducing code error rates, improving development efficiency, automatically checking interface compliance, reducing the need for manual checks, simplifying code maintenance, and improving fault tolerance and ease of development.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN114816356B_ABST
    Figure CN114816356B_ABST
Patent Text Reader

Abstract

This invention discloses a system and method for generating HTTP request code based on interface documentation. The system includes an interface documentation generation and storage module, an interface information standardization verification module, a JSON tree conversion module, an interface identifier module, a models array generation module, a services array generation module, a model file generation module, a service file generation module, an api.module file generation module, and an HTTP request code generation module. This invention avoids internally assembling request headers and formatting request parameters when generating HTTP request function logic; instead, these processes are handled during function calls and in a unified interceptor. Compared to traditional solutions that place all logic within the request function body, this invention ensures clear, concise, and easy-to-use request function logic, reducing its coupling.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to a system and method for generating HTTP request code based on interface documentation, belonging to the field of computer software technology. Background Technology

[0002] After completing the API documentation, the corresponding API request code still needs to be written manually. However, this process presents several problems, such as: frequent changes to fields / structures in the API documentation and cumbersome comparisons, requiring manual code updates for each change; complex and tedious definitions of API input / output parameters, requiring manual addition of each parameter; unclear field information, necessitating frequent switching between API documentation sections to understand field meanings; and human error leading to various coding mistakes, such as mistakenly writing the `result` field as the `results` field. Therefore, a method is needed to automatically generate API request code from the API documentation to improve development efficiency.

[0003] Existing solutions for converting API documentation into request code typically only generate a portion of the core HTTP (Hypertext Transfer Protocol) code, without adding API / field comments, parameter types, or other information. Generally, traditional code generation solutions assemble the request headers and parameters for each API within the request function body, resulting in bloated, obscure, and repetitive code. When encountering issues such as duplicate functions or API fields, they often use hash methods to ensure naming consistency, but this also makes the meaning of the hash methods difficult for users to understand directly. Summary of the Invention

[0004] The purpose of this invention is to address the deficiencies mentioned in the background section above.

[0005] To achieve the aforementioned objectives, in a first aspect, the present invention provides a system for generating HTTP request code based on interface documentation, comprising: an interface documentation generation and storage module for writing interface documentation and storing it in a database; an interface information standardization verification module for verifying whether the interface information in the interface documentation conforms to the RESTful API specification; a JSON tree conversion module for converting interface information with a flat, linear structure conforming to the RESTful API specification into a JSON tree; an interface identification module for extracting interface information from the JSON tree to form a unique identifier for the interface; a models array generation module for generating a models array by extracting the input / output parameters of the interface and adding comments; a services array generation module for generating a services array by parsing the module name, request / return parameters, and interface path of the interface and adding comments; a model file generation module for traversing the models array and generating at least one model file using the template rendering engine Handlebars, wherein one model file stores the parameter type content of one module in the project; and a service file generation module for traversing the services array and generating at least one service file using the template rendering engine Handlebars, wherein one service file stores the parameter type content of one module in the project. The module includes: an HTTP request function; an api.module file generation module, which encapsulates all model and service files into an api.module file and exposes it for external calls to HTTP request functions or parameter type definitions; an HTTP request code generation module, which outputs the api.module file to the user-configured code output path, uses a syntax analyzer to perform syntax checking on the project's entry file, and uses a lexical analyzer to convert the code character sequence into a token sequence, ultimately generating an abstract syntax tree; recursively parses the abstract syntax tree, creates an AST node named ImportDeclaration, which represents the reference statement of api.module; inserts this node at the last ImportDeclaration node of the abstract syntax tree, decompiles the returned new abstract syntax tree, generates HTTP request code, and writes it to the project's entry file.

[0006] Furthermore, the interface information in the JSON tree includes at least the module name and the interface path.

[0007] Furthermore, the interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

[0008] Furthermore, the HTTP request function includes a function name, function input parameter aliases and types, function output parameter aliases and types, HTTP request method, and interface path.

[0009] Furthermore, the function name is formed by concatenating the interface request method and the interface path.

[0010] Secondly, the present invention provides a method for generating HTTP request code based on interface documentation, comprising the following steps: (1) writing interface documentation and storing it in a database; (2) verifying whether the interface information in the interface documentation conforms to the RESTful API specification; if yes, proceed to the next step, otherwise end; (3) converting the interface information of the flat linear structure conforming to the RESTful API specification into a JSON tree; (4) extracting the interface information from the JSON tree to form a unique identifier for the interface; (5) extracting the input / output parameter content of the interface and adding comments to generate a models array; (6) parsing the module name, request / return parameters, and interface path of the interface, and adding comments to generate a services array; (7) traversing the models array and using the template rendering engine handlebars to generate at least one model file, one of which stores the parameter type content of a module in the project; (8) traversing the services array and using the template rendering engine handlebars to generate at least one service file, one of which stores the HTTP request function of a module in the project. (9) Encapsulate all model files and service files into an api.module file and expose it to the outside world for external calls to HTTP request functions or parameter type definitions; (10) Output the api.module file to the code output path configured by the user, use a syntax analyzer to perform syntax checks on the project's entry file, and use a lexical analyzer to convert the code character sequence into a token sequence, and finally generate an abstract syntax tree; recursively parse the abstract syntax tree, create an AST node named ImportDeclaration, which represents the reference statement of api.module; insert the node into the last ImportDeclaration node of the abstract syntax tree, decompile the returned new abstract syntax tree, generate HTTP request code, and write it into the project's entry file.

[0011] Furthermore, the interface information in the JSON tree includes at least the module name and the interface path.

[0012] Furthermore, the interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

[0013] Furthermore, the HTTP request function includes a function name, function input parameter aliases and types, function output parameter aliases and types, HTTP request method, and interface path.

[0014] Furthermore, the function name is formed by concatenating the interface request method and the interface path.

[0015] Compared with the prior art, the beneficial effects of the present invention are as follows:

[0016] 1. All description information, field names, and field types were extracted from the API documentation. Using a depth-first recursive algorithm, multiple code files were generated according to module categories, resulting in a clear structure. Each API file also included comments, input parameter types, output parameter types, and method functions. Finally, each generated code file was encapsulated into an API module, which was then exposed externally. In contrast, the traditional method generated all code in a single file.

[0017] 2. When generating HTTP request function logic, the system does not internally assemble request headers or format request parameters; instead, these processes are handled during function calls and in a unified interceptor. Compared to traditional solutions that place all logic within the request function body, this invention ensures clear, concise, and easy-to-use request function logic, while reducing its coupling.

[0018] 3. During the generation of HTTP request code, the specification of each interface is scanned to check if it conforms to the RESTful API style. If any interface in the documentation does not conform to the specification, a corresponding prompt will be given, and the code generation process will be interrupted. Traditional methods do not include this step; after developers complete their documentation, others must manually check its compliance.

[0019] 4. By parsing the source code's Abstract Syntax Tree (AST), the original project code and the new code are associated and referenced, and syntax validation is performed. Compared to the traditional method of modifying the original project code using regular expressions, this reduces the risk and improves the fault tolerance. Furthermore, based on real-world projects, it ensures out-of-the-box usability during development.

[0020] 5. No need for developers to write API request code; it's automatically generated based on the API documentation, saving development time. The generated API request code also includes API name descriptions, field meanings, and other relevant comments, eliminating the need for developers to repeatedly switch between documents to search for API or field definitions. After the field type definitions are filled in the API documentation, the entire API's parameter type definitions are directly generated, automatically prompting developers with field structure and content when referencing API return fields. Furthermore, combined with coding tools, it automatically indicates error messages in case of parameter mismatches, helping developers quickly troubleshoot problems. Attached Figure Description

[0021] Figure 1 This is a flowchart of one embodiment of the method of the present invention;

[0022] Figure 2 This is a flowchart illustrating the generation process of the models file in one embodiment of the method of the present invention;

[0023] Figure 3 This is a flowchart illustrating the generation process of the services file in one embodiment of the method of the present invention;

[0024] Figure 4 This is a flowchart of source code parsing in one embodiment of the system / method of the present invention;

[0025] Figure 5 This is a data structure diagram of the api.module file in one embodiment of the system / method of the present invention;

[0026] Figure 6 This is a schematic diagram of the interface documentation writing interface in one embodiment of the system / method of the present invention;

[0027] Figure 7 This is a schematic diagram of the interface for requesting parameters and returning data in one embodiment of the system / method of the present invention. Detailed Implementation

[0028] The technical solution of the present invention will be further described below with reference to the accompanying drawings and specific embodiments.

[0029] like Figures 1-5As shown, an embodiment of the system for generating HTTP request code based on interface documentation according to the present invention includes: an interface documentation generation and storage module for writing interface documentation and storing it in a database; an interface information standardization verification module for verifying whether the interface information in the interface documentation conforms to the RESTful API specification; a JSON tree conversion module for converting interface information with a flat, linear structure conforming to the RESTful API specification into a JSON tree; an interface identification module for extracting interface information from the JSON tree to form a unique identifier for the interface; a models array generation module for generating a models array by extracting the input / output parameters of the interface and adding comments; a services array generation module for generating a services array by parsing the module name, request / return parameters, and interface path of the interface and adding comments; a model file generation module for traversing the models array and generating at least one model file using the template rendering engine Handlebars, where one model file stores the parameter type content of one module in the project; and a service file generation module for traversing the services array and generating at least one service file using the template rendering engine Handlebars, where one service file stores the parameter type content of one module in the project. The module includes: an HTTP request function; an api.module file generation module, which encapsulates all model and service files into an api.module file and exposes it for external calls to HTTP request functions or parameter type definitions; an HTTP request code generation module, which outputs the api.module file to the user-configured code output path, uses a syntax analyzer to perform syntax checking on the project's entry file, and uses a lexical analyzer to convert the code character sequence into a token sequence, ultimately generating an abstract syntax tree; recursively parses the abstract syntax tree, creates an AST node named ImportDeclaration, which represents the reference statement of api.module; inserts this node at the last ImportDeclaration node of the abstract syntax tree, decompiles the returned new abstract syntax tree, generates HTTP request code, and writes it to the project's entry file.

[0030] In one embodiment, the interface information in the JSON tree includes at least the module name and the interface path.

[0031] In one embodiment, the interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

[0032] In one embodiment, the HTTP request function includes a function name, function input parameter aliases and types, function output parameter aliases and types, HTTP request method, and interface path.

[0033] In one embodiment, the function name is formed by concatenating the interface request method and the interface path.

[0034] like Figures 1-5 As shown, an embodiment of the method for generating HTTP request code based on interface documentation according to the present invention includes the following steps: (1) writing interface documentation and storing it in a database; (2) verifying whether the interface information in the interface documentation conforms to the RESTful API specification; if yes, proceed to the next step, otherwise end; (3) converting the interface information of the flat linear structure conforming to the RESTful API specification into a JSON tree; (4) extracting the interface information from the JSON tree to form a unique identifier for the interface; (5) extracting the input / output parameter content of the interface and adding comments to generate a models array; (6) parsing the module name, request / return parameters, and interface path of the interface, and adding comments to generate a services array; (7) traversing the models array and using the template rendering engine handlebars to generate at least one model file, one of which stores the parameter type content of a module in the project; (8) traversing the services array and using the template rendering engine handlebars to generate at least one service file, one of which stores the HTTP request function of a module in the project. (9) Encapsulate all model files and service files into an api.module file and expose it to the outside world for external calls to HTTP request functions or parameter type definitions; (10) Output the api.module file to the code output path configured by the user, use a syntax analyzer to perform syntax checks on the project's entry file, and use a lexical analyzer to convert the code character sequence into a token sequence, and finally generate an abstract syntax tree; recursively parse the abstract syntax tree, create an AST node named ImportDeclaration, which represents the reference statement of api.module; insert the node into the last ImportDeclaration node of the abstract syntax tree, decompile the returned new abstract syntax tree, generate HTTP request code, and write it into the project's entry file.

[0035] In one embodiment, the interface information in the JSON tree includes at least the module name and the interface path.

[0036] In one embodiment, the interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

[0037] In one embodiment, the HTTP request function includes a function name, function input parameter aliases and types, function output parameter aliases and types, HTTP request method, and interface path.

[0038] In one embodiment, the function name is formed by concatenating the interface request method and the interface path.

[0039] To facilitate understanding of this invention, some application examples are given below for specific illustration:

[0040] Step 1: Use a visualization system (such as yapi) to write the interface documentation and save it to the database.

[0041] Step 2: Traverse the API documentation data from the database table in Step 1 to extract API information. During the extraction process, simultaneously verify whether the API documentation conforms to the RESTful API style. If any non-compliant issues are found in the API documentation, display the API name and suggested guidelines, and terminate the process. If compliant, convert the flat linear structure into a tree structure, ultimately forming a JSON (JavaScript Object Notation) tree.

[0042] Step 3: Extract the module name and API path from the JSON tree, segment them using underscores, colons, and forward slashes, and assemble them into a large camelCase string to uniquely identify the API. (e.g., / api / user / comment_list / :id is assembled into ApiUserCommentListId). Model-related fields are used to generate type names. For output parameters, add the Res identifier before the type name; for input parameters, add the Params identifier to the end of the type name. This allows developers to quickly determine and retrieve the type of API parameters.

[0043] Step 4: Obtain the API request method and concatenate it with the return structure from Step 3 to generate the API request function name. (Note: This method avoids most function name duplication issues. Furthermore, the code editor allows for fuzzy search, enabling quick writing of the function method given the API path. For example, a GET request for the API ` / api / user / list` corresponds to the function name `getApiUserList`. The coding tool will automatically complete the function name during input.)

[0044] Step 5: Generate the interface input parameter type name (result from Step 3 + Params) and output parameter type name (Res + result from Step 3). (Note: Adding the Res and Params identifiers distinguishes the naming of input and output parameters. For example: Input parameter: ApiUserCommentListIdParams, Output parameter: ResApiUserCommentListId)

[0045] Step 6: Extract the request parameter object and return parameter object from the JSON tree, and assemble them with the return result from Step 5 in key-value format to generate the models object. (Note: ApiUserCommentListIdParams: {parameter object xxx}).

[0046] Step 7: Extract the content of the interface and parameter field types from the JSON tree and add comments.

[0047] Step 8: Repeat steps 3-7 until all model parameters have been generated. Store all model parameters in the `models` array as an object array (Note: An object array is a structure where the elements stored in the array are objects. For example: [{name:1},{name:2}]). (The flowchart for generating `models` is shown below.) Figure 2 (As shown)

[0048] Step 9: Parse the module name of the interface in the JSON to generate the service class name. Add comment information fields.

[0049] Step 10: Parse the interface request / return parameters, request method, interface path, input parameter position, and other fields in the module to which Step 9 belongs, and store them in a service array object (Note: An object array is a structure in which the elements stored in the array are objects. For example: [{name:1},{name:2}]).

[0050] Step 11: Repeat steps 9-10 until the service information for all modules has been generated, and save the results to the services array. (The flowchart for generating services is shown below.) Figure 3 (As shown)

[0051] Step 12: Iterate through the results of Steps 8 and 11, using the Handlebars template rendering engine to replace the variables in the model and service template files with the results of each iteration. The model file stores the parameter types of all interfaces under a certain module (Note: A project may have multiple modules such as user and permission modules, and a module corresponds to many interfaces, so here a module corresponds to a service file, which contains all the interface request functions under that module, and the model corresponds to all the parameter type definitions under that module). The service file stores all the HTTP request functions under a certain module.

[0052] Step 13: Generate the api.module file (its data structure is as follows) Figure 5 As shown, import all model and service files and expose the module file externally. When external systems need to call functions or type definitions, they can simply reference this module.

[0053] Step 14: Output all code files from Steps 12 and 13 to the specified location according to the code output path configured by the user.

[0054] Step 15: Use a parser to perform syntax checks on the entry file in the project, and use a lexical analyzer to convert the code character sequence into a token sequence, ultimately generating an Abstract Syntax Tree (AST).

[0055] Step 16: Recursively parse the abstract syntax tree from Step 15, creating an AST node named ImportDeclaration, which represents the reference statement of api.module. Insert this node at the last ImportDeclaration node in the abstract syntax tree, ensuring that the original reference order of the entry file is not disrupted.

[0056] Step 17: Decompile the new abstract syntax tree returned in Step 16 to generate HTTP request code and write it into the entry file. (Source code parsing flowchart is shown below.) Figure 4 (As shown).

[0057] Parser: A parser typically appears as a component of a compiler or interpreter. Its role is to perform syntax checking and build a data structure (usually a hierarchical data structure such as a parse tree or abstract syntax tree) composed of the input words. A parser typically uses a separate lexical analyzer to separate individual "words" from the input character stream and uses the word stream as its input.

[0058] Lexical analyzer: Lexical analysis is the process in computer science of converting a sequence of characters into a sequence of tokens. The program or function that performs lexical analysis is called a lexical analyzer (or simply lexer), also known as a scanner. Lexical analyzers typically exist as functions that are called by the syntax analyzer.

[0059] Token: Here, a token is a string, the smallest unit that constitutes source code. The process of generating tokens from the input character stream is called tokenization. During this process, the lexical analyzer also classifies the tokens. The lexical analyzer usually does not care about the relationships between tokens (this falls under the category of syntax analysis). For example, the lexical analyzer can recognize parentheses as tokens, but it does not guarantee that the parentheses match.

[0060] Abstract Syntax Tree (AST): In computer science, an Abstract Syntax Tree (AST), or simply a syntax tree, is an abstract representation of the syntactic structure of source code. It represents the syntactic structure of a programming language in a tree-like structure, where each node represents a structure within the source code. The syntax is described as "abstract" because it doesn't represent every detail of the actual syntax. For example, nested parentheses are implicit in the tree structure and not presented as nodes; conditional jump statements like `if-condition-then` can be represented using nodes with three branches. In contrast to the Abstract Syntax Tree is the Concrete Syntax Tree (usually called a parse tree). Generally, during the translation and compilation of source code, the parser creates a parse tree and then generates the AST from it. Once the AST is created, additional information is added during subsequent processing, such as the semantic analysis phase.

[0061] The following example uses the "User Module" interface documentation of a certain project:

[0062] Step 1: Write the interface documentation, such as Figures 6-7 As shown.

[0063] Step 2: Install the CLI tool globally, and in the root directory of the specified project, execute the `generate api` command, and enter the address of the online interface documentation and the code generation path to generate HTTP request code.

[0064] API documentation JSON tree:

[0065] {"info":{"title":"test1","version":"last"},"basePath":" / ","tags":[{"name":"user","description":"user description"}],"schemes":["http"],"paths":{" / user / :user_id":{"delete":{"tags":["user"],"summary":"Delete user","description":"","consumes":["application / json"],"parameters":[{"name":"user_id","in":"path","description":"","required":true,"type":"string"}],"responses":{"200":{"description":"successful operation","schema":{"$schema":"http: / / json-schema.org / draft-04 / schema#","type":"object","properties":{"code":{"type":"number"},"msg":{"type":"string"},"data":{"type":"null"}},"required":["code","msg","data"]}}}},"put":{"tags":["user"],"summary":"Edit user","description":"","consumes":["application / json"],"parameters":[{"name":"user_id","in":"path","description":"","required":true,"type":"string"},{"name":"params","in":"body","schema":{"$ref":"# / definitions / user / UserUser_idPutParams"}}],"responses":{"200":{"description":"successful operation","schema":{"type":"object","title":"title","properties": {"code": {"type": "number"}, "msg": {"type": "string"}, "data": {"$ref": "# / definitions / user / ResPutUserUser_id"}}, "required": ["code", "msg", "data"]}}}, " / user": {"post": {"tags": ["user"], "summary": "Add user", "description": "", "consumes": ["application / json"], "parameters": [{"name": "params", "in": "body", "schema": {"$ref": "# / definitions / user / UserPostParams"}}], "responses": {"200": {"description": "successful operation", "schema": {"type": "object", "title": "title", "properties": {"code": {"type": "number"}, "msg": {"type": "string"}, "data": {"$ref": "# / definitions / user / ResPostUser"}}}, "required": ["code", "msg", "data"]}}}}, " / user / :id": {"get": {"tags": ["user"], "summary": "Query user", "description": "", "consumes": ["text / plain"], "parameters": [{"name": "id", "in": "path", "description": "", "required": true, "type": "string"}],"responses": {"200": {"description": "successful operation", "schema": {"$schema": "http: / / json-schema.org / draft-04 / schema#", "type": "object", "properties": {"code": {"type": "number"}, "msg": {"type": "string"},"data": {"$ref": "# / definitions / user / ResGetUserId"}},"required": ["code", "msg", "data"]}}}}}},"definitions": {"user": {"UserUser_idPutParams": {"type": "object", "title": "title", "properties": {"name": {"type": "string", "description": "User name"}, "desc": {"type": "string", "description": "User description"}, "address": {"type": "string", "description": "Home address"}},"required": ["name", "desc", "address"]}, "ResPutUserUser_id": {"type": "object", "properties": {"id": {"type": "string", "title": "User ID"}},"required": ["id"]}, "UserPostParams": {"type": "object", "title": "title", "properties": {"name": {"type": "string", "title": "User name"}, "desc": {"type": "string", "title": "User description"}, "address": {"type": "string", "title": "Home address"}},"required": ["name", "desc", "address"]}, "ResPostUser": {"type": "object", "properties": {"id": {"type": "string", "title": "User ID"}},"required": ["id"]}, "ResGetUserId": {"type": "object", "properties": {"name": {"type": "string"}, "id": {"type": "number"}},"required": ["name", "id"]}}}},

[0066] Below are the two core files: the `models` directory contains all the model definitions in the API documentation, and the `service` directory contains all the HTTP request functions in the API documentation. The files within this directory are distinguished by the API module name. For example, the generated structure for the user module is shown below:

[0067] api / models / user.ts

[0068] / *tslint:disable* /

[0069] export interface UserUser_idPutParams{

[0070] / **

[0071] *Home address

[0072] /

[0073] address: string;

[0074] / **

[0075] *User Description

[0076] /

[0077] desc:string;

[0078] / **

[0079] Username

[0080] /

[0081] name: string;

[0082] }

[0083] export interface ResPutUserUser_id{

[0084] id: string;

[0085] }

[0086] export interface UserPostParams{

[0087] address: string;

[0088] desc:string;

[0089] name: string;

[0090] }

[0091] export interface ResPostUser{

[0092] id:string;

[0093] }

[0094] export interface ResGetUserId{

[0095] id:number;

[0096] name:string;

[0097] }

[0098] api / service / user.ts

[0099] / *tslint:disable* /

[0100] import{Injectable}from'@angular / core';

[0101] import{HttpClient}from'@angular / common / http';

[0102] import{Observable}from'rxjs';

[0103] import{ICommonResponse}from'.. / strict-http-response';

[0104] import{ApiBaseService}from'.. / base-service';

[0105] import{ResPutUserUser_id,UserUser_idPutParams,ResPostUser,UserPostParams,ResGetUserId}from'.. / models / user';

[0106] / **

[0107] *user description

[0108] * /

[0109] @Injectable({

[0110] providedIn: 'root',

[0111] [[ID=3}}

[0112] export class UserService extends ApiBaseService {

[0113] constructor(protected http: HttpClient) {

[0114] super(http);

[0115] }

[0116] / **

[0117] * Delete user

[0118] * @param user_id

[0119] * @return successful operation

[0120] * /

[0121] deleteUserUserId(user_id: string): Observable<ICommonResponse <null>>{

[0122] return this.http.delete<ICommonResponse <null>>(`user / ${user_id}`)

[0123] }

[0124] / **

[0125] * Edit user

[0126] * @param params The `UserService.PutUserUserIdParams` containing the following parameters:

[0127] *

[0128] * - `user_id`:

[0129] *

[0130] * - `params`:

[0131] *

[0132] * @return successful operation

[0133] * /

[0134] putUserUserId(params: UserService.PutUserUserIdParams): Observable<ICommonResponse<ResPutUserUser_id>> {

[0135] return this.http.put<ICommonResponse<ResPutUserUser_id>>(`user / ${params.user_id}`, params.params)

[0136] }

[0137] / **

[0138] * Add user

[0139] * @param params undefined

[0140] * @return successful operation

[0141] * /

[0142] postUser(params?:UserPostParams):Observable<ICommonResponse <respostuser>>{

[0143] return this.http.post<ICommonResponse <respostuser>>(`user`,params)

[0144] }

[0145] / **

[0146] * Query user

[0147] * @param id

[0148] * @return successful operation

[0149] * /

[0150] getUserId(id: string): Observable<ICommonResponse <resgetuserid>>{

[0151] return this.http.get<ICommonResponse <resgetuserid>>(`user / ${id}`)

[0152] }

[0153] }

[0154] export module UserService{

[0155] / **

[0156] *Parameters for putUserUserId

[0157] /

[0158] export interface PutUserUserIdParams{

[0159] user_id: string;

[0160] params? :UserUser_idPutParams;

[0161] }

[0162] }

[0163] Compared with the prior art, the beneficial effects of the present invention are as follows:

[0164] 1. All description information, field names, and field types were extracted from the API documentation. Using a depth-first recursive algorithm, multiple code files were generated according to module categories, resulting in a clear structure. Each API file also included comments, input parameter types, output parameter types, and method functions. Finally, each generated code file was encapsulated into an API module, which was then exposed externally. In contrast, the traditional method generated all code in a single file.

[0165] 2. When generating HTTP request function logic, the system does not internally assemble request headers or format request parameters; instead, these processes are handled during function calls and in a unified interceptor. Compared to traditional solutions that place all logic within the request function body, this invention ensures clear, concise, and easy-to-use request function logic, while reducing its coupling.

[0166] 3. During the generation of HTTP request code, the specification of each interface is scanned to check if it conforms to the RESTful API style. If any interface in the documentation does not conform to the specification, a corresponding prompt will be given, and the code generation process will be interrupted. Traditional methods do not include this step; after developers complete their documentation, others must manually check its compliance.

[0167] 4. By parsing the source code's Abstract Syntax Tree (AST), the original project code and the new code are associated and referenced, and syntax validation is performed. Compared to the traditional method of modifying the original project code using regular expressions, this reduces the risk and improves the fault tolerance. Furthermore, based on real-world projects, it ensures out-of-the-box usability during development.

[0168] 5. No need for developers to write API request code; it's automatically generated based on the API documentation, saving development time. The generated API request code also includes API name descriptions, field meanings, and other relevant comments, eliminating the need for developers to repeatedly switch between documents to search for API or field definitions. After the field type definitions are filled in the API documentation, the entire API's parameter type definitions are directly generated, automatically prompting developers with field structure and content when referencing API return fields. Furthermore, combined with coding tools, it automatically indicates error messages in case of parameter mismatches, helping developers quickly troubleshoot problems.

[0169] This invention is described with reference to flowchart illustrations and / or block diagrams of systems, methods, and computer storage media according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing device to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing device, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.

[0170] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.

[0171] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.

[0172] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention and not to limit it. Although the present invention has been described in detail with reference to the above embodiments, those skilled in the art should understand that modifications or equivalent substitutions can still be made to the specific implementation of the present invention. Any modifications or equivalent substitutions that do not depart from the spirit and scope of the present invention should be covered within the scope of protection of the claims of the present invention.< / resgetuserid> < / resgetuserid> < / respostuser> < / respostuser> < / null> < / null>

Claims

1. A system for generating HTTP request code based on interface documentation, characterized in that, include: The interface documentation generation and storage module is used to write interface documentation and store it in a database. The interface information compliance verification module is used to verify whether the interface information in the interface document conforms to the RESTful API specification. The JSON tree conversion module is used to convert interface information with a flat, linear structure that conforms to the RESTful API specification into a JSON tree. The interface identification module is used to extract interface information by traversing the JSON tree to form a unique identifier for the interface; The models array generation module generates a models array by extracting the input / output parameters of the interface and adding comments. The services array generation module generates a services array by parsing the module name, request / return parameters, and interface path of the interface and adding comments. The model file generation module iterates through the models array and uses the template rendering engine handlebars to generate at least one model file, one of which stores the parameter type content of a module in the project; The service file generation module iterates through the services array and uses the template rendering engine handlebars to generate at least one service file. One of the service files stores the HTTP request function of a module in the project. The HTTP request function includes the function name, function input parameter alias and type, function output parameter alias and type, HTTP request method and interface path. The function name is formed by concatenating the interface request method and the interface path. The api.module file generation module is used to encapsulate all model files and service files into an api.module file and expose it to the outside world for external calls to HTTP request functions or parameter type definitions; The HTTP request code generation module is used to output the api.module file to the code output path configured by the user, use a syntax analyzer to check the syntax of the project's entry file, and use a lexical analyzer to convert the code character sequence into a token sequence, and finally generate an abstract syntax tree; The abstract syntax tree is recursively parsed, and an AST node named ImportDeclaration is created, which represents the reference statement of api.module. This node is inserted into the last ImportDeclaration node of the abstract syntax tree. The returned new abstract syntax tree is decompiled to generate HTTP request code, which is then written into the project's entry file.

2. The system for generating HTTP request code based on interface documentation according to claim 1, characterized in that, The interface information in the JSON tree includes at least the module name and the interface path.

3. The system for generating HTTP request code based on interface documentation according to claim 2, characterized in that, The interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

4. A method for generating HTTP request code based on interface documentation, characterized in that, Includes the following steps: (1) Write the interface documentation and store it in a database; (2) Verify whether the interface information in the interface document conforms to the RESTful API specification; if yes, proceed to the next step; if no, end. (3) Convert the interface information of the flat, linear structure that conforms to the RESTful API specification into a JSON tree; (4) Extract the interface information from the JSON tree to form a unique identifier for the interface; (5) Extract the input / output parameters of the interface and add comments to generate the models array; (6) Parse the module name, request / return parameters, and interface path of the interface, add comments, and generate the services array; (7) Iterate through the models array and use the template rendering engine handlebars to generate at least one model file, one of which stores the parameter type content of a module in the project; (8) Traverse the services array and use the template rendering engine handlebars to generate at least one service file. One of the service files stores the HTTP request function of a module in the project. The HTTP request function includes the function name, function input parameter alias and type, function output parameter alias and type, HTTP request method and interface path. The function name is formed by concatenating the interface request method and the interface path. (9) Encapsulate all model files and service files into an api.module file and expose it to the outside world for external calls to HTTP request functions or parameter type definitions; (10) Output the api.module file to the code output path configured by the user, use the syntax analyzer to perform syntax checking on the project's entry file, and use the lexical analyzer to convert the code character sequence into a token sequence, and finally generate an abstract syntax tree; The abstract syntax tree is recursively parsed, and an AST node named ImportDeclaration is created, which represents the reference statement of api.module. This node is inserted into the last ImportDeclaration node of the abstract syntax tree. The returned new abstract syntax tree is decompiled to generate HTTP request code, which is then written into the project's entry file.

5. The method for generating HTTP request code based on interface documentation according to claim 4, characterized in that, The interface information in the JSON tree includes at least the module name and the interface path.

6. The method for generating HTTP request code based on interface documentation according to claim 5, characterized in that, The interface information extracted from the JSON tree is assembled into a camelCase string, which is used to uniquely identify the interface.

Citation Information

Patent Citations

  • Code automatic generation method and device, computer device and storage medium

    CN110502242A

  • Software code and document robot method

    CN111666072A

  • Code generation method and device, terminal equipment and storage medium

    CN113419716A