Method and implementation of calling API interface with PHP (with e-commerce platform product details interface case included)

With the advent of the Internet, cloud computing and big data era, more and more applications need to call third-party API interfaces to obtain data and achieve data interoperability and collaborative work. As a commonly used server-side language, PHP can also realize data interaction and integration of different systems by calling API interfaces. This article will introduce the method and implementation process of calling API interface in PHP.

1. Introduction to API interface

API (Application Programming Interface), application programming interface, is a protocol used for communication between different applications. Simply put, an API is a set of programmable conventions that define how an application communicates with other programs or servers. Through APIs, an application can request services or data from another application, or provide its own services or data to other applications.

APIs usually use standard protocols such as HTTP or SOAP for communication, and support the exchange of multiple data formats, such as XML, JSON, CSV, etc. APIs often require authentication and parameter passing to ensure data validity and security.

2. How to call API interface in PHP

1. Use the curl library to make HTTP requests

Curl is a powerful open source network transmission tool that supports multiple protocols, including HTTP, FTP, SMTP, etc. In PHP, we can easily make HTTP requests through the curl library and obtain the data returned by the API.

The following is an example of using the curl library to send an HTTP GET request, where is $urlthe URL address of the API interface, is the request header parameter, ℎ����� is the ���� request header parameter, and 'params` is the GET parameter of the HTTP request:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);

If it is a POST request, the request parameters can $bodybe passed in and the request header information is still placed $headerin:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);

The error information and error code of the curl request can be obtained through the curl_errorand curl_errnofunctions.

2. Use the file_get_contents function to make HTTP requests

In addition to the curl library, PHP also provides file_get_contentsfunctions for obtaining the content of the URL address, in which HTTP request header information can be set:

$header = array(
    'Content-type: application/json',
    'Authorization: Bearer ' . $token
);
$options = array(
    'http' => array(
        'method' => 'GET',
        'header' => implode("
", $header)
    )
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

This method can also be used for POST requests, just modify methodthe and headerparameters.

3. Use the Guzzle library to make HTTP requests

Guzzle is a third-party HTTP client library for PHP that provides a series of easy-to-use APIs, supports HTTP/1.1 and HTTP/2, supports asynchronous requests, and both request and response headers can be customized. Install Guzzle via composer:

composer require guzzlehttp/guzzle

The following is an example of using the Guzzle library to send an HTTP GET request, where is $urithe URL address of the API interface, $queryis the GET parameter of the HTTP request, and $headersis the HTTP request header parameter:

$client = new GuzzleHttpClient();
$response = $client->request('GET', $uri, [
    'query' => $query,
    'headers' => $headers
]);
$data = $response->getBody()->getContents();

The POST request is also very simple. Just requestchange the GET in the method to POST and put the request parameters in form_paramsthe parameters.

3. API interface call implementation

If the API you want to call is a third-party API, you need to check the API documentation first to understand its request method, URL, parameters, return results and other information. If you write the API yourself, you need to write an API interface program to implement the functions of receiving requests, processing requests, and returning data.

The following is a simple API interface program example for returning the current product details page information:

<?php

// 请求示例 url 默认请求参数已经URL编码处理
// 本示例代码未加密secret参数明文传输,若要加密请参考:https://help/demo/sdk/demo-sign.php
$method = "GET";
$url = "https://taobao/item_get/?key=<您自己的apiKey>&secret=<您自己的apiSecret>&num_iid=652874751412&is_promotion=1";
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_ENCODING, "gzip");
var_dump(curl_exec($curl));
?>

Response example

{
	"item": {
		"num_iid": "652874751412",
		"title": "北欧轻奢布艺沙发 小户型简约现代客厅ins风网红款三双人订制沙发",
		"desc_short": "",
		"price": 480,
		"total_price": 0,
		"suggestive_price": 0,
		"orginal_price": 480,
		"nick": "惜情yqq1127",
		"num": "200",
		"min_num": 0,
		"detail_url": "https://item.taobao.com/item.htm?id=652874751412",
		"pic_url": "//img.alicdn.com/imgextra/i4/2568161054/O1CN01aYBriY1Jem9UDtt9e_!!2568161054.jpg",
		"brand": "#0 工厂",
		"brandId": "1435187098",
		"rootCatId": "50008164",
		"cid": "50020632",
		"crumbs": [],
		"created_time": "",
		"modified_time": "",
		"delist_time": "",
		"desc": "<img size=\"27893\">https://img.alicdn.com/imgextra/i3/2568161054/O1CN01LFmSOU1Jem9QOjMPb_!!2568161054.jpg</img><img size=\"132455\">https://img.alicdn.com/imgextra/i3/2568161054/O1CN014vyOOT1Jem9DpHz3Y_!!2568161054.jpg</img><img size=\"2455\">https://img.alicdn.com/imgextra/i1/2568161054/O1CN01B3PpsA1Jem9N8V7uf_!!2568161054.jpg</img><img size=\"117664\">https://img.alicdn.com/imgextra/i2/2568161054/O1CN015JbyeY1Jem9MZshUt_!!2568161054.jpg</img><img size=\"16674\">https://img.alicdn.com/imgextra/i1/2568161054/O1CN01HXSoxx1Jem9RvgzHN_!!2568161054.jpg</img><img size=\"96260\">https://img.alicdn.com/imgextra/i3/2568161054/O1CN01IEultA1Jem9MdEx8R_!!2568161054.jpg</img><img size=\"13573\">https://img.alicdn.com/imgextra/i3/2568161054/O1CN0176K98O1Jem9QOjE69_!!2568161054.jpg</img><img size=\"110974\">https://img.alicdn.com/imgextra/i4/2568161054/O1CN013Pxp1O1Jem9RvgeTv_!!2568161054.jpg</img><img size=\"104198\">https://img.alicdn.com/imgextra/i1/2568161054/O1CN01SfyZ8M1Jem9QOi1Gx_!!2568161054.jpg</img><img size=\"576580\">https://img.alicdn.com/imgextra/i4/2568161054/O1CN01bb1POa1Jem9Sdgve2_!!2568161054.jpg</img><img size=\"676617\">https://img.alicdn.com/imgextra/i3/2568161054/O1CN018Eo9dV1Jem9KV0y79_!!2568161054.jpg</img><img size=\"9125\">https://img.alicdn.com/imgextra/i1/2568161054/O1CN01vuEofr1Jem9Nzy9xY_!!2568161054.jpg</img><img size=\"107197\">https://img.alicdn.com/imgextra/i4/2568161054/O1CN01qw9sAi1Jem8wkNKpy_!!2568161054.jpg</img><img size=\"198877\">https://img.alicdn.com/imgextra/i1/2568161054/O1CN01HeFhFw1Jem8rLnjBY_!!2568161054.jpg</img><img size=\"71423\">https://img.alicdn.com/imgextra/i2/2568161054/O1CN01SNgjoi1Jem9QOil15_!!2568161054.jpg</img><img size=\"37628\">https://img.alicdn.com/imgextra/i2/2568161054/O1CN01RXf3RA1Jem9DpHVwj_!!2568161054.jpg</img><img size=\"170889\">https://img.alicdn.com/imgextra/i4/2568161054/O1CN01gZmZjt1Jem9ISThgm_!!2568161054.jpg</img><img size=\"6378\">https://img.alicdn.com/imgextra/i2/2568161054/O1CN01YL0FHM1Jem9PQTjX9_!!2568161054.jpg</img><img size=\"212074\">https://img.alicdn.com/imgextra/i4/2568161054/O1CN01UhsEhZ1Jem8yvJIhZ_!!2568161054.jpg</img><img src=\"https://www.o0b.cn/i.php?t.png&rid=gw-3.64fec371ecc41&p=1778787181&k=i_key&t=1694417780\" style=\"display:none\" />",
		"desc_img": [],
		"item_imgs": [
			{
				"url": "//img.alicdn.com/imgextra/i4/2568161054/O1CN01aYBriY1Jem9UDtt9e_!!2568161054.jpg"
			},
			{
				"url": "//img.alicdn.com/imgextra/i3/2568161054/O1CN01kjOfNb1Jem9DmWn8Y_!!2568161054.jpg"
			},
			{
				"url": "//img.alicdn.com/imgextra/i1/2568161054/O1CN01HoB9ha1Jem9DmWn8r_!!2568161054.jpg"
			},
			{
				"url": "//img.alicdn.com/imgextra/i4/2568161054/O1CN011PjP2P1Jem9MXEUFT_!!2568161054.jpg"
			},
			{
				"url": "//img.alicdn.com/imgextra/i3/2568161054/O1CN01KUfBFL1Jem9KTTMn1_!!2568161054.jpg"
			}
		],
		"item_weight": "",
		"item_size": "",
		"location": "江苏南通",
		"post_fee": "",
		"express_fee": null,
		"ems_fee": "",
		"shipping_to": "",
		"has_discount": "false",
		"video": {
			"url": null
		},
		"is_virtual": "",
		"sample_id": "",
		"is_promotion": "false",
		"props_name": "31480:14306495906:几人坐:脚踏90*60*48cm;31480:14306495907:几人坐:双人165*95*67cm;31480:14306495908:几人坐:三人210*95*67cm;31480:14306495909:几人坐:单人100*95*67cm;31480:21480914361:几人坐:四人位240*95*67cm;31480:21480914362:几人坐:大四人320*95*76cm;31480:1387571900:几人坐:3米贵妃沙发;31480:32527954:几人坐:定制尺寸;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
		"prop_imgs": {
			"prop_img": [
				{
					"properties": "1627207:28321",
					"url": "//img.alicdn.com/imgextra/i1/2568161054/O1CN017GTZ4h1Jem9Qra1ap_!!2568161054.jpg"
				}
			]
		},
		"property_alias": "",
		"props": [
			{
				"name": "品牌",
				"value": "#0 工厂"
			},
			{
				"name": "型号",
				"value": "520"
			},
			{
				"name": "材质",
				"value": "木"
			},
			{
				"name": "木质材质",
				"value": "松木"
			},
			{
				"name": "面料",
				"value": "绒布"
			},
			{
				"name": "风格",
				"value": "北欧"
			},
			{
				"name": "几人坐",
				"value": "脚踏90*60*48cm,双人165*95*67cm,三人210*95*67cm,单人100*95*67cm,四人位240*95*67cm,大四人320*95*76cm,3米贵妃沙发,定制尺寸"
			},
			{
				"name": "颜色分类",
				"value": "乳白色"
			},
			{
				"name": "填充物",
				"value": "海绵"
			},
			{
				"name": "结构工艺",
				"value": "木质工艺"
			},
			{
				"name": "是否可定制",
				"value": "是"
			},
			{
				"name": "沙发组合形式",
				"value": "U形"
			},
			{
				"name": "是否可拆洗",
				"value": "是"
			},
			{
				"name": "适用对象",
				"value": "成年人"
			},
			{
				"name": "是否带储物空间",
				"value": "否"
			},
			{
				"name": "产地",
				"value": "上海"
			},
			{
				"name": "地市",
				"value": "上海市"
			},
			{
				"name": "区县",
				"value": "奉贤区"
			},
			{
				"name": "是否组装",
				"value": "否"
			},
			{
				"name": "出租车是否可运输",
				"value": "否"
			},
			{
				"name": "填充物硬度",
				"value": "软"
			},
			{
				"name": "款式定位",
				"value": "经济型"
			}
		],
		"total_sold": "604",
		"skus": {
			"sku": [
				{
					"price": 480,
					"total_price": 0,
					"orginal_price": 480,
					"properties": "31480:14306495906;1627207:28321",
					"properties_name": "31480:14306495906:几人坐:脚踏90*60*48cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "4881047531343"
				},
				{
					"price": 1688,
					"total_price": 0,
					"orginal_price": 1688,
					"properties": "31480:14306495907;1627207:28321",
					"properties_name": "31480:14306495907:几人坐:双人165*95*67cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "135",
					"sku_id": "4881047531344"
				},
				{
					"price": 2088,
					"total_price": 0,
					"orginal_price": 2088,
					"properties": "31480:14306495908;1627207:28321",
					"properties_name": "31480:14306495908:几人坐:三人210*95*67cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "4881047531345"
				},
				{
					"price": 968,
					"total_price": 0,
					"orginal_price": 968,
					"properties": "31480:14306495909;1627207:28321",
					"properties_name": "31480:14306495909:几人坐:单人100*95*67cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "4881047531346"
				},
				{
					"price": 2388,
					"total_price": 0,
					"orginal_price": 2388,
					"properties": "31480:21480914361;1627207:28321",
					"properties_name": "31480:21480914361:几人坐:四人位240*95*67cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "5039985183001"
				},
				{
					"price": 3188,
					"total_price": 0,
					"orginal_price": 3188,
					"properties": "31480:21480914362;1627207:28321",
					"properties_name": "31480:21480914362:几人坐:大四人320*95*76cm;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "5039985183002"
				},
				{
					"price": 3400,
					"total_price": 0,
					"orginal_price": 3400,
					"properties": "31480:1387571900;1627207:28321",
					"properties_name": "31480:1387571900:几人坐:3米贵妃沙发;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "5039984824000"
				},
				{
					"price": 3000,
					"total_price": 0,
					"orginal_price": 3000,
					"properties": "31480:32527954;1627207:28321",
					"properties_name": "31480:32527954:几人坐:定制尺寸;1627207:28321:颜色分类:乳白色 尺寸颜色可定制",
					"quantity": "200",
					"sku_id": "5039985183003"
				}
			]
		},
		"seller_id": "2568161054",
		"sales": 19,
		"shop_id": "567158267",
		"props_list": {
			"31480:14306495906": "几人坐:脚踏90*60*48cm",
			"31480:14306495907": "几人坐:双人165*95*67cm",
			"31480:14306495908": "几人坐:三人210*95*67cm",
			"31480:14306495909": "几人坐:单人100*95*67cm",
			"31480:21480914361": "几人坐:四人位240*95*67cm",
			"31480:21480914362": "几人坐:大四人320*95*76cm",
			"31480:1387571900": "几人坐:3米贵妃沙发",
			"31480:32527954": "几人坐:定制尺寸",
			"1627207:28321": "颜色分类:乳白色 尺寸颜色可定制"
		},
		"seller_info": {
			"nick": "惜情yqq1127",
			"item_score": "4.9 ",
			"score_p": "4.9 ",
			"delivery_score": "4.9 ",
			"shop_type": "C",
			"user_num_id": "2568161054",
			"sid": "567158267",
			"title": "现代布艺沙发",
			"zhuy": "https://shop567158267.taobao.com/",
			"shop_name": "现代布艺沙发"
		},
		"tmall": false,
		"error": "",
		"warning": "",
		"url_log": [],
		"fav_count": "8018",
		"fans_count": "684",
		"freight": "平邮: 快递包邮",
		"props_imgs": {
			"prop_img": [
				{
					"properties": "1627207:28321",
					"url": "//img.alicdn.com/imgextra/i1/2568161054/O1CN017GTZ4h1Jem9Qra1ap_!!2568161054.jpg"
				}
			]
		},
		"_ddf": "xdl",
		"promo_type": null,
		"props_img": {
			"1627207:28321": "//img.alicdn.com/imgextra/i1/2568161054/O1CN017GTZ4h1Jem9Qra1ap_!!2568161054.jpg"
		},
		"format_check": "ok",
		"shop_item": [],
		"relate_items": []
	},
	"error": "",
	"secache": "4ad7ad2480af253fec9c2fd4daa266bb",
	"secache_time": 1694417780,
	"secache_date": "2023-09-11 15:36:20",
	"translate_status": "",
	"translate_time": 0,
	"language": {
		"default_lang": "cn",
		"current_lang": "cn"
	},
	"reason": "",
	"error_code": "0000",
	"cache": 0,
	"api_info": "today:67 max:10100 all[165=67+65+33];expires:2030-12-31",
	"execution_time": "2.133",
	"server_time": "Beijing/2023-09-11 15:36:20",
	"client_ip": "106.6.35.109",
	"call_args": {
		"num_iid": "652874751412",
		"is_promotion": "1"
	},
	"api_type": "taobao",
	"translate_language": "zh-CN",
	"translate_engine": "baidu",
	"server_memory": "6MB",
	"request_id": "gw-3.64fec371ecc41",
	"last_id": "2022567237"
}

 When calling the API interface, you may encounter various errors and exceptions, such as network connection errors, parameter errors, interface response errors, etc. In order to better handle errors and exceptions during API calls, we need to write corresponding error handling and debugging code so that problems can be discovered and solved in time.

V. Summary

Through the introduction of this article, we have learned the method and implementation process of calling API interfaces in PHP, including using curl library, file_get_contentsfunctions and Guzzle library to make HTTP requests, writing API interface programs, error handling and debugging, etc. API interface is a common interconnection method between modern applications. Mastering the basic knowledge and skills of API calling can help us better realize the functional requirements of applications.

Guess you like

Origin blog.csdn.net/APItesterCris/article/details/132809265