The effect

background

When I was doing the front end, the back end classmates didn’t give me interface documents because they were old comrades

Helpless and painful as I was, I needed to sit next to him with a pen and listen to his dictation

Write down the REQUIRED API urls, parameters, etc

Now that you’re doing the back end yourself, you can’t run amok like this

How can you give other students what you eat?

At this point,apiDoc you deserve a steady output of quality interface documentation

Install apidoc

The official website is a global installation, I like to install into the project, so that in another environment, NPM install can download all the dependency packages

npm install apidoc --save-dev/-D
Copy the code

Write a comment

Register comments for the interface

/** * @api {post} /v1/auth/register User Register * @apiName UserRegister * @apiGroup userAuthentication * * @apiParam {String} username New user's username. * @apiParam {String} password New user's password. * * @apiSuccess {String} username The username of the register user. * @apiSuccess {string} message The registering success info. * * @apisuccessexample Success-Response: * HTTP/1.1 200 OK * {* "username": "username", * "message": "User registered successful" * } * * @apiError REGISTER_FAILURE The register failure. * * @apiErrorExample Error-response: * HTTP/1.1 500 Internal Server Error * {* "err": "REGISTER_FAILURE", * "message": "User register failure!" *} * /
Copy the code

Delete comments of the interface

/** * @api {delete} /v1/auth/user/ User delete * @apiName UserDelete * @apiGroup userAuthentication * * @apiParam {String} username User's username. * @apiParam {String} executor Executor of this operation. * * @apiSuccess {String} username The username of the deleted user. * @apiSuccess {string} message The message if deleting successful. * * @apisuccessexample Success-Response: * HTTP/1.1 200 OK * {* "username": "username", * "message": "Delete User Successful" * } * * @apiError NOT_LOGIN The register failure. * * @apiErrorExample Error-Response: * HTTP/1.1 401 Unauthorized * {* "err": "NOT_LOGIN", * "message": "User has not logon in!" *} * /
Copy the code

Write command

Write apidoc -I routers to the package.json command

The routers folder contains routing files

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint .",
    "apidoc": "apidoc -i routers/",
    "dev": "node --harmony index.js"
  },
Copy the code

{“message”:”Done.”,”level”:”info”

Execute the command

To retrieve the interface documentation, run NPM run apidoc

This will make the Doc folder appear in your project

Generating documentation

Thus, the doc folder contains all the material for that page

Open index. HTML

Hot interface documentation was born

Structural interpretation

A static document is nicely generated, but api_data.js and api_project.js actually control this method. But the actual data display is made up of two JSON files, api_data.json and api_project.json.

Json and API_project. json. Replace these two files generated by APidOC, and then replace js files to directly produce static documents.

Command line interface

View all commands

apidoc -h
Copy the code
options role
-f –file-filters A Regex filter for selecting files that should be analyzed (multiple -fs can be used). (Default: [])
-e, –exclude-filters A Regex filter for selecting files/directories that should not be parsed (many-e can be used). (Default: [])
-i, –input Enter the/source directory name. (Default: [])
-o, –output Output directory. (Default:./doc/)
-t, –template Use templates for output files. (Default: /usr/local/lib/node_modules/apidoc/template/)
-c, –config The directory path that contains the configuration file (apidoc.json). (Default value:./)
-p, –private Include private APIs in output.
-v, –verbose Detailed debugging output.
–debug Displays debug messages.
–color Turn off the log color.
–parse Only parses the file and returns data, not creates the file.
–parse-filters Optional user-defined filters. Format name = filename (default: [])
–parse-languages Optional user-defined language. Format name = filename (default: []
–parse-parsers Optional user-defined profiler. Format name = filename (default: [])
–parse-workers Optional user-defined staff. Format name = filename (default: [])
–silent Close all output.
–simulate Execute without writing to any file.
–markdown [markdown] Turn off the default tag parser or set the file to a custom parser. (Default: true)
–line-ending Turn off automatic line tail detection. Permissible value: LF, CR, CRLF.
–encoding Sets the encoding of the source code. UTF8 format. (Default: “UTf8”)
-h, –help Output Usage Information

ApiDoc parameters used (translation)

@api

@api {method} path [title]
Copy the code

The necessary! Without this indicator, the APidOC parser ignores the document block. The only exception is document blocks defined by @ApideFine, which do not require @API.

Usage: @api {get} /user/:id Users unique ID.

Name Description
method Request method name: DELETE, GET, POST, PUT, …
path Request Path.
title optional A short title. (used for navigation and article header)
/**
 * @api {get} /user/:id
 */
Copy the code

@apiName

@apiName name
Copy the code

Should always be used. Define the name of the method document block. The name will be used for the subnavigation in the generated output. Structure definitions do not require @apinName. Usage: @apinName getUser

Name Description
name The unique name of the method. You can define the same name and different@apiversion. Format:method+path(e.g.get+user), there is only one suggestion, which you can name according to your needs. Can also be used as a navigation title.
/**
 * @api {get} /user/:id
 * @apiName GetUser
 */
Copy the code

@apiGroup

@apiGroup name
Copy the code

Should always be used. Defines the group to which a method document block belongs. The group will be used for the main route in the generated output. Structure definitions do not require @apigroup. Usage: @apigroup user

Name Description
name The group name. Also use navigation headings.
/**
 * @api {get} /user/:id
 * @apiGroup User
 */
Copy the code

@apiParam

@apiParam [(group)] [{type}] [field=defaultValue] [description]
Copy the code

Describes the parameters passed to the API methods.

@apiparam (mygroup) number id Users unique ID.

Name Description
(group)optional All parameters will be grouped by this name. If there is no group, set the default parameters. You can use@apidefineSet the title and description.
{type}optional Parameter type, for example{Boolean}.{Number}.{String}.{Object}.{String[]}
{type{size}}optional Variable size information{string{.. 5}}A character string with a maximum value of 5.{string{2.. 5}}A string with a minimum of 2 and a maximum of 5.{number{100-999}}I numbers between 100 and 999.
{type=allowedValues}optional Information about the allowable values of variables.{string="small"}containssmallString,{string="small","huge"}containssmall/hugeString,{number = 1,2,3,99}A number with permissible values of 1,2,3, and 99,{string {.. 5}="small","huge"}A string of up to 5 characters containing only the word “small” or “mage”.
field Variable name.
[field] Fieldname with parentheses defines the variable as an optional variable.
=defaultValueoptional Parameter Default value.
descriptionoptional Field description.
/**
 * @api {get} /user/:id
 * @apiParam {Number} id Users unique ID.
 */

/**
 * @api {post} /user/
 * @apiParam {String} [firstname]  Optional Firstname of the User.
 * @apiParam {String} lastname     Mandatory Lastname.
 * @apiParam {String} country="DE" Mandatory with default value "DE".
 * @apiParam {Number} [age=18]     Optional Age with default 18.
 *
 * @apiParam (Login) {String} pass Only logged in users can post this.
 *                                 In generated documentation a separate
 *                                 "Login" Block will be generated.
 */
Copy the code

@apiSuccess

@apiSuccess [(group)] [{type}] field [description]
Copy the code

Returns the argument on success. Usage: @apisuccess {String} firstName firstname of the User.

Name Description
(group)optional All parameters will be grouped by this name.

If there is no group, the default setting succeeds 200. You can set the title and description using @apidefine. {type} optional | return types, such as {Boolean}, {Number}, {String}, {Object}, {String} [] field | returned identifier (returning success code). The description optional | fields.

/**
 * @api {get} /user/:id
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
Copy the code

Example with (group), more group-examples at @apiSuccessTitle:

/**
 * @api {get} /user/:id
 * @apiSuccess (200) {String} firstname Firstname of the User.
 * @apiSuccess (200) {String} lastname  Lastname of the User.
 */
Copy the code

Example with Object:

/**
 * @api {get} /user/:id
 * @apiSuccess {Boolean} active        Specify ifthe account is active. * @apiSuccess {Object} profile User profile information. * @apiSuccess {Number} profile.age Users  age. * @apiSuccess {String} profile.image Avatar-Image. */Copy the code

Example with Array:

/**
 * @api {get} /users
 * @apiSuccess {Object[]} profiles       List of user profiles.
 * @apiSuccess {Number}   profiles.age   Users age.
 * @apiSuccess {String}   profiles.image Avatar-Image.
 */
Copy the code

@apiSuccessExample

@apiSuccessExample [{type}] [title]
                   example
Copy the code

An example of a successful return message, output as preformatted code. @apisuccessexample {json} success-Response: {“content”: “This is an example content”}

Name Description
typeoptional The response format
titleoptional A short title for the example
example Detailed examples with support for multiple lines
/** * @api {get} /user/:id * @apisuccessexample {json} success-Response: * HTTP/1.1 200 OK * {*"firstname": "John",
 *       "lastname": "Doe"
 *     }
 */
Copy the code

@apiError

@apiError [(group)] [{type}] field [description]
Copy the code

Returns the argument on success. Usage: @apiError UserNotFound.

Name Description
(group)optional All parameters will be grouped by this name. If there is no group, the default error is set4xx. You can use@apidefineSet the title and description.
{type}optional Return type, such as{Boolean}.{Number}.{String}.{Object}.{String[]}
field Return identifier (return failure code).
description optional Field description.
/**
 * @api {get} /user/:id
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
Copy the code

@apiErrorExample

@apiErrorExample [{type}] [title]
                 example
Copy the code

An example of a failure return message, output as preformatted code. @apierRorexample {json} error-response: This is an example.

Name Description
typeoptional The response format
titleoptional A short title for the example
example Detailed examples with support for multiple lines
/** * @api {get} /user/:id * @apierrorexample {json} error-response: * HTTP/1.1 404 Not Found * {*"error": "UserNotFound"
 *     }
 */
Copy the code

reference

Apidoc website

Interface document artifact apidoc

Apidoc quickly generate online documents, APIDOC generate static file generation rules, principle analysis, practice

Finally, don’t forget to give this project a star, thank you for your support.

blog

A learning programming technology of the public number. Every day, I post high-quality posts, open source projects, utilities, interview tips, programming learning resources and more. The goal is to achieve personal technology and public growth together. Welcome to pay attention to, progress together, to the full stack of big man cultivation road