CN114816356A - System and method for generating HTTP request code based on interface document - Google Patents

System and method for generating HTTP request code based on interface document Download PDF

Info

Publication number
CN114816356A
CN114816356A CN202210301824.7A CN202210301824A CN114816356A CN 114816356 A CN114816356 A CN 114816356A CN 202210301824 A CN202210301824 A CN 202210301824A CN 114816356 A CN114816356 A CN 114816356A
Authority
CN
China
Prior art keywords
interface
module
http request
generating
file
Prior art date
Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.)
Pending
Application number
CN202210301824.7A
Other languages
Chinese (zh)
Inventor
李熠
李凌辉
宫旭
陈运文
纪达麒
蔡伟
任帅安
赵朝阳
张绍鼎
李芯杰
Current Assignee (The listed assignees may be inaccurate. Google has not performed a legal analysis and makes no representation or warranty as to the accuracy of the list.)
Daguan Data Chengdu Co ltd
Original Assignee
Daguan Data Chengdu Co ltd
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Daguan Data Chengdu Co ltd filed Critical Daguan Data Chengdu Co ltd
Priority to CN202210301824.7A priority Critical patent/CN114816356A/en
Publication of CN114816356A publication Critical patent/CN114816356A/en
Pending legal-status Critical Current

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F8/00Arrangements for software engineering
    • G06F8/30Creation or generation of source code
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F8/00Arrangements for software engineering
    • G06F8/40Transformation of program code
    • G06F8/41Compilation
    • G06F8/42Syntactic analysis
    • G06F8/427Parsing
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F8/00Arrangements for software engineering
    • G06F8/40Transformation of program code
    • G06F8/53Decompilation; Disassembly

Landscapes

  • Engineering & Computer Science (AREA)
  • General Engineering & Computer Science (AREA)
  • Theoretical Computer Science (AREA)
  • Software Systems (AREA)
  • Physics & Mathematics (AREA)
  • General Physics & Mathematics (AREA)
  • Devices For Executing Special Programs (AREA)

Abstract

The invention discloses a system and a method for generating an HTTP request code based on an interface document, wherein the system comprises an interface document forming and storing module, an interface information normative checking module, a JSON tree conversion module, an interface identification module, a models array generating module, a services array generating module, a model file generating module, a service file generating module, an api. When the HTTP request function logic is generated, a request header, a formatted request parameter and the like are not assembled inside, but are processed in a function calling and unified interceptor. Compared with the traditional scheme that all logics are completely arranged in the request function body, the method and the device ensure that the request function logics are clear, simple and easy to use, and reduce the coupling degree of the request function logics.

Description

System and method for generating HTTP request code based on interface document
Technical Field
The invention relates to a system and a method for generating an HTTP request code based on an interface document, belonging to the technical field of computer software.
Background
After the writing of the interface document is completed, the related interface request code needs to be manually written. However, there are many problems, such as: the field/structure in the interface document is changed frequently and is difficult to compare, and the code needs to be updated manually each time the field/structure is changed; the interface parameter input/output model is fussy to define and needs to be manually added one by one; the field information is ambiguous, and research personnel need to switch interface documents frequently to understand the field meaning; human causes result in a series of code errors, such as, for example, a result field being rewritten as a results field, and so on. Therefore, it is required to improve the efficiency of development using a method of automatically generating an interface request code through an interface document.
The existing scheme for converting an interface document into a request code generally only generates a part of HTTP (Hyper Text Transfer Protocol) core code, and does not add contents such as interface/field comments, parameter types and the like. Generally, a conventional code generation scheme assembles information such as a request header and parameters of each interface in a request function body, so that codes are bloated and obscure and are unintelligible, and a lot of repeated work is performed at the same time. When problems that functions and interface fields are possibly repeated are encountered, naming is ensured not to be conflicted through some hash methods, but the meaning of the hash methods cannot be directly understood by users.
Disclosure of Invention
The object of the present invention is to solve the drawbacks mentioned in the background art.
In order to achieve the above object, in a first aspect, the present invention provides a system for generating an HTTP request code based on an interface document, including an interface document forming and storing module, configured to compile an interface document and store the interface document in a database form; the interface information normalization checking module is used for checking whether the interface information in the interface document conforms to RESTful API (application program interface) specifications; the JSON tree conversion module is used for converting the interface information of the flat layer linear structure conforming to the RESTful API specification into a JSON tree; the interface identification module is used for forming a unique identification of an interface by traversing the JSON tree to extract interface information in the JSON tree; the model array generating module is used for generating the model arrays by extracting the input/output parameter contents of the interfaces and adding comments; the services array generation module generates a services array by analyzing the module name, the request/return parameters and the interface path of the interface and adding comments; the model file generation module is used for traversing the model arrays and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the item; the service file generation module is used for traversing the service array and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project; the module file generating module is used for packaging all the module files and service files into the api module file and exposing the api module file to the outside for externally calling HTTP request functions or parameter type definitions; the HTTP request code generation module is used for outputting the api.module file to a code output path configured by a user, carrying out syntax check on an entry file of a project by using a syntax analyzer, converting a code character sequence into a mark sequence by using a lexical analyzer, and finally generating an abstract syntax tree; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
Further, the interface information in the JSON tree at least includes a module name and an interface path.
Further, the interface information extracted from the JSON tree is assembled into a large hump character string, and the large hump character string is used for uniquely identifying the interface.
Further, the HTTP request function includes a function name, a function entry argument name and type, a function exit argument name and type, an HTTP request mode, and an interface path.
Further, the function name is formed by splicing an interface request mode and an interface path.
In a second aspect, the present invention provides a method for generating an HTTP request code based on an interface document, comprising the steps of: (1) compiling an interface document and storing the interface document in a database form; (2) checking whether the interface information in the interface document conforms to RESTful API specification; if yes, continuing the next step, and if not, ending; (3) converting interface information of a flat-layer linear structure conforming to RESTful API specification into a JSON tree; (4) forming a unique identifier of an interface by traversing the JSON tree and extracting interface information in the JSON tree; (5) extracting the contents of the input/output parameters of the interface and adding annotations to generate a models array; (6) analyzing the module name, request/return parameters and interface path of the interface, adding comments, and generating a services array; (7) traversing the models arrays, and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the project; (8) traversing the service arrays, and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project; (9) encapsulating all model files and service files into api. module files and exposing the files to the outside for calling HTTP request functions or parameter type definitions from the outside; (10) the api module file is output to a code output path configured by a user, a syntax analyzer is used for carrying out syntax check on an entry file of a project, a lexical analyzer is used for converting a code character sequence into a mark sequence, and finally an abstract syntax tree is generated; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
Further, the interface information in the JSON tree at least includes a module name and an interface path.
Further, the interface information extracted from the JSON tree is assembled into a large hump character string, and the large hump character string is used for uniquely identifying the interface.
Further, the HTTP request function includes a function name, a function entry argument name and type, a function exit argument name and type, an HTTP request mode, and an interface path.
Further, the function name is formed by splicing an interface request mode and an interface path.
Compared with the prior art, the invention has the beneficial effects that:
1. extracting all description information, field names, field types and the like from the interface document, generating a plurality of code files according to module classification through a depth-first recursive algorithm, having clear structure, generating each interface annotation, participation type and method function, finally packaging each generated code file into an api module, and exposing the api module to the outside. Whereas the conventional approaches are all generated in one file.
2. When generating the HTTP request function logic, the request header, formatted request parameters and the like are not internally assembled, but are put to process in function calling and in a unified interceptor. Compared with the traditional scheme that all logics are completely arranged in the request function body, the method and the device ensure that the request function logics are clear, simple and easy to use, and reduce the coupling degree of the request function logics.
3. In the process of generating the HTTP request code, the normalization of each interface is scanned and whether the RESTful API style is met is checked. If the interface in the document is not in accordance with the specification, a corresponding prompt is made, and the code generation process is interrupted. The traditional method does not have the step, and other personnel are required to manually check the normativity of the document every time the developer writes the document.
4. The original engineering code and the new code are related and quoted in an AST (Abstract Syntax Tree) analyzing mode, and Syntax checking is carried out on the original engineering code and the new code. Meanwhile, the development is guaranteed to be used after being opened from a practical project.
5. Development personnel do not need to write interface request codes, and the interface request codes are automatically generated according to the interface documents, so that the development time is saved. In the generated interface request code, the related comments such as interface name description, interface field meaning and the like are generated at the same time, and research personnel do not need to switch the document back and forth to search the interface or the meaning of a certain field. After the field type definition is filled in the interface document, the parameter type definition of the whole interface is directly generated, and research personnel can automatically prompt the structure and the content of the field when the field is returned by the interface. Meanwhile, by combining with a coding tool, if the parameters are not matched, the error reasons can be automatically prompted, and a developer is helped to quickly troubleshoot problems.
Drawings
FIG. 1 is a flow chart of one embodiment of the method of the present invention;
FIG. 2 is a flow chart of the generation of a model file in one embodiment of the method of the present invention;
FIG. 3 is a flow chart of the generation of services files in one embodiment of the method of the present invention;
FIG. 4 is a flow diagram of source code resolution in one embodiment of the system/method of the present invention;
module files fig. 5 is a data structure diagram of an api module file in an embodiment of the system/method of the present invention;
FIG. 6 is a schematic diagram of an interface documentation interface in accordance with an embodiment of the present system/method;
FIG. 7 is a schematic diagram of an interface for requesting parameters and returning data in accordance with an embodiment of the present system/method.
Detailed Description
The technical solution of the present invention is further explained with reference to the accompanying drawings and the specific embodiments.
As shown in fig. 1 to 5, an embodiment of the system for generating an HTTP request code based on an interface document according to the present invention includes an interface document forming and storing module for writing an interface document and storing it in a database form; the interface information normalization checking module is used for checking whether the interface information in the interface document conforms to RESTful API (application program interface) specifications; the JSON tree conversion module is used for converting the interface information of the flat layer linear structure conforming to the RESTful API specification into a JSON tree; the interface identification module is used for forming a unique identification of an interface by traversing the JSON tree to extract interface information in the JSON tree; the model array generating module is used for generating the model arrays by extracting the input/output parameter contents of the interface and adding comments; the servicees array generating module generates a servicees array by analyzing the module name, the request/return parameter and the interface path of the interface and adding comments; the model file generation module is used for traversing the models arrays and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the project; the service file generation module is used for traversing the service array and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project; the module file generating module is used for packaging all the module files and service files into the api module file and exposing the api module file to the outside for externally calling HTTP request functions or parameter type definitions; the HTTP request code generation module is used for outputting the api.module file to a code output path configured by a user, carrying out syntax check on an entry file of a project by using a syntax analyzer, converting a code character sequence into a mark sequence by using a lexical analyzer, and finally generating an abstract syntax tree; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
In one embodiment, the interface information in the JSON tree includes at least a module name and an interface path.
In one embodiment, the interface information extracted from the JSON tree is assembled into a large hump string that uniquely identifies the interface.
In one embodiment, the HTTP request function includes a function name, a function entry argument name and type, a function exit argument name and type, an HTTP request mode, and an interface path.
In one embodiment, the function name is formed by splicing an interface request mode and an interface path.
As shown in fig. 1-5, one embodiment of the method for generating an HTTP request code based on an interface document of the present invention includes the steps of: (1) compiling an interface document and storing the interface document in a database form; (2) checking whether the interface information in the interface document conforms to RESTful API specification; if yes, continuing the next step, and if not, ending; (3) converting interface information of a flat-layer linear structure conforming to RESTful API specification into a JSON tree; (4) forming a unique identifier of an interface by traversing the JSON tree and extracting interface information in the JSON tree; (5) extracting the contents of the input/output parameters of the interface and adding annotations to generate a models array; (6) analyzing the module name, request/return parameters and interface path of the interface, adding comments, and generating a services array; (7) traversing the models arrays, and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the project; (8) traversing the service arrays, and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project; (9) encapsulating all model files and service files into api. module files and exposing the files to the outside for calling HTTP request functions or parameter type definitions from the outside; (10) the api module file is output to a code output path configured by a user, a syntax analyzer is used for carrying out syntax check on an entry file of a project, a lexical analyzer is used for converting a code character sequence into a mark sequence, and finally an abstract syntax tree is generated; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
In one embodiment, the interface information in the JSON tree includes at least a module name and an interface path.
In one embodiment, the interface information extracted from the JSON tree is assembled into a large hump string that uniquely identifies the interface.
In one embodiment, the HTTP request function includes a function name, a function entry argument name and type, a function exit argument name and type, an HTTP request mode, and an interface path.
In one embodiment, the function name is formed by splicing an interface request mode and an interface path.
For the convenience of understanding the invention, the following description is presented in terms of some examples of application:
step 1, writing an interface document through a visualization system (such as yapi) and saving the interface document to a database.
And 2, traversing the interface document data from the database table in the step one, extracting interface information, and simultaneously checking whether the normalization written by the interface accords with the RESTful API style or not in the extraction process. If the interface document has a problem which is not in accordance with the specification, the interface name and the specification suggestion are prompted, and the process is terminated. If the rule is satisfied, the flat layer linear structure is converted into a tree structure, and finally a JSON (JavaScript Object Notation) tree is formed.
And 3, extracting the module name and the interface path in the JSON tree, cutting by using underlines, colons and slashes as marks, and assembling into a large hump character string for uniquely identifying the interface. (e.g.,/api/user/comment _ list/: id assembled into ApiUserComplementListId) model-related fields are used to generate the type name. If the call is a call, adding Res identification in front of the type name; and if the type name is the entry, adding a Params mark at the tail part of the type name. The interface parameter type searching method is convenient for developers to quickly judge the type and search when the interface parameter type is obtained.
And 4, step 4: and (4) acquiring an interface request mode, splicing the interface request mode with the return structure in the step (3) and generating an interface request function name. (show: by this way, function name can avoid most of the repeated problem of function name, meanwhile, through the code editor, can realize the function of fuzzy search, on the premise of knowing the interface path, can write out the function method fast. for example, GET requests interface/api/user/list, the corresponding function name is getAPIUserList, in the course of inputting function name, the coding tool will prompt automatically to complement the function name).
And 5: interface in-going type names (result of step 3 + Params) and out-going type names (Res + result of step 3) are generated. (Note: addition of Res and Params identifiers, distinguishing the names of access participants: for example: ApiUserComplementListIdparams, Exit: ResApiUserComplementListId)
And 6, extracting a request parameter object and a return parameter object of the interface in the JSON tree, and assembling the request parameter object and the return parameter object with the return result in the step 5 in a key-value mode to generate the models object. (Note: ApiUserComponentListIdParams: { parameter object xxx }).
And 7: extracting the contents of the interface and parameter field types in the JSON tree, and adding comments.
And 8: and (5) repeating the steps 3 to 7 until all model parameters are generated. All model parameters are stored in the models array in the form of an object array (stating: the object array is a structure, i.e., the stored elements in the array are objects, e.g., [ { name:1}, { name:2} ]). (models generating flow chart as shown in FIG. 2)
And step 9: and analyzing the module name of the interface in the JSON to generate a service class name. And adds a comment information field.
Step 10: and analyzing fields such as interface request/return parameters, request modes, interface paths, entry positions and the like in the module to which the step 9 belongs, and storing the fields in a service array object (which indicates that an object array is a structure, namely elements stored in the array are objects, such as [ { name:1}, { name:2} ]).
Step 11: and (5) repeating the steps 9 to 10 until the service information of all the modules is generated, and storing the result into the service array. (services production flow chart as shown in FIG. 3)
Step 12: and traversing the results of the step 8 and the step 11, and replacing variables in the model and service template file with result values of each traversal by using a template rendering engine handlebars. The model file stores a certain module (it is stated that a project may have a plurality of modules such as users and authorities, and a module corresponds to a plurality of interfaces, so that a module corresponds to a service file, all interface request functions under the module are under the file, and all parameter type definitions under the module are under the model), and the service file stores all HTTP request functions under a certain module.
Module file is generated (the data structure is shown in fig. 5), all the module and service files are introduced, the module file is exposed to the outside, and the module is referred when the function or type definition is required to be called from the outside.
And 14, outputting all the code files of the step 12 and the step 13 to a specified position according to a code output path configured by a user.
And 15, using a parser (parser) to perform Syntax check on the entry file in the project engineering, using a lexical parser (lexical analyzer) to convert the code character sequence into a marker (token) sequence, and finally generating an Abstract Syntax Tree (AST).
Step 16, the abstract syntax tree of step 15 is recursively parsed, creating an AST node named ImportDeclaration, which represents the reference statement of api. The node is inserted into the last import declaration node of the abstract syntax tree, and the insertion to the tail ensures that the reference sequence of the original entry file is not destroyed.
And step 17: and (4) performing decompiling on the new abstract syntax tree returned in the step (16), generating an HTTP request code, and writing the HTTP request code into an entry file (a source code analysis flow chart is shown in FIG. 4).
Parser (Parser): parsers (parsers), which are typically found as components of compilers or interpreters, perform syntax checking and construct data structures (typically hierarchical data structures such as parse trees, abstract syntax trees, etc.) consisting of input words. A parser typically uses a separate lexical parser to separate individual "words" from the input character stream and uses the word stream as its input.
Lexical analyzer (Lexical analyzer): lexical analysis (English) is a process in computer science that converts character sequences into token sequences. The program or function that performs lexical analysis is called a lexical analyzer (lexical analyzer, referred to as a lexer for short) or a scanner (scanner). The lexical analyzer typically exists in the form of a function for invocation by the parser.
Marker (Token): the tag here is a string, which is the smallest unit that constitutes the source code. The process of generating tokens from the input character stream is called tokenization (tokenization), in which the lexical analyzer also classifies tokens. The lexical analyzer is generally not concerned with the relationships between tokens (which fall within the scope of parsing), for example: the lexical analyzer is able to identify the brackets as tokens, but does not guarantee whether the brackets match.
Abstract Syntax Tree (AST): in computer science, an Abstract Syntax Tree (AST), or simply Syntax Tree (Syntax Tree), is an Abstract representation of the Syntax structure of source code. It represents the syntactic structure of the programming language in the form of a tree, each node on the tree representing a structure in the source code. The syntax is said to be "abstract" in that the syntax does not represent every detail that appears in the true syntax. For example, nesting brackets are implicit in the structure of the tree and are not present in the form of nodes; whereas a conditional jump statement like the if-condition-then may be represented using a node with three branches. In contrast to abstract syntax trees, concrete syntax trees (often called parse trees). Generally, in the translation and compilation process of source code, a parser creates a parse tree and then an AST is generated from the parse tree. Once the AST is created, some information is added during subsequent processing, such as the semantic analysis stage.
The following takes the "user module" interface document for a project as an example:
the first step is as follows: an interface document is composed as shown in fig. 6 to 7.
The second step is that: and (3) globally installing a cli tool by a user, executing a general api command under the root directory of the specified project engineering, and inputting an online interface document address and a code generation path to generate the HTTP request code.
Interface document JSON tree:
{ "info" { "title": test1"," version ": last" }, "basePath": "/", "tags" [ { "name": user "," description ": user" }, "user" - "," files "-", "users" { "id" { "delete" { "tags" - "," users "-", "deletion" - "," users "-", "user" - "," deletion "-", "description" - "," messages "-", "parameter" - "," user "-", "in" - "," partition "-", "text" - "," user "-" "text" - "," text "-" { "text" - "," { "text" - "," "" "," text "-", "text" - ", "msg" { "type": string "}," data "{" type ": null" }, "" required "}," [ "code", "msg", "data" } } }, "{" tags "[", "user" ], "metadata" [ "," metadata "]," metadata "[", "user" "" edit user "," description "", "" requirements "" "" "" "" "" "" "" "" "[" application/j "]," parameters "-", "{" name "-" "user _ id," "in" "," "path", "description" "," "" "", "" required "", "" text "", "{" character "", "{" parameter "", "" "" "," "box" "," "" "{" map "{" parameter "", "{" text "", "" text "", "" text "", "" "" "" "" "" "", "" text "", "" "," "" text "", "" "," "text" "," "" text "" ", "data" { "$ ref": "#/definitions/user/ResPutUserUser _ id" } }, "required" - [ "code", "msg", "data" } } } }, "/user" { "post" - { "tags" - "," "newly added user", "description" - "," "contract" - "" data "-", "" application/json "-" ], "parameters" - "," { "name" - "," "in" - "" body "," schema "-", "" "" "" "" "" #/definitions/user/PostPostParams "-" } "-", "" responses "-" } "-" { "200" - { "description" - { "storage" - "," { "filter" - "," } "-", "" filter "-", "-", "-", "" filter "-", "" filter "-", "-", "" filter "-" "filter" - "," - "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "" parameter "-", "required" [ "code", "msg", "data" ] } } }, "/user/] id" { "get" [ "] {" tags "[" user "]," summary "]," query user "", "#" "" "", "" messages "[" text/plane "]," parameters "[ {" name "]" "" id "," in "", "" path "," description "" "" "", "" "" "" required "", "" sound "" "type" ], "responses" "," "200" { "description" "" sub "", "" strategy operation "," schema "" "," "" { "schema" "," { "text" "," "" "" "" "," "" "" "" "" "" "" "{" text "", "" "" "" "" "" "" "" "" "" "" "" "" "," { "text" "," "" "" "" "" "" "" "" "", "" "" { "text" "," "" "" "," "" "" "" "" "" { "text" "" "," "" "" "" "" "," "" "" "" "" "" "" "", "" "" "" "" "" "" "," "", "" "" "" "" "", "" "" "", "" "" "," "" "" "" "" "" "" "" "" "" "" "" "," "" "" "," { "text" "," "", "" "", "" "" "," "", "" "" "" "", "" "" "" "" "" "" "" "" "" "" "" "", "" "" "" "" "" "" "" "" "," "" "" "," "," "" "" "" "," "" "," ", "msg", "data" ] } } } }, { "users": { "user _ id puttables": { "type": "object": "title", "properties": { "name" { "type": { "drawing": "description" }, "user name" }, { "desc" { "type": ": shape": "user description" }, { "address" { "object" { "type" }, { "object" }, ")," - { "user" { "object": shape "}," { "object": shape ": texture" "," { "user" { "property": texture "{" user ": texture" { "object": texture "),", "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": id ": string" }, "id" }, "{" shape "}," required "}," name "-," name }, "type" }, "id" }, "name }," type "}," id "{" shape "}," number "}," required "}," life "", "name" }, "name }, and" address "}
Two files of the core are shown below, with models in the catalog representing all model definitions in the interface document. All HTTP request functions in the interface document are contained under the service directory. The files under the directory are distinguished according to the names of the interface modules. For example, the generation structure of the user module is as follows:
api/models/user.ts
/*tslint:disable*/
export interface UserUser_idPutParams{
/**
home address
*/
address:string;
/**
User description
*/
desc:string;
/**
Name of user
*/
name:string;
}
export interface ResPutUserUser_id{
id:string;
}
export interface UserPostParams{
address:string;
desc:string;
name:string;
}
export interface ResPostUser{
id:string;
}
export interface ResGetUserId{
id:number;
name:string;
}
api/service/user.ts
/*tslint:disable*/
import{Injectable}from'@angular/core';
import{HttpClient}from'@angular/common/http';
import{Observable}from'rxjs';
import{ICommonResponse}from'../strict-http-response';
import{ApiBaseService}from'../base-service';
import{ResPutUserUser_id,UserUser_idPutParams,ResPostUser,UserPostParams,ResGetUserId}from'../models/user';
/**
*user description
*/
@Injectable({
providedIn:'root',
})
export class UserService extends ApiBaseService{
constructor(protected http:HttpClient){
super(http);
}
/**
Deleting user
*@param user_id
*@return successful operation
*/
deleteUserUserId(user_id:string):Observable<ICommonResponse<null>>{
return this.http.delete<ICommonResponse<null>>(`user/${user_id}`)
}
/**
Editing user
*@param params The`UserService.PutUserUserIdParams`containing the following parameters:
*
*-`user_id`:
*
*-`params`:
*
*@return successful operation
*/
putUserUserId(params:UserService.PutUserUserIdParams):Observable<ICommonResponse<ResPutUserUser_id>>{
return this.http.put<ICommonResponse<ResPutUserUser_id>>(`user/${params.user_id}`,params.params)
}
/**
New user
*@param params undefined
*@return successful operation
*/
postUser(params?:UserPostParams):Observable<ICommonResponse<ResPostUser>>{
return this.http.post<ICommonResponse<ResPostUser>>(`user`,params)
}
/**
Query users
*@param id
*@return successful operation
*/
getUserId(id:string):Observable<ICommonResponse<ResGetUserId>>{
return this.http.get<ICommonResponse<ResGetUserId>>(`user/${id}`)
}
}
export module UserService{
/**
*Parameters for putUserUserId
*/
export interface PutUserUserIdParams{
user_id:string;
params?:UserUser_idPutParams;
}
}
Compared with the prior art, the invention has the beneficial effects that:
1. extracting all description information, field names, field types and the like from the interface document, generating a plurality of code files according to module classification through a depth-first recursive algorithm, having clear structure, generating each interface annotation, participation type and method function, finally packaging each generated code file into an api module, and exposing the api module to the outside. Whereas the conventional approaches are all generated in one file.
2. When generating the HTTP request function logic, the request header, formatted request parameters and the like are not internally assembled, but are put to process in function calling and in a unified interceptor. Compared with the traditional scheme that all logics are completely arranged in the request function body, the method and the device ensure that the request function logics are clear, simple and easy to use, and reduce the coupling degree of the request function logics.
3. In the process of generating the HTTP request code, the normalization of each interface is scanned and whether the RESTful API style is met is checked. If the interface in the document is not in accordance with the specification, a corresponding prompt is made, and the code generation process is interrupted. The traditional method does not have the step, and other personnel are required to manually check the normativity of the document every time the developer writes the document.
4. The original engineering code and the new code are related and quoted in an AST (Abstract Syntax Tree) analyzing mode, and Syntax checking is carried out on the original engineering code and the new code. Meanwhile, the development is guaranteed to be used after being opened from a practical project.
5. Development personnel do not need to write interface request codes, and the interface request codes are automatically generated according to the interface documents, so that the development time is saved. In the generated interface request code, the related comments such as interface name description, interface field meaning and the like are generated at the same time, and research personnel do not need to switch the document back and forth to search the interface or the meaning of a certain field. After the field type definition is filled in the interface document, the parameter type definition of the whole interface is directly generated, and research personnel can automatically prompt the structure and the content of the field when the field is returned by the interface. Meanwhile, by combining with a coding tool, if the parameters are not matched, the error reasons can be automatically prompted, and a developer is helped to quickly troubleshoot problems.
The present 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 flow and/or block of the flow diagrams and/or block diagrams, and combinations of flows and/or blocks in the flow diagrams and/or block diagrams, can be implemented by computer program instructions. These computer program instructions may be provided to a processor of a general purpose computer, special purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, create means for implementing the functions specified in the flowchart flow or flows and/or block diagram block or blocks.
These computer program instructions may also be stored in a computer-readable memory that can direct a computer or other programmable data processing apparatus to function in a particular manner, such that the instructions stored in the computer-readable memory produce an article of manufacture including instruction means which implement the function specified in the flowchart flow or flows and/or block diagram block or blocks.
These computer program instructions may also be loaded onto a computer or other programmable data processing apparatus to cause a series of operational steps to be performed on the computer or other programmable apparatus to produce a computer implemented process such that the instructions which execute on the computer or other programmable apparatus provide steps for implementing the functions specified in the flowchart flow or flows and/or block diagram block or blocks.
Finally, it should be noted that: the above embodiments are only for illustrating the technical solutions of the present invention and not for limiting the same, and although the present invention is described in detail with reference to the above embodiments, those of ordinary skill in the art should understand that: modifications and equivalents may be made to the embodiments of the invention without departing from the spirit and scope of the invention, which is to be covered by the claims.

Claims (10)

1. A system for generating HTTP request code based on an interface document, comprising:
the interface document forming and storing module is used for compiling the interface document and storing the interface document in a database form;
the interface information normalization checking module is used for checking whether the interface information in the interface document conforms to RESTful API (application program interface) specifications;
the JSON tree conversion module is used for converting the interface information of the flat layer linear structure conforming to the RESTful API specification into a JSON tree;
the interface identification module is used for forming a unique identification of an interface by traversing the JSON tree to extract interface information in the JSON tree;
the model array generating module is used for generating the model arrays by extracting the input/output parameter contents of the interfaces and adding comments;
the services array generation module generates a services array by analyzing the module name, the request/return parameters and the interface path of the interface and adding comments;
the model file generation module is used for traversing the models arrays and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the project;
the service file generation module is used for traversing the service array and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project;
the module file generating module is used for packaging all the module files and service files into the api module file and exposing the api module file to the outside for externally calling HTTP request functions or parameter type definitions;
the HTTP request code generation module is used for outputting the api.module file to a code output path configured by a user, carrying out syntax check on an entry file of a project by using a syntax analyzer, converting a code character sequence into a mark sequence by using a lexical analyzer, and finally generating an abstract syntax tree; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
2. The system for generating an HTTP request code based on an interface document of claim 1, wherein the interface information in the JSON tree includes at least a module name and an interface path.
3. The system for generating HTTP request code based on an interface document of claim 2, wherein the interface information extracted from the JSON tree is assembled into a large hump string, the large hump string uniquely identifying the interface.
4. The system for generating an HTTP request code based on an interface document of claim 1, wherein the HTTP request function includes a function name, a function-in argument name and type, a function-out argument name and type, an HTTP request manner, and an interface path.
5. The system for generating an HTTP request code based on an interface document of claim 4, wherein the function name is formed by splicing an interface request mode and an interface path.
6. A method of generating an HTTP request code based on an interface document, comprising the steps of:
(1) compiling an interface document and storing the interface document in a database form;
(2) checking whether the interface information in the interface document conforms to RESTful API specification; if yes, continuing the next step, if no, ending;
(3) converting interface information of a flat-layer linear structure conforming to RESTful API specification into a JSON tree;
(4) forming a unique identifier of an interface by traversing the JSON tree and extracting interface information in the JSON tree;
(5) extracting the contents of the input/output parameters of the interface and adding annotations to generate a models array;
(6) analyzing the module name, request/return parameters and interface path of the interface, adding comments, and generating a services array;
(7) traversing the models arrays, and generating at least one model file by using a template rendering engine handlebars, wherein one model file stores the parameter type content of one module in the item;
(8) traversing the service arrays, and generating at least one service file by using a template rendering engine handlebars, wherein one service file stores the HTTP request function of one module in the project;
(9) encapsulating all model files and service files into api. module files and exposing the files to the outside for calling HTTP request functions or parameter type definitions from the outside;
(10) the api module file is output to a code output path configured by a user, a syntax analyzer is used for carrying out syntax check on an entry file of a project, a lexical analyzer is used for converting a code character sequence into a mark sequence, and finally an abstract syntax tree is generated; recursively analyzing the abstract syntax tree, and creating an AST node named ImportDeclaration, wherein the AST node represents a reference statement of api. And inserting the node into the last import declaration node of the abstract syntax tree, performing decompiling on the returned new abstract syntax tree, generating an HTTP request code, and writing the HTTP request code into an entry file of the project.
7. The method for generating an HTTP request code based on an interface document of claim 6, wherein the interface information in the JSON tree includes at least a module name and an interface path.
8. The method for generating an HTTP request code based on an interface document as recited in claim 7, wherein the interface information extracted from the JSON tree is assembled into a large hump character string, and the large hump character string is used to uniquely identify the interface.
9. The method of generating an HTTP request code based on an interface document of claim 6, wherein the HTTP request function includes a function name, a function-in argument name and type, a function-out argument name and type, an HTTP request manner, and an interface path.
10. The method for generating an HTTP request code based on an interface document as recited in claim 9, wherein the function name is formed by splicing an interface request manner and an interface path.
CN202210301824.7A 2022-03-25 2022-03-25 System and method for generating HTTP request code based on interface document Pending CN114816356A (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN202210301824.7A CN114816356A (en) 2022-03-25 2022-03-25 System and method for generating HTTP request code based on interface document

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
CN202210301824.7A CN114816356A (en) 2022-03-25 2022-03-25 System and method for generating HTTP request code based on interface document

Publications (1)

Publication Number Publication Date
CN114816356A true CN114816356A (en) 2022-07-29

Family

ID=82531063

Family Applications (1)

Application Number Title Priority Date Filing Date
CN202210301824.7A Pending CN114816356A (en) 2022-03-25 2022-03-25 System and method for generating HTTP request code based on interface document

Country Status (1)

Country Link
CN (1) CN114816356A (en)

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN116501303A (en) * 2023-06-25 2023-07-28 北京长亭科技有限公司 Automatic API code generation method and device

Cited By (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN116501303A (en) * 2023-06-25 2023-07-28 北京长亭科技有限公司 Automatic API code generation method and device
CN116501303B (en) * 2023-06-25 2023-11-14 北京长亭科技有限公司 Automatic API code generation method and device

Similar Documents

Publication Publication Date Title
US10698682B1 (en) Computerized software development environment with a software database containing atomic expressions
Nentwich et al. Flexible consistency checking
JP4619698B2 (en) Code segment creation method and system
US9965259B2 (en) System for translating diverse programming languages
Wagner et al. Incremental analysis of real programming languages
US20130152061A1 (en) Full fidelity parse tree for programming language processing
Schiewe et al. Advancing static code analysis with language-agnostic component identification
Angelov et al. PGF: A portable run-time format for type-theoretical grammars
CN111651165A (en) Integration method of programming language, programming software system and electronic device
Zaytsev Grammar Zoo: A corpus of experimental grammarware
Li et al. A User-extensible Refactoring Tool for Erlang Programs
Irwin et al. Object oriented metrics: Precision tools and configurable visualisations
CN114816356A (en) System and method for generating HTTP request code based on interface document
Fritzson et al. Metamodelica–a symbolic-numeric modelica language and comparison to julia
Dalibor et al. Mind the gap: lessons learned from translating grammars between MontiCore and Xtext
CN107577476A (en) A kind of Android system source code difference analysis method, server and medium based on Module Division
CN111831288A (en) Method and system for automatically generating Thrift IDL data structure and automatic transfer function
Hackman et al. mel-model extractor language for extracting facts from models
Henriksson A lightweight framework for universal fragment composition: with an application in the semantic web
Collard Meta-differencing: An infrastructure for source code difference analysis
Kosanović et al. Applang–A DSL for specification of mobile applications for android platform based on textX
Duffy The design & implementation of an abstract semantic graph for statement-level dynamic analysis of C++ applications
Szőke Automating the refactoring process
Kara Design and implementation of the modelicaml code generator using acceleo 3. x
Grigorev et al. String-embedded language support in integrated development environment

Legal Events

Date Code Title Description
PB01 Publication
PB01 Publication
SE01 Entry into force of request for substantive examination
SE01 Entry into force of request for substantive examination