API specification conventions let you write high quality APIs!

Keywords: JSON xml

abstract

API design principles:

  • Controlling the granularity and number of API s
  • Naming should follow the principle of simplicity, readability and uniformity.
  • Prioritize API design, then code

Say one more thing: In order to develop more efficiently and save the cost of writing documents, these popular projects, such as microservices and agile development, use Swagger to generate descriptions for API services.

URL Design [for Backend Development]

HTTP Specification

The verb currently has two HTTP methods for CRUD operations.

GET: Read
 POST: New (Create,Update,Delete)
PUT: Update
 PATCH: Update, usually a partial update
 DELETE: Delete (Delete)

Naming Specification

  • concise
concise Tedious
captcha get-captcha-image
info getUserInfo
cars getAllCars
  • readable
Readable Poor readability
delete delete-sysuser
add addDetIstr
update updateDetIstr
get appGetByNO

Swollen API

Interface Number Control

Opposition to unsigned API, resulting in API interface out of control, too many interfaces, affecting front-end debugging.

Interfaces that can be merged, try to merge, do not write duplicate interfaces

A class should have no more than six interfaces, as shown in the following figure:

Return Value Specification

  • It is forbidden to return invalid fields and expose the underlying information while increasing the communication cost for front-end personnel.As shown in the following figure:

API Interface Comment Specification

HTTP status code

Common Status Codes
2xx: Operation successful
 4xx: Client error
 5xx: server error

Full status code, portal: HTTP Series: HTTP Status Code

2xx status code
 200 Request (or Processing) Successful
 201 Request (or Processing) Failed
 
4xx status code
 Bad Request: The request parameters are incomplete or incorrect.
Unauthorized: Unauthorized identity.
Forbidden: The user has been authenticated, but does not have the required permissions to access the resource.
Not Found: The requested resource does not exist or is not available.
Method Not Allowed: The user has been authenticated, but the HTTP method used is not within his privileges.
Gone: The requested resource has been transferred from this address and is no longer available.
Unsupported Media Type: The return format requested by the client is not supported.For example, the API can only return JSON format, but the client requires XML format.
Unprocessable Entity: The attachment uploaded by the client cannot be processed, causing the request to fail.
Too Many Requests: Client requests exceeded the limit.
 
5xx status code
 In general, the API does not disclose server details to users, so only two status codes are sufficient.
Internal Server Error: The client request was valid and an unexpected event occurred while the server was processing.
Service Unavailable: The server cannot process requests and is typically used for site maintenance status.

API Return Format Specification

Request format for API
http://{domain name}/v1/{module}/{action}
Domain name: https://localhost:5011 or http://localhost:5010 or https://api.stonecontact.com
 Module: controller name, such as user.
Action: Functions implemented by each module.For example: add, delete, etc.
  
The specific format of the front-end components is regulated by the components of the website where you are hungry.
Document description is detailed in Swagger
 Server return status code is based on the HTTP StatusCode object of.NET Core, which is not enough to be extended
API return format
  • The response level directory contains three fields as follows: code, message, data
{
 "code": 200,
 "message": "", 
 "data":    
}
  • Server Exception Format
{
 "code": 500,
 "message": "Internal request error!",
 "data": 0
}
  • Validation returns error format
{
    "code": 400,
    "message": "Validation errors",
    "data": [
        "'Color Name' Cannot be empty.",
        "ColorName is mandatory.(Length:0-50)",
        "'Color Name_ CN' Cannot be empty."
    ]
}
  • List Format
{
  "code": 200,
  "message": "Operation success.",
  "data": {
    "grid": [
      {
        "colorID": 5,
        "colorName": "White",
        "pri": 0,
        "updateTimeTag": "2019-07-11T01:11:12.8490797Z",
        "colorName_CN": "white"
      },
      {
        "colorID": 6,
        "colorName": "Red",
        "pri": 0,
        "updateTimeTag": "2019-07-11T01:11:12.8496838Z",
        "colorName_CN": "gules"
      },
      {
        "colorID": 7,
        "colorName": "Multicolor",
        "pri": 0,
        "updateTimeTag": "2019-07-11T01:11:12.8496915Z",
        "colorName_CN": "blend"
      }
    ],
    "recordCount": 19
  }
}
  • Permission Format
{
 "code": 401,
}
  • Return a single object
{
    "code": 200,
    "message": "Operation success.",
    "data": {
        "colorID": 4,
        "colorName": "Brown",
        "pri": 0,
        "updateTimeTag": "2019-07-11T01:06:20.0629948Z",
        "colorName_CN": "brown"
    }
}
  • Tree Format
{
  "code": 200,
  "message": "Operation success.",
  "data": [
    {
      "id": 365,
      "text": "Stone Blocks",
      "pid": 0,
      "expanded": true,
      "leaf": true,
      "children": [
        {
          "id": 366,
          "text": "Marble Blocks",
          "pid": 365,
          "expanded": true,
          "leaf": false,
          "children": null
        },
        {
          "id": 367,
          "text": "Granite Blocks",
          "pid": 365,
          "expanded": true,
          "leaf": false,
          "children": null
        }
      ]
    },
    {
      "id": 172,
      "text": "Stone Tiles & Slabs",
      "pid": 0,
      "expanded": true,
      "leaf": true,
      "children": [
        {
          "id": 173,
          "text": "Alabaster Tiles & Slabs",
          "pid": 172,
          "expanded": true,
          "leaf": false,
          "children": null
        },
        {
          "id": 174,
          "text": "BlueStone Tiles & Slabs",
          "pid": 172,
          "expanded": true,
          "leaf": false,
          "children": null
        }
      ]
    }
  ]
}
  • Return to DropDownList format
"code":200,
    "msg":"Success",
    "data":[
        {
            "text":"China",
            "value":"0"
        },
        {
            "text":"America",
            "value":"1"
        },
        {
            "text":"Canada",
            "value":"3"
        }
    ],
  • API return code
API return code Meaning
200 Request succeeded
40000 Validation error
500 Server side error
400 Resource not found
  • Internal Service Call Interface
//1.Get Call Method
//1.1 with parameters
//Dictionary<string, object> param = new Dictionary<string, object>();
//param.Add("PageSize", 20);
//param.Add("PageIndex", 5);
//var client = RestSharpHelper.GetClient("url");
//var data = client.SendRequest(RestSharp.Method.GET, param);
 
//1.2 No parameters
var client = RestSharpHelper.GetClient("http://localhost:5010/api/v1/SysColor/list");
var response = client.SendRequest(Method.GET);
if (response.StatusCode == HttpStatusCode.OK)
{
    var result = JsonConvert.DeserializeObject<ColorResult>(response.Data.Data);
}
 
//2.Post Call Method
var client2 = RestSharpHelper.GetClient("http://localhost:5010/api/v1/SysColor/list");
var response2 = client2.SendRequest(Method.POST, JsonConvert.SerializeObject(new PostModel() { }));
 
if (response2.StatusCode == HttpStatusCode.OK)
{
    var result2 = JsonConvert.DeserializeObject<ColorResult>(response2.Data.Data);
}

Last

  • See here for more references to great posts: Chen Yongjia's Blog

  • A little friend who likes bloggers can pay attention and compliment, keep updating Hey!

397 original articles published, 973 praised, 90,000 visits+
His message board follow

Posted by artin on Thu, 16 Jan 2020 17:55:04 -0800