Using swagger to assist in developing fabric application Web APIs

Source: Internet
Author: User

In the previous several blogs, we have already set up the fabric environment, can also use go development chaincode, then we can test the correctness of Chaincode through the CLI after Chaincode development, after Chaincode development, The next step is to write about application.

Application is divided into 2 parts, part of the later business logic, that is, the Web API, is generally provided through the form of restful, the other part is the UI, of course, most of the cases are GUI, that is, the website front-end, Windows programs, apps and so on. About the front end, I because there is no artistic, made out of the interface is very ugly, so also weaknesses, rarely do front-end development, focus on the implementation of the background business logic.

A Brief introduction

In the development of Web API, the most famous tool in the industry is swagger, this is an artifact! I used the ABP framework when I was developing C #, and I used the swagger to see the swagger when I tried to use Go's Web development Framework Beego, and now I use node development, and I can't imagine using swagger. It can only be explained that the swagger cross-platform cross-language ability is too strong. Swagger can help us to document the API for easy testing.

There are 2 ways to develop swagger:

    1. Use the migrated Swagger library in the Web development framework, which is the code first, followed by the schema of the API documentation. For example, in the ABP framework, we just need to define the interfaces and annotations in Apicontroller, and the framework can help us build the swagger interface.
    2. Use the Swagger Yaml file to define the API interface, define it, and then use the Swagger codegen to generate the corresponding language code.

The first way to develop is to look at the support of the web framework you're using, and then we'll talk about the second development approach.

Two writing swagger YAML

The official has provided me with an example of a pet store, and provided a powerful grammar check and preview function, which is swagger Editor, which we can see directly by visiting http://editor.swagger.io/. If the access is particularly slow or inaccessible due to some mystical power, we can also download the image of Swagger editor to run locally.

Run the following command directly in the environment where Docker is installed:

Docker pull swaggerapi/swagger-:8080 swaggerapi/swagger-editor
然后就可以访问http://{Your_Server_IP}。

Whether it's an online editor or a locally deployed Docker, we finally see the interface:

The left window is the content of the Yaml file we are editing, and the right window is the effect of the preview API document.

About the Yaml file, in fact, the readability is very strong, most of them do not need to explain to know what the meaning, below I would like to highlight the following a few of the more important elements:

1. Host&basepath

host Specifies the address of our API server, which is the server that we deploy when we deploy the Web API. If we are developing locally and using custom ports, such as 8080, then we need to change to localhost:8080.

BasePath is the virtual directory of the specified API, such as we have a list of all users of the API is: Get/user, if we set the BasePath is "/api", then we have to access the path should be:

GET Http://localhost:8080/api/User

Of course, if we want to be more normative, such as the API version is also put in, then we can set BasePath to "/api/v1", so our access path is:

GET Http://localhost:8080/api/v1/User

This basepath parameter involves the generation of server-side API routing, and host involves the invocation address of each API test.

2. Tags

tags are used to partition a large number of APIs, say simple point is for a large number of APIs to better look, easier to find. We can annotate tags to make the API documentation easier to read.

Tags do not involve changes in the background, each specific API can specify which of the (or which tag), and then in the swagger display, the API will be included under the tag to belong to.

Note: The Yaml file format is strict with indentation, just like python, so if we are adding elements, we must be aware that indentation is correct. 】

For example, we create a new tag called the Bank, and then add a bit of this tag description, then we go to the/pet post, you can add tags to a line, write as a bank, and then you can see the right preview window updated, showing the bank of this tag-related API:

If there is no refresh, we can see the effect by clicking on the Edit->convert to Yaml menu above.

3. Paths

This is the most important configuration element. The main API configuration is in this link. The next level of explanation.

The first level is the URL, with/begins, and the parameters can be specified in the URL. For example, if we want to obtain the bank information of a bankid, then the URL is

/bank/{bankid}

The second level is the HTTP method, and the main methods we use in WEBAPI are: Query get, create post, modify put, and remove delete. Because we are querying the bank information for a bank ID, we enter the get at this level

The third level has multiple elements, namely:

tags that indicate which tag this API belongs to.

Summary, a simple description of the interface, a word can be.

Description, as the name implies, is an introduction to the interface, can be written in detail.

OperationID, this is the corresponding method name in the background, swagger route can be based on the URL and OperationID here to find the corresponding action method.

Consumes, is the client to the server when the type of support, generally we just need to preserve the JSON, you can delete the XML. If it is a get method, the element is not required.

Produces is what style data the server is returning to the client data, and we still keep the JSON.

Parameters is a specific parameter, where the settings are more complex, including specifying whether the parameter is in the URL or in the body, what type of parameter is passed in, if it must have the parameter, the description of the parameter, and so on. If the argument is an object, you need to add a reference to the object type, and the object is defined in the subsequent definitions node.

Responses is what HTTP code is returned by the server. Each status code indicates what it means.

Security is the way to specify the security check for this interface, and if it is not set, it is anonymous access. It refers to the definition in securitydefinitions.

X-swagger-router-controller, which is an extension element that specifies the controller name that corresponds to the background of the URL.

In conjunction with the above, we customize a yaml content that gets the bank object by ID as follows:

/bank/{BankID}: Get:tags:-Bank Summary: Get basic banking information based on bank ID Description: Detailed description Operationid:getbankbyid produces:-application/JSON parameters:-Name:bankidinch: Path Description: Primary key ID required for bank object:trueType:integer Format:int64 Responses:' $': Description: Find the Bank Schema: $ref:'#/definitions/bank'       ' -': Description: Invalid ID'404': Description:id The corresponding bank was not found
4. Securitydefinitions

This is a security-defined module, where we can define our WEBAPI security authentication methods, such as:

    • Basic Authentication
    • API Keys
    • Bearer Authentication
    • OAuth 2.0
    • OpenID Connect Discovery
    • Cookie Authentication

There are so many authentication methods, many of which I have not used, understand not deep, I mainly use bearer and OAuth 2.0, specific settings you can refer to the document:

https://swagger.io/docs/specification/authentication/

5. Definitions

Here is where we define which JSON objects we will be involved in the API. In other words, the JSON that we want to post in the API, or the JSON returned by the server, is defined here, and the above steps directly refer to the definition here.

For example we need to refer to the Bank object above, then we define here as follows:

Bank:    Object    Properties:     ID:       type:integer       format:int32     name:         String

If the object nested references other objects, you can also refer to the past by $ref, we can refer to the Pet object in the official example, we reference the category.

The above elements I simply explain, for a variety of in-depth usage, you can refer to the Official document: https://swagger.io/docs/

Three generation of background code

As long as we preview the code on the right without reporting any errors, then we can generate the code for the backend. This is because the Fabric SDK is node, so our web API is also developed using node. We click the Nodejs-server option under the Generate Server menu:

The system downloads a compressed package that is our web API node project after decompression. On the machine where node is installed, we use the following command to install the package on which the project depends:

Install --registry=https://registry.npm.taobao.org
When the installation is complete, run the following command:
NPM start
We can see the website address is: Http://localhost:8080/docs
Open the browser, visit this website, you can see the UI generated by swagger, and see our custom method to get the bank object.
Here, let's try passing in Parameter 1 and calling the API to see the result:
Here is a false result of swagger giving us a mock, and if we want to return the actual result, we need to find the Bankservice.js in the Controllers folder and see the following:
' Use strict '; Exports.getbankbyid=function(args, res, next) {/** * Get Bank basic information according to bank ID * Detailed description * * BankID Integer Bank object primary Key ID * returns BANK **/   varexamples = {}; examples[' Application/json '] = {   "Name": "Aeiou",   "id": 0 }; if(Object.keys (examples). length > 0) {Res.setheader (' Content-type ', ' Application/json '); Res.end (Json.stringify (Examples[object.keys (examples) [0] | | {},NULL, 2)); } Else{res.end (); } }
The part of the mock code is removed, and our real business logic is written in to complete our WEBAPI development work.
Iv. Summary

Swagger really is the Web API development of the artifact, too useful. There are also official Swaggerhub, which support the collaboration of many people in the preparation of YAML documents, but are charged. We can actually manage YAML files in the project through Git, because the file exists in the API folder of the WEBAPI project, so you can actually edit them together and then use git to merge the conflicts. In addition swagger also has the client, read some support various languages, various frameworks, all kinds of app development, is really too strong, because I do not develop the GUI, so not how contact, need you to study.

Using swagger to assist in developing fabric application Web APIs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.