Menu

API Overall Design

This article was last updated 37 days ago, please note whether the content is still available

Here is the English translation of the provided Chinese content, maintaining the original structure and HTML:

Overview

Based on the functional modules (Module) of Z-BlogPHP, they can be divided into the following nine modules:

  • User Module

  • Article Module (including Pages)

  • Application Module (including Plugins and Themes)

  • Sidebar Module

  • Attachment Module

  • Comment Module

  • Tag Module

  • Category Module

  • System and Settings Module

Interface Behavior (Action), simply put, is the implementation of data Create, Read, Update, and Delete operations for a certain module. For example, operations such as adding a user, user login, and retrieving/modifying user information in the User Module.

The overall idea of the ZBP API is: the server performs corresponding Behavior operations on a Module based on the request sent by the client, and returns the execution result to the client. Essentially, it's not much different from the original web version; it's just different output formats under the same business logic. The web version returns HTML, while the API returns JSON.

Unified Entry Point

The API entry point is defined as: http[s]://<domain>/zb_system/api.php

Request Methods

Clients primarily use GET and POST HTTP request methods to request server resources.

Among these, GET represents a "GET" operation, corresponding to a SELECT operation in the database. For example: retrieving a specific article.

POST represents "CREATE", "UPDATE", and "DELETE" operations, corresponding to INSERT, UPDATE, and DELETE operations in the database. For example: creating a new user.

To ensure support for a large number of parameters, for "GET/QUERY" type interfaces, both GET and POST request methods are supported. For "CREATE/DELETE/UPDATE" type interfaces, only POST requests are supported.

Common Request Headers

HeaderRequiredExample ValueDescription
Content-TypeOptionalapplication/json; charset=utf-8The message format accepted by the client.
Regardless, the server always returns content in JSON format.
Accept-EncodingOptionalgzip, deflate, brCompression algorithms accepted by the client
User-AgentOptionalMozilla/5.0-
RefererOptionalhttps://example.com/Referrer URL
Accept-LanguageOptionalzh-cnLanguage code accepted by the client

Authentication

Obtaining Authentication Credentials

POST https://example.com/zb_system/api.php?mod=member&act=login

HTTP Body:

{
  "username": "zblog_usr",
  "password": "zblog_pwd",
  "savedate": 30
}

"savedate": 30: Validity period of 30 days;

Note: For password, it is recommended to use the MD5 value of the plain text password. You can also use the plain text password (but there's a risk of it being leaked if intercepted) ↑↑

Response Body:

{
  "code": 200,
  "message": "Operation successful",
  "data": {
    "user": {
      "ID": "1",
      "Level": "1",
      "Name": "zblog_usr"
    },
    "token": "6K+t6K="
  },
  "error": null
}

Usage

For subsequent requests requiring authentication, the "Authentication Token" can be passed in three ways:

  1. Set the authorization header as follows: Authorization: Bearer {YourToken} (Recommended)

  2. When accessing the API via POST, you can submit a form input with the name token and value as {YourToken}.

  3. When accessing the API via GET, append it to the URL: https://example.com/zb_system/api.php?mod=setting&act=get&token={YourToken} (This method may leak the token)

Important: For method 1, additional configuration of your web server might be required. Refer to "Frequently Asked Questions".

Constructing Requests

Module Naming

ModuleNaming
User Modulemember
Article Module (including Pages)post
Application Module (including Plugins and Themes)app
Sidebar Modulesidebar
Attachment Moduleupload
Comment Modulecomment
Tag Moduletag
Category Modulecategory
System and Settings Modulesystem

General URL Format

https://example.com/zb_system/api.php?mod=<module_name>[&act=<action_name>][&other...]

Since it's a single entry point, different modules cannot be represented by paths; they must be represented by URL parameters. Parameter order does not matter.

URL Parameters

Module Name

  • The module name is the English name of the functional module.

Action Name

  • The action name represents the operation. For example, act=post means creating a resource, act=update means modifying/updating a resource, and act=delete means deleting a resource.

  • Action Name Omission Mechanism:

    When the request method is GET, because the semantic meaning of GET is "retrieve," if the action name is not specified, the default operation is the act=get behavior.

    Therefore, the interface for "retrieving information of a specific user" is mod=user&act=get&id=123. You can omit act=get and use mod=user&id=123 directly.

    POST requests do not support the action name omission mechanism; the action name must be specified.

  • Multi-semantic Action Names:

    Multi-semantic action names can represent operations on more specific resource objects. Multiple semantic action names are separated by an underscore "_".

    For example, for the Sidebar Module (mod=sidebar), there are two resource objects: the sidebar itself, and the "modules" within the sidebar. The interface mod=sidebar&act=get&id=1 represents "retrieving information of the sidebar with ID 1". To implement "retrieving information of modules within the sidebar," a more detailed semantic act=get_module is needed, i.e., mod=sidebar&act=get_module&id=name. This applies similarly to other cases where multiple resource objects exist.

Other Parameters

  • Represents additional content, such as constraint conditions, authorization tokens, or custom content from third-party developers.

Constraints and Filtering

Constraint Filters (Filter) are generally used for list-type resources, such as article lists.

The specific supported constraint conditions are determined by the data table of the functional module.

Multiple constraint conditions use "AND" logic by default.

ParameterTypeExample ValueDescription
perpageint50Number of items to return per page. Unauthenticated requests are limited by a maximum value.
pageint2Specifies the page number.
sortbystringnameSorting criteria. Case-sensitive. Refer to the "Sorting Criteria Table" for details.
orderstringasc or descSorting order. asc: ascending, desc: descending.

Sorting criteria supported by each "API Module":

modsortby
categoryID, Order, Count, Group
commentID, PostTime
memberID, CreateTime, PostTime, UpdateTime, Articles, Pages, Comments, Uploads
postID, CreateTime, PostTime, UpdateTime, CommNums, ViewNums
tagID, Order, Count
uploadID, PostTime, DownNums

Specific query parameters supported by different "API Modules" can be found in the "Interface List";

Common Response Headers

HeaderDescriptionExample ValueDescription
Content-TypeRequiredapplication/json; charset=utf-8Currently, only JSON format is supported for responses.
Content-EncodingOptionalgzipContent compression method. Enabled based on client selection. gzip compression is enabled by default.
DateOptionalSun, 23 Feb 2020 07:03:41 GMTServer response time. Sometimes useful for testing latency.

General Response Format

The response Body from the server is a JSON string, uniformly formatted as follows:

Parameter NameTypeDescription
messagestringResponse description
dataobjectMain data
errorobjectError information
runtimeobjectDebugging information

Detailed error and debugging information is only output when debug mode is enabled.

Attribute names are always in lowercase. If necessary, multiple words are separated by an underscore "_", such as "new_data".

Response Content Examples and Status Codes

Example 1: No permission

Reason: Not logged in or the logged-in user does not have sufficient permissions; Refer to "Login and Authentication".

{
  "code": 401,
  "message": "No permission",
  "data": null,
  "error": null,
  "runtime": {
    "time": "94.76",
    "query": 4,
    "memory": 1684
  }
}

Example 2: Illegal access

Reason: Authentication Token not set correctly; Refer to "Login and Authentication".

{
  "code": 419,
  "message": "Illegal access",
  "data": null,
  "error": null,
  "runtime": {
    "time": "94.29",
    "query": 4,
    "memory": 1657
  }
}

Example 3: Successful request for a user's information

{
  "code": 200,
  "message": "OK",
  "data": {
    "member": {
      "ID": 123,
      "Name": "Chris",
      "Email": "123@example.com",
      "StaticName": "admin"
    }
  },
  "error": null,
  "runtime": {
    "time": "90.74",
    "query": 5,
    "memory": 1807
  }
}

Internal Calls

To facilitate the system itself (including themes and plugins) in calling the website's API, we provide an internal calling method.

Calling

ApiExecute($mod, $act, $get = array(), $post = array())

Example

var_dump(ApiExecute('post', 'get', array('id' => '1')));

Add/Remove Private API

Description
In the API system, a Private API can only be called by itself, meaning it can only be called via the ApiExecute method.

ApiAddPrivateMod('newapi', __DIR__ . '/myapi.php'); // Inserts the implementation file into the system's Private API with 'newapi' as the module name.
ApiRemovePrivateMod($modname); // Removes the Private API with the module name 'newapi'.

The code used in this section requires version 1.7.3.3230 or later of the main program.


Helpful?

Post comment

Support Live Chat
TOP