Code generation method and system of server based on OpenAPI (Open Application Program Interface)
Through the server-side code generation method based on OpenAPI, combined with the organization's customized templates and OpenAPI documents, the problem of lack of flexibility and customization of existing tools' code generation is solved, and efficient and accurate code generation is achieved to meet the business needs of each organization.
Patent Information
- Application Number
- CN202510269362.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-07
- Publication Date
- 2025-06-13
AI Technical Summary
The code framework output by existing server-side code generation tools lacks flexibility and customization, and is difficult to adapt to the actual business scenarios and technical environments of each organization, resulting in the need of large-scale modifications, increasing workload and possible introduction of errors.
Using the server-side code generation method based on OpenAPI, by analyzing OpenAPI documents, combining the organization's customized server-side engineering templates, it automatically matches and fills variables to generate server-side code that meets specific business needs.
Improves the efficiency and accuracy of code generation, ensures that the generated code is highly consistent with the organization's business needs and technical specifications, reduces development cycles and maintenance costs, and improves the adaptability and flexibility of the code.
Smart Images

Figure CN120144102A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of software development, and in particular to a server-side code generation tool, and in particular to an OpenAPI-based server-side code generation method and system. Background Art
[0002] In modern software development practice, the design and implementation of the server-side code framework, as the core architecture supporting business logic and data processing, often need to closely match the specific needs and internal technology ecosystem of the organization. This feature is particularly prominent in organizations of a certain size, because these organizations usually have complex business logic, unique business processes, and internal tool sets developed for specific tasks. These factors work together to make the server-side code framework not only meet general technical requirements, but also deeply integrate the personalized needs of the organization, thus forming a set of distinctive technical systems.
[0003] However, most of the server-side code generation tools on the market tend to provide a standardized solution, aiming to quickly generate server-side infrastructure code through automated means. Although this "one-click generation" model greatly improves the efficiency of code production and reduces initial development costs, the output code framework often lacks sufficient flexibility and customization, making it difficult to directly adapt to the actual business scenarios and technical environments of various organizations:
[0004] (1) Adaptability issues: The code frameworks generated by existing server-side code generation tools often fail to fully consider the organization's specific business logic, technology stack, and internal tool integration requirements. Therefore, when these generated codes are directly applied within the organization, they usually need to undergo substantial modifications and adjustments to ensure that they are compatible with the existing technology system and business requirements. This process not only increases unnecessary workload, but may also introduce potential errors and instability factors, thereby reducing development efficiency and code quality.
[0005] (2) The contradiction between standardization and efficiency: The original intention of server-side code automatic generation technology is to achieve unified code style, simplified development process and reduced maintenance cost through standardization and automation. However, when the generated code framework cannot directly meet the needs of the organization and requires developers to make a lot of modifications, this original intention is challenged. Modifying the generated code framework not only violates the original intention of automatic code generation to reduce duplication of work and improve development efficiency, but may also destroy the original unified code specifications, resulting in a decrease in the consistency and maintainability of the code base.
[0006] To this end, the present invention proposes a code generation method and system for a server based on OpenAPI. Summary of the invention
[0007] In view of this, the present invention hopes to provide a method and system for generating server-side code based on OpenAPI to solve or alleviate the technical problems existing in the prior art, that is, how to further improve adaptability, solve the contradiction between standardization and efficiency, and provide at least one beneficial option for this; the technical solution of the present invention is implemented as follows:
[0008] In the first aspect, a method for generating server-side code based on OpenAPI:
[0009] (1) Overview:
[0010] The present invention aims to quickly generate server-side code that meets specific business requirements by means of a highly automated method, combining the OpenAPI specification with the server-side engineering template customized by the organization. It first parses the OpenAPI document, extracts key data such as interface definitions, parameter information, and return types, and then loads the engineering template preset by the organization. The template contains a complete file structure and preset filling variables. Next, the solution automatically matches the OpenAPI data with the filling variables in the template. For variables not covered by OpenAPI, user input is obtained through an interactive interface. Through cyclic checking and filling, it is ensured that all variables are correctly assigned. Finally, the server-side engineering files are generated using the filled template, and syntax and standardization checks are performed. This solution not only improves the efficiency and accuracy of code generation, but also ensures that the generated code highly conforms to the organization's business requirements and technical specifications, thereby accelerating the development cycle of server-side applications and reducing maintenance costs.
[0011] (2) Technical solution:
[0012] To achieve the above technical objectives, the solution of the present invention is as follows: After receiving the user input containing the path or URL pointing to a specific OpenAPI document, and the activation instruction for the selected or customized server-side engineering template identifier, the following operation steps are executed:
[0013] 2.1 Step S1, load the OpenAPI document:
[0014] Read and parse the OpenAPI document specified by the user, and extract the interface definitions, parameter information, and return types therein. According to the template identifier selected by the user, load the corresponding organization-customized server-side engineering template from the template library. It contains a complete file structure and preset filling variables.
[0015] 2.1.1 Step S100, read the OpenAPI document:
[0016] Read the OpenAPI document from the path or URL specified by the user. Use an OpenAPI parsing library or tool to perform syntax parsing on the document content. Traverse the parsed document structure to identify and extract the definitions of interfaces (GET or POST request methods). For each interface, further extract its parameter information (path parameters, query parameters, and request body) and return type (the structure definition of the successful response).
[0017] Store the extracted data in memory.
[0018] 2.1.2 Step S101, Load the organization-customized server project template:
[0019] Access the template library in the form of a file system directory, database, or remote service, and use the template identifier to find the corresponding template file in the template library. Load the content of the template file, including the file structure and preset filling variables; store the loaded template in memory.
[0020] 2.1.3 Step S102, Prepare the list of filling variables:
[0021] Scan the loaded template file to identify and record the positions and names of all filling variables; initialize a list of filling variables to store the information of these variables;
[0022] This list will be used to track which variables have been filled and which still require user input or default values in the subsequent steps.
[0023] 2.2 Step S2, Initialize the list of filling variables:
[0024] Scan the loaded template file to identify and record the positions and names of all filling variables to form a list of variables to be filled. For each variable in the list of filling variables, first try to extract the corresponding information from the OpenAPI document for filling.
[0025] If the variable value does not exist in the OpenAPI document, prompt the user to enter the missing value through an interactive interface; otherwise, proceed to the next step;
[0026] 2.2.1 Step S200, Scan the template file:
[0027] Use the file traversal function to check the content of the template file one by one. Apply regular expressions or specific tag recognition mechanisms to find all preset filling variables. These variables are usually represented in a special format or tag, such as {{variable_name}}. Record the position (i.e., which line or position in which file) and name of each variable.
[0028] 2.2.2 Step S201, Form the list of variables to be filled:
[0029] Create a data structure (list, dictionary, or object) to store information about the variables; add the name, location, and current status (such as "unfilled") of each variable to this data structure;
[0030] This list will serve as a reference and tracking tool for subsequent variable filling.
[0031] 2.2.3 Step S202, attempt to fill variables from the OpenAPI document:
[0032] Traverse the list of variables to be filled; for each variable, attempt to find matching data in the OpenAPI document based on its name and expected information type; if matching data is found, fill that data into the variable's location and update the variable's status to "filled"; if no matching data is found in the OpenAPI document, keep the variable's "unfilled" status.
[0033] 2.2.4 Step S203, handle unfilled variables:
[0034] Traverse the list of variables to be filled and find all variables with the status of "unfilled"; for each unfilled variable, display a prompt to the user via the graphical user interface (GUI) or command-line interface (CLI) indicating which variable's value needs to be input; receive the value input by the user and fill it into the corresponding variable's location; update the variable's status to "filled".
[0035] If the user chooses not to input the value of a certain variable (or inputs an invalid value), set a default value for that variable or mark it as a required item and prompt the user again according to the system configuration or default behavior.
[0036] 2.2.5 Step S204, proceed to the next step:
[0037] Traverse the list of variables to be filled and confirm that there are no unfilled variables left out. If all variables have been processed, record the current status and prepare to enter the next step (such as Step S3: loop check and filling). If there are still unprocessed variables, decide whether to continue prompting the user for input, use default values, or abort the process according to the system configuration or user selection.
[0038] 2.3 Step S3, loop check and filling:
[0039] Repeat Step S2 until all filled variables are correctly assigned values and there are no omissions or errors.
[0040] 2.4 Step S4, generate code file:
[0041] Use the filled template to generate the server - side project files containing all the necessary code and configurations. Use a custom semantic tool to check the generated code files to ensure that the syntax is correct and complies with the organization's coding standards.
[0042] 2.4.1 Step S400, Apply the filled template:
[0043] Traverse all the template files that have been loaded and filled with variables; for each template file, replace all variable placeholders with its filled content. Generate the corresponding server - side project files (including source code files, configuration files, or script files) according to the type and structure of the template file.
[0044] 2.4.2 Step S401, Organize the file structure:
[0045] Create the necessary directories and sub - directories according to the file structure definition in the template library or the file structure specified by the user; move the generated files to the corresponding directories to ensure that the file structure is clear and complies with the project's organization specifications.
[0046] 2.4.3 Step S402, Perform custom semantic checks:
[0047] Call a static code analysis tool, a code formatting tool, or a plugin in the form of an integrated development environment (IDE) as a custom semantic tool to traverse all the generated code files, perform syntax checks, type checks, naming convention checks, and code style checks; collect and organize the inspection results output by the tool, including errors, warnings, and suggestions.
[0048] 2.4.4 Step S403, Process the inspection results:
[0049] For issues that can be automatically corrected, such as code formatting issues or simple naming convention issues, let the system automatically correct them;
[0050] For issues that require user attention (i.e., issues other than automatically corrected ones), display detailed error messages and suggested correction solutions to the user through a graphical user interface (GUI) or a command - line interface (CLI).
[0051] 2.4.5 Step S404, Complete the code file generation:
[0052] Traverse all the generated code files. If all files meet the requirements, record the success status of the generation process and prepare to enter the next step (such as Step S5: Output the generation results).
[0053] If there are still files that fail the inspection, decide whether to regenerate, manually correct, or abort the process according to the system configuration or user selection.
[0054] 2.5 Step S5, Output the generation result:
[0055] Package or decompress the generated server-side project files to the directory specified by the user. Generate an execution report, including the list of generated code files, the filling variable assignment situation, and the execution time, and provide it to the user. According to the user configuration or system preset, additional operations can be performed, including compiling the generated code, deploying it to the test environment, and triggering automated tests.
[0056] (III) Mechanism for solving technical problems:
[0057] 3.1 Mechanism for improving adaptability and its principle:
[0058] Organization-customized server-side project templates: The present invention allows organizations to customize server-side project templates according to their own business requirements and technical specifications. These templates not only contain a complete file structure but also preset filling variables, providing a basis for subsequent automated generation.
[0059] Interactive variable filling: For filling variables not covered in the OpenAPI document, the present invention prompts the user to input the missing values through an interactive interface. This method ensures that the generated code can adapt to the specific needs of the organization and improves the flexibility of the present invention.
[0060] Through customized templates, organizations can incorporate their own business logic, coding specifications, and technical architectures into the templates, making the generated code more in line with actual needs.
[0061] The interactive variable filling mechanism enables users to intervene as necessary during the automated generation process, ensuring that the generated code not only complies with the OpenAPI specification but also meets the specific needs of the organization.
[0062] 3.2 Mechanism for solving the contradiction between standardization and efficiency and its principle:
[0063] OpenAPI specification parsing: The present invention automatically extracts key data such as interface definitions, parameter information, and return types by parsing the OpenAPI document, and these data will be used as the basis for filling template variables.
[0064] Automated generation and verification: Using the parsed data and customized templates, the present invention automatically generates server-side project files and performs syntax and standardization checks through customized semantic tools.
[0065] The OpenAPI specification provides a standardized way for API design. Parsing the OpenAPI document can ensure the consistency and standardization of the generated code at the interface level.
[0066] The automated generation mechanism reduces the manual coding workload and improves the efficiency of code generation. At the same time, by using a custom semantic tool for syntax and normativity checking, it can ensure that the quality of the generated code meets the organization's coding specifications and technical requirements.
[0067] In the second aspect, a code generation system for an OpenAPI-based server:
[0068] As Figure 2 shown, this system is used to implement the OpenAPI-based server code generation method described above, and it includes:
[0069] (1) Input processing module: responsible for receiving the user input containing the path or URL pointing to a specific OpenAPI document, as well as the activation instruction of the selected or custom server project template identifier.
[0070] Perform a preliminary verification on the input to ensure that the path or URL is valid and the template identifier exists.
[0071] (2) Document parsing and template loading module, including:
[0072] Document parsing sub-module: responsible for reading and parsing the OpenAPI document, and extracting key data such as interface definitions, parameter information, and return types.
[0073] Template loading sub-module: According to the template identifier selected by the user, load the corresponding organization-customized server project template from the template library. This template contains a complete file structure and preset filling variables.
[0074] (3) Variable processing module:
[0075] Variable identification sub-module: Scan the loaded template file, identify and record the positions and names of all filling variables, and form a list of variables to be filled.
[0076] Variable filling sub-module: For each variable, first try to extract the corresponding information from the OpenAPI document for filling; if the information does not exist, prompt the user to input the missing value through an interactive interface.
[0077] (4) Loop check and filling control module: responsible for controlling the loop process of variable filling, ensuring that all filling variables are correctly assigned values, and there are no omissions or errors. In each loop, call the variable processing module for variable checking and filling until all variables are correctly processed.
[0078] (5) Code generation and verification module: Use the filled template to generate a server project file containing all necessary codes and configurations. Call a custom semantic tool to perform syntax checking and normativity verification on the generated code file to ensure the code quality.
[0079] (6) Output and subsequent operation module: Package or decompress the generated server project files to the directory specified by the user. Generate an execution report, including the list of generated code files, the assignment of filled variables, and the execution time, and provide it to the user. According to the user configuration or system preset, perform additional operations, such as compiling the code, deploying it to the test environment, and triggering automated tests, etc.
[0080] (7) The execution process of the mutual cooperation among the above modules is as follows:
[0081] P1. After the input processing module receives the user input, it passes the parsing result to the document parsing and template loading module.
[0082] P2. The document parsing and template loading module parses the OpenAPI document and loads the template, and then passes the parsed data and template to the variable processing module.
[0083] P3. The variable processing module identifies and fills the variables, and passes the filling result to the loop checking and filling control module for verification.
[0084] P4. The loop checking and filling control module controls the loop process to ensure that all variables are correctly processed, and then passes the final filling result to the code generation and verification module.
[0085] P5. The code generation and verification module generates code and performs verification, and passes the generated code files and verification results to the output and subsequent operation module.
[0086] P6. The output and subsequent operation module is responsible for outputting the results to the user and performing additional operations according to the configuration.
[0087] Compared with the prior art, the beneficial effects of the present invention are:
[0088] First, significantly improve the development efficiency: The traditional manual coding method is time-consuming and error-prone, while the present invention greatly shortens the development cycle by automatically generating code. Developers only need to focus on the customization of the OpenAPI document and template, and can quickly generate server project files that meet the requirements, thus accelerating the project delivery speed.
[0089] Second, enhance the consistency and standardization of the code: The present invention generates code based on the OpenAPI specification and the organization's custom template, ensuring the consistency of the code in aspects such as interface definition, parameter processing, and return format. At the same time, through the custom semantic tool for syntax and standardization checking, the quality of the code is further improved, and the maintenance cost is reduced.
[0090] III. Improve the adaptability and flexibility of the code: Organizations can customize templates according to their own business needs and technical specifications, and supplement the variable values not covered in the OpenAPI documentation through an interactive interface, making the generated code more in line with the actual scenario. This mechanism not only ensures the standardization of the code but also endows it with sufficient flexibility to cope with changing business needs.
[0091] IV. Lower the technical threshold and labor costs: The present invention simplifies the complexity of server-side development, enabling even non-senior developers to quickly get started and generate high-quality code. This reduces the requirements for developers' skill levels, cuts down on labor costs, and also helps with the inheritance and sharing of team knowledge.
[0092] V. Facilitate continuous integration and continuous deployment (CI / CD): The generated code and configuration files can be directly integrated into the CI / CD process to achieve automated compilation, testing, deployment, and monitoring. This helps improve the efficiency and stability of software delivery and reduces the risk of errors caused by human operations. BRIEF DESCRIPTION OF THE DRAWINGS
[0093] To more clearly illustrate the technical solutions in the embodiments of the present application or in the prior art, the following will briefly introduce the accompanying drawings required for use in the description of the embodiments or the prior art. Obviously, the accompanying drawings in the following description are only some embodiments of the present application. For those of ordinary skill in the art, other accompanying drawings can be obtained based on these drawings without creative efforts.
[0094] Figure 1 It is a schematic flowchart of the method of the present invention;
[0095] Figure 2 It is a schematic diagram of the system composition of the present invention. DETAILED DESCRIPTION OF THE EMBODIMENTS
[0096] To make the above objects, features, and advantages of the present invention more obvious and understandable, the following will provide a detailed description of the specific embodiments of the present invention with reference to the accompanying drawings. Many specific details are set forth in the following description to fully understand the present invention. However, the present invention can be implemented in many other ways different from those described herein. Those skilled in the art can make similar improvements without departing from the connotation of the present invention. Therefore, the present invention is not limited by the specific embodiments disclosed below;
[0097] It should be noted that the embodiments in this specification are described in a progressive manner, with each embodiment focusing on the differences from other embodiments. The same or similar parts among the embodiments can be referred to each other. For the devices disclosed in the embodiments, since they correspond to the methods disclosed in the embodiments, the description is relatively simple, and the relevant parts can be referred to the description of the method part.
[0098] Explanation of related terms:
[0099] (1) OpenAPI: It is a specification for defining a standard RESTful API that is independent of specific programming languages. As documentation, it allows people to understand the function of a service without accessing the source code; it also allows a computer to precisely understand a service without other input.
[0100] (2) Code generation: The computer automatically generates code for calling the API described based on the OpenAPI specification. Server-side code generation is to automatically generate the code that can run on the server side to provide the corresponding API service.
[0101] (3) Interface definition: It describes the functions, access paths, request methods, etc. of the API, and is the contract for the interaction between the client and the server.
[0102] (4) Parameter information: It refers to the data that needs to be passed when calling the API interface, including parameter names, types, whether they are required, etc.
[0103] (5) Return type: The data format and content structure of the API interface response, such as JSON object, array, or specific data type.
[0104] (6) Organization-customized server-side project template: A pre-designed server-side project code framework and file organization method according to the organization's business requirements and technical specifications.
[0105] (7) File structure: It refers to the hierarchical relationship and organization method of files and directories in the project template.
[0106] (8) Variable value: In the template or code, the specific data or value used for replacement or filling.
[0107] (9) Preset filling variable: A placeholder predefined in the template that needs to be replaced by actual data in the subsequent process.
[0108] (10) Server-side project file: The specific server-side code and configuration files generated according to the template and filling variables, used to build and run the server-side application.
[0109] Example 1: As Figure 1 shown, this example will provide an application example of the code generation method for the server side based on OpenAPI in the development of the monthly and daily settlement system for online car-hailing as follows.
[0110] In the development of the online car-hailing monthly and daily settlement system, we need to quickly generate server-side engineering files that comply with business logic and coding specifications. By adopting a code generation solution based on OpenAPI, we can automate this process, improve development efficiency, and ensure code consistency and standardization.
[0111] In this embodiment, regarding step S1: Loading the OpenAPI document:
[0112] Reading the OpenAPI document (step S100): The user specifies the URL or path of the OpenAPI document, such as http: / / example.com / api-docs or / path / to / api-docs.yaml. Use an OpenAPI parsing library (such as SwaggerParser) to read and parse the document, and extract interface definitions, parameter information, and return types.
[0113] Exemplarily, extract the definition of the GET / rides interface, including its path parameters, query parameters (such as startDate and endDate), and return type (such as RideSummary structure).
[0114] Loading the organization's custom server-side engineering template (step S101): The user selects or specifies a template identifier, such as netflix-oss or custom-template-v1. Load the corresponding template files from the template library, and these files contain the complete file structure and preset filling variables, such as {{apiPath}}, {{modelName}}, etc.
[0115] Preparing the list of filling variables (step S102): Scan the loaded template files, identify and record the positions and names of all filling variables. Initialize a list of filling variables for subsequent tracking and filling of these variables.
[0116] In this embodiment, regarding step S2: Initializing the list of filling variables:
[0117] Scanning the template files (step S200): Traverse the template files and use regular expressions to identify all filling variables, such as {{variable_name}}. Record the position (file, line, column) and name of each variable.
[0118] Forming the list of variables to be filled (step S201): Create a data structure (such as a dictionary) to store the name, position, and status (unfilled / filled) of the variables. Try to fill the variables from the OpenAPI document (step S202): For each variable, try to find matching data in the OpenAPI document for filling.
[0119] Exemplarily, {{apiPath}} can be filled with / rides, and {{modelName}} can be filled with RideSummary.
[0120] This step improves adaptability because the system can automatically extract information from the OpenAPI document and fill it into the template, reducing the workload of manual input.
[0121] Process unfilled variables (step S203): For variables that do not exist in the OpenAPI document, prompt the user to enter the missing values through the GUI or CLI. If the user does not enter or enters invalid values, the system can set default values according to the configuration or mark them as required items and prompt again. This step resolves the contradiction between standardization and efficiency, ensuring both the standardization of the code (by prompting the user to enter missing values) and improving efficiency (through automatic filling and default value setting).
[0122] Proceed to the next step (step S204): Confirm that all variables have been processed without omission or error. Prepare to enter the next step (loop check and filling) to ensure that all variables are correctly assigned values.
[0123] In this embodiment, regarding step S3: Loop check and filling: Repeat step S2 until all filled variables are correctly assigned values and there are no omissions or errors. This step ensures that all variables are correctly processed, improving the accuracy and integrity of code generation.
[0124] In this embodiment, regarding step S3: Step S4: Generate code files:
[0125] Apply the filled template (step S400): Traverse all template files filled with variables, and use the filled content to replace the variable placeholders. Generate corresponding server-side project files, such as source code files, configuration files, and script files.
[0126] Organize the file structure (step S401): Create directories and subdirectories according to the file structure definition in the template library or the file structure specified by the user. Move the generated files to the corresponding directories to ensure that the file structure is clear and complies with the project specifications.
[0127] Execute custom semantic checks (step S402): Call custom semantic tools (such as ESLint, Pylint, etc.) to traverse the generated code files, perform syntax checks, type checks, naming convention checks, and code style checks. Collect and organize the check results, including errors, warnings, and suggestions.
[0128] Process the inspection results (Step S403): For issues that can be automatically corrected (such as code formatting issues), the system automatically makes corrections. For issues that require user attention, detailed error messages and proposed correction solutions are displayed through the GUI or CLI. This step further improves the code's standardization and quality, ensuring that the generated code complies with the organization's coding standards by automatically correcting and prompting users to correct issues.
[0129] Complete the generation of code files (Step S404): Traverse all the generated code files to confirm that they all meet the requirements. If all files meet the requirements, record the successful status of the generation process and prepare to enter the next step. If a file fails the inspection, decide whether to regenerate, manually correct, or abort the process according to the system configuration or user selection.
[0130] Step S5: Output the generation results: Package or extract the generated server-side project files to the directory specified by the user. Generate an execution report, including the list of generated code files, the filling of variable assignments, and the execution time, and provide it to the user. According to the user configuration or system preset, perform additional operations, such as compiling the generated code, deploying it to the test environment, and triggering automated tests.
[0131] In this embodiment, by adopting a code generation scheme based on OpenAPI and applying this scheme in the development of the monthly and daily settlement system for online car-hailing, code files are automatically generated, reducing the time for manual coding. Using a unified template and filling variables ensures the consistency of the generated code style and structure. Through the inspection and correction of custom semantic tools, it is ensured that the generated code complies with the organization's coding standards. The system can automatically extract information from the OpenAPI document and fill it into the template, adapting to different API definitions and requirements. By means of loop inspection and filling, custom semantic inspection, and user interaction prompts, the error rate during the code generation process is reduced.
[0132] Embodiment 2: On the basis of Embodiment 1, this embodiment will further provide its specific Python execution program as follows:
[0133]
[0134]
[0135]
[0136]
[0137] In the above program, the program first loads the OpenAPI document, which can be achieved through a URL (online) or a file path (local). Use yaml.safe_load to parse the OpenAPI document in YAML format. Load all template files from the specified template directory and store them in a dictionary with the file name as the key and the file content as the value. Scan the template files, use regular expressions to identify all filling variables (such as {{variable_name}}), and record their positions and status (not filled).
[0138] Traverse the variable list and try to find matching data in the OpenAPI document for filling. If found, update the value and status of the variable. For variables that do not exist in the OpenAPI document, prompt the user to enter the missing values and update the value and status of the variable.
[0139] Repeat the above steps until all variables are correctly assigned and there are no omissions or errors.
[0140] Use the Jinja2 template engine to apply the filled variables to the template to generate the corresponding server-side project files.
[0141] Create directories and subdirectories according to the file structure definition in the template library or the user-specified file structure, and move the generated files to the corresponding directories. The custom semantic check part is not implemented in this example, but corresponding tools (such as Pylint) can be called after generating the code files to perform the check and handle according to the check results.
[0142] Package or decompress the generated server-side project files to the directory specified by the user and generate an execution report, including the list of generated code files, the assignment of filled variables, and the execution time.
[0143] All of the above embodiments only represent the implementation manners of the relevant actual applications of the present invention. The descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of the invention patent. It should be noted that for those of ordinary skill in the art, without departing from the concept of the present invention, several deformations and improvements can still be made, and these all belong to the protection scope of the present invention. Therefore, the protection scope of the invention patent shall be subject to the appended claims.
[0144] For those skilled in the art, it can be further realized that the units and algorithm steps of each example described in combination with the embodiments disclosed herein can be implemented by electronic hardware, computer software, or a combination of the two. To clearly illustrate the interchangeability of hardware and software, the composition and steps of each example have been generally described according to functions in the above description. Whether these functions are executed in a hardware or software manner depends on the specific application and design constraints of the technical solution. Skilled professionals can use different methods to implement the described functions for each specific application, but such implementation should not be considered to exceed the scope of the present invention.
[0145] At the same time, those skilled in the art can understand that all or part of the processes of implementing the methods of all the above embodiments can be completed by instructing relevant hardware through a computer program. The computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above methods. Among them, any reference to a memory, storage, database, or other medium provided in the present application and used in the embodiments can include non-volatile and / or volatile memories. Non-volatile memories can include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memories can include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in various forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), double data rate SDRAM (SSRSDRAM), enhanced SDRAM (ESDRAM), synchronous link (Synchlink) DRAM (SLDRAM), memory bus (Rambus) direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
Claims
1. A code generation method based on the server side of OpenAPI, characterized in that: After receiving the user input containing the path or URL pointing to a specific OpenAPI document and the activation instruction of the selected or customized server project template identifier, perform the following steps: S1, reads and parses the OpenAPI document specified by the user; according to the template identifier selected by the user, loads the corresponding organization-defined server-side project template from the template library; S2, scans the loaded template file, identifies and records the locations and names of all filled variables, and forms a list of variables to be filled; S3, repeat step S2 until all filled variables are correctly assigned; S4, using the filled template, generates a server-side project file containing all necessary code and configuration; S5, packages or decompresses the generated server-side project files to a directory specified by the user; generates an execution report, including a list of generated code files, variable assignments, and execution time, and provides it to the user.
2. The code generation method according to claim 1, characterized in that: In S1, the interface definition, parameter information and return type of the OpenAPI document need to be extracted; the organization's customized server-side project template needs to include the file structure and preset fill variables.
3. The code generation method according to claim 2, characterized in that: The execution process of S1 includes: S100, read the OpenAPI document from the path or URL specified by the user; use the OpenAPI parsing library or tool to perform syntax parsing on the document content; traverse the parsed document structure, identify and extract the definition of the interface; for each interface, further extract its parameter information and return type; S101, accessing a template library in the form of a file system directory, a database or a remote service, and using a template identifier to search for a corresponding template file in the template library; loading the content of the template file, including the file structure and preset fill variables; S102, scanning the loaded template file, identifying and recording the positions and names of all filled variables.
4. The code generation method according to claim 1, characterized in that: In S2, for each variable in the populated variable list, first try to extract the corresponding information from the OpenAPI document for filling; If the variable value does not exist in the OpenAPI document, the user is prompted to enter the missing value through the interactive interface; otherwise, proceed to the next step.
5. The code generation method according to claim 1, characterized in that: The execution method of S2 includes: S200, traverse the content in the template file; apply regular expressions or a specific tag recognition mechanism to find all preset fill variables; S201, creating a data structure for storing variable information; adding the name, position and current state of each variable to the data structure; S202, for each variable, try to find matching data in the OpenAPI document according to its name and expected information type; if matching data is found, fill the data into the position of the variable and update the state of the variable to "filled"; if matching data is not found in the OpenAPI document, keep the "unfilled" state of the variable; S203, traverse the list of variables to be filled, find all variables with a status of "unfilled"; for each unfilled variable, display a prompt to the user, indicating which variable value needs to be entered; receive the value entered by the user, and fill it into the position of the corresponding variable; update the status of the variable to "filled". S204: If all variables have been processed, the current status is recorded and the next step is prepared.
6. The code generation method according to claim 1, characterized in that: In the S4, it also includes using a custom semantic tool to check the generated code file.
7. The code generation method according to claim 6, characterized in that: The execution process of S4 also includes: S400, traverse all template files loaded and filled with variables; for each template file, replace all variable placeholders with its filled content; generate corresponding server-side project files according to the type and structure of the template file; S401, creating necessary directories and subdirectories according to the file structure definition in the template library or the file structure specified by the user; S402, calling a static code analysis tool, a code formatting tool, or a plug-in custom semantic tool in the form of an integrated development environment, traversing all generated code files, performing syntax checking, type checking, naming convention checking, and code style checking; collecting and organizing the inspection results output by the tool, including errors, warnings, and suggestions; S403, for problems that can be corrected automatically, such as code formatting problems or simple naming convention problems, the system automatically corrects them; for problems that require user attention, detailed error information and suggested correction solutions are displayed to the user; S404, traverse all generated code files, if all files meet the requirements, record the success status of the generation process and proceed to the next step.
8. The code generation method according to any one of claims 1 to 7, characterized in that: In the S5, it also includes executing the operations of additionally compiling the generated code, deploying it to the test environment, and triggering the automated test according to the user configuration or system preset.
9. A code generation system for implementing the code generation method according to any one of claims 1 to 8, characterized in that: include: Input processing module: responsible for receiving user input containing the path or URL pointing to a specific OpenAPI document; The document parsing and template loading module is responsible for reading and parsing the OpenAPI document, extracting key data such as interface definition, parameter information, and return type; According to the template identifier selected by the user, the corresponding organization-defined server-side project template is loaded from the template library; Variable processing module: scans the loaded template file, identifies and records the location and name of all filled variables, and forms a list of variables to be filled; for each variable, first try to extract the corresponding information from the OpenAPI document for filling; if the information does not exist, prompt the user to enter the missing value through the interactive interface; Cycle check and filling control module: responsible for controlling the cycle process of variable filling; Code generation and verification module: Use the filled template to generate server-side project files containing all necessary code and configuration; Output and subsequent operation module: package or decompress the generated server project files to the directory specified by the user.
10. The server-side code generation system according to claim 9, characterized in that: The execution process of the system is: P1. After receiving the user input, the input processing module passes the parsing result to the document parsing and template loading module; P2, the document parsing and template loading module parses the OpenAPI document and loads the template, and then passes the parsed data and template to the variable processing module; P3, the variable processing module identifies and fills the variables, and passes the filling results to the loop check and filling control module for verification; P4, cycle inspection and filling control module controls the cycle process; P5, the code generation and verification module generates code and verifies it, and passes the generated code file and verification results to the output and subsequent operation module; P6, output and subsequent operation module is responsible for outputting the results to the user.