Home Backend Development PHP Tutorial Detailed explanation of web API interface and restful specifications

Detailed explanation of web API interface and restful specifications

Nov 28, 2019 pm 02:47 PM
api restful

Detailed explanation of web API interface and restful specifications

What is a web API interface?

Clarify the request method, provide the parameters required by the corresponding backend, and request the url link to get the response data from the backend

Request method: get, post, put, patch. ...

Request parameters: key-value type data in json or xml format

Response result: return key-value type data in json or xml format

How to write an interface?

Write the url link with reference to a certain rule (specification), and formulate the request method, request data and response results according to the rules

Interface specification: webapi interface specification: restful

RESTful introduction

REST has nothing to do with technology. It represents a software architecture style. REST is the abbreviation of Representational State Transfer, and the Chinese translation is "Representation state transfer" or "presentation layer state transformation".

Domain name

Use the api keyword to identify the interface url

https://api.example.com
https://example.org/api/
Copy after login

Note: If you see the word api, it means that the request url link is before completion

Version of background data interaction

1. Put the version information in the URL, such as:

https://api.example.com/v1/
https://api.example.com/v2/
Copy after login

v1, v2 represents different data versions Withdrawal, the premise is that a data resource has multiple versions

2. Put the version information in the request header.

url path

We regard everything on the Internet as a resource and use nouns to express it (generally plural form)

https://api.example.com/v1/zoos
https://api.example.com/v1/animals
https://api.example.com/v1/employees
Copy after login

In the url link Rewards do not appear verbs that operate resources

Error demonstration:https://api.baidu.com/delete-user

Verbs can appear in special interfaces because these The interface generally does not have a clear resource, or the verb is the core meaning of the interface

https://api.baidu.com/place/search
https://api.baidu.com/login
Copy after login

method request method

GET: Get the resource (one or more items) from the server )

POST: Create a new resource on the server

PUT: Update the resource on the server (the client provides the changed complete resource)

PATCH: Update the resource on the server (client The changed attributes are provided by the client)

DELETE: Delete resources from the server

Filtering

Pass search conditions in the form of upload parameters in the url

https://api.example.com/v1/zoos?limit=10:指定返回记录的数量
https://api.example.com/v1/zoos?offset=10:指定返回记录的开始位置
https://api.example.com/v1/zoos?page=2&per_page=100:指定第几页,以及每页的记录数
https://api.example.com/v1/zoos?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序
https://api.example.com/v1/zoos?animal_type_id=1:指定筛选条件
Copy after login

Status code

200 OK - [GET]: The server successfully returns the data requested by the user. This operation is idempotent (Idempotent).

201 CREATED - [POST/PUT/PATCH]: The user successfully created or modified data.

202 Accepted - [*]: Indicates that a request has entered the background queue (asynchronous task)

204 NO CONTENT - [DELETE]: The user deleted the data successfully.

301: Permanent redirection

302: Temporary redirection

400 INVALID REQUEST - [POST/PUT/PATCH]: The request issued by the user has an error and the server did not proceed The operation of creating or modifying data is idempotent.

401 Unauthorized - [*]: Indicates that the user does not have permission (the token, username, and password are incorrect).

403 Forbidden - [*] Indicates that the user is authorized (as opposed to the 401 error), but access is prohibited.

404 NOT FOUND - [*]: The request issued by the user is for a record that does not exist, and the server did not perform the operation. The operation is idempotent.

406 Not Acceptable - [GET]: The format requested by the user is not available (for example, the user requested JSON format, but only XML format).

410 Gone -[GET]: The resource requested by the user is permanently deleted and will not be obtained again.

422 Unprocesable entity - [POST/PUT/PATCH] A validation error occurred while creating an object.

500 INTERNAL SERVER ERROR - [*]: A server error occurred and the user will not be able to determine whether the request made was successful.

Error handling

When the status code is 4xx, the error message should be returned, and error is used as the key.

{
    error: "Invalid API key"
}
Copy after login

Return results

For different operations, the results returned by the server to the user should comply with the following specifications

GET /collection: Returns a list of resource objects (Array)

GET /collection/resource: Return a single resource object

POST /collection: Return a newly generated resource object

PUT /collection/resource: Return a complete Resource object

PATCH /collection/resource: Returns a complete resource object

DELETE /collection/resource: Returns an empty document

{
    "status": 0,
    "msg": "ok",
    "results":[
        {
            "name":"肯德基(罗餐厅)",
            "location":{
                "lat":31.415354,
                "lng":121.357339
            },
            "address":"月罗路2380号",
            "province":"上海市",
            "city":"上海市",
            "area":"宝山区",
            "street_id":"339ed41ae1d6dc320a5cb37c",
            "telephone":"(021)56761006",
            "detail":1,
            "uid":"339ed41ae1d6dc320a5cb37c"
        }
        ...
        ]
}
Copy after login

Hypermedia API

RESTful API is best implemented as Hypermedia, that is, links are provided in the returned results to other API methods, so that users know what to do next without checking the documentation.

{"link": {
  "rel":   "collection https://www.example.com/zoos",
  "href":  "https://api.example.com/zoos",
  "title": "List of zoos",
  "type":  "application/vnd.yourformat+json"
}}
Copy after login

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Detailed explanation of web API interface and restful specifications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Save API data to CSV format using Python Save API data to CSV format using Python Aug 31, 2023 pm 09:09 PM

In the world of data-driven applications and analytics, APIs (Application Programming Interfaces) play a vital role in retrieving data from various sources. When working with API data, you often need to store the data in a format that is easy to access and manipulate. One such format is CSV (Comma Separated Values), which allows tabular data to be organized and stored efficiently. This article will explore the process of saving API data to CSV format using the powerful programming language Python. By following the steps outlined in this guide, we will learn how to retrieve data from the API, extract relevant information, and store it in a CSV file for further analysis and processing. Let’s dive into the world of API data processing with Python and unlock the potential of the CSV format

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

How to develop a simple CRUD API using MongoDB How to develop a simple CRUD API using MongoDB Sep 19, 2023 pm 12:32 PM

How to use MongoDB to develop a simple CRUD API In modern web application development, CRUD (Create, Delete, Modify, Check) operations are one of the most common and important functions. In this article, we will introduce how to develop a simple CRUD API using MongoDB database and provide specific code examples. MongoDB is an open source NoSQL database that stores data in the form of documents. Unlike traditional relational databases, MongoDB does not have a predefined schema

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles