Home Backend Development PHP Tutorial PHP API interface testing

PHP API interface testing

Mar 20, 2018 pm 03:03 PM
api php test

I have been writing API interfaces recently. Every time I write an interface, I need to test it myself first to see if there are any syntax errors and whether the requested data is correct. However, many of them are POST requests and I cannot directly open the link in the browser for testing. , so there must be a simulation tool that can send HTTP requests locally to simulate data requests.
This is what I did at the beginning, create a file in the local wampserver running directory, write Curl requests in it, and conduct simulated request tests, but each interface needs The parameters are all different. I need to constantly modify the requested parameters and API, which is very inconvenient. Later, I couldn’t distinguish the messy data in my request file:

I searched for related tools on the Internet. There are many online tests, such as: ATOOL online tools, Apizza, etc., I looked at them and they all do a good job, very easy to use, the interface is beautiful, and the service is very considerate. But I am considering security issues, and at the same time it gives meThe data returned is the original JSON format, I am used to looking at arrays The format is relatively intuitive.
So, in line with the concept of having enough food and clothing by myself, I wrote a simple API test page locally. After submitting the data, I implemented the API request testing function locally. I didn't need to consider security issues, and I could convert the results at will. Only two files are needed to complete it, one is the page post.html for filling in the data, and the other is the post.php file that receives the data from the post.html page and processes the request to implement the function.
1. The front-end page file post.html


is just a simple page, no complex layout, no JS special effects, just write There are 6 parameters, which are generally enough. If not, you can add them yourself. By default, body request parameters are passed here, and only GET and POST are used for request methods.

<html xmlns="http://blog.csdn.net/sinat_35861727?viewmode=contents">

<head>
	<meta http-equiv = "Content-Type" content = "text/html;charset = utf8">
	<meta name = "description" content = "提交表单">
	<title>API接口请求表单</title>
</head>
	<style type="text/css">
		.key1{
			width:100px;
		}
		.value1{
			width:230px;
			margin:0 0 0 10px;
		}
		.main{
			margin:0 auto;
			width:450px;
			height:auto;
			background:lightgray;
			padding:40px 40px;
		}
		.refer{
			width:100px;
			height:24px;
		}
		.url{
			width:350px;
		}
	</style>
<body>

<p class="main">
	<form method="POST" action="post.php" target="_blank">
		<p>请求地址:<input class="url" type="text" name="curl" placeholder="API接口地址"></p>
		<p>参 数1: <input class="key1" type="text" name="key1" placeholder="参数名">
					 <input class="value1" type="text" name="value1" placeholder="参数值"></p>
		<p>参 数2: <input class="key1" type="text" name="key2" placeholder="参数名">
					 <input class="value1" type="text" name="value2" placeholder="参数值"></p>
		<p>参 数3: <input class="key1" type="text" name="key3" placeholder="参数名">
					 <input class="value1" type="text" name="value3" placeholder="参数值"></p>
		<p>参 数4: <input class="key1" type="text" name="key4" placeholder="参数名">
					 <input class="value1" type="text" name="value4" placeholder="参数值"></p>
		<p>参 数5: <input class="key1" type="text" name="key5" placeholder="参数名">
					 <input class="value1" type="text" name="value5" placeholder="参数值"></p>
		<p>参 数6: <input class="key1" type="text" name="key6" placeholder="参数名">
					 <input class="value1" type="text" name="value6" placeholder="参数值"></p>
		<p>请求方式: <select name="method">
			<option value="POST">POST请求</option>
			<option value="GET">GET请求</option>
		</select></p>
		<p style="text-align:center;"><input class="refer" type="submit" value="提交"></p>
	</form>
</p>
</body>


</html>
Copy after login


2. Data processing file post.php

Receives the data from the post.html page, sends a request and then processes the request result. What is passed from the front-end page is the Body Request parameters, if you still need Header parameters, you can add them manually in this file.

<?php

echo &#39;<title>API接口请求响应</title>&#39;;

/**
 * 设置网络请求配置
 * @param  [string] $curl 请求的URL
 * @param  [bool]   true || false 是否https请求
 * @param  [string] $method 请求方式,默认GET
 * @param  [array]  $header 请求的header参数
 * @param  [object] $data PUT请求的时候发送的数据对象
 * @return [object] 返回请求响应
 */
function ihttp_request($curl,$https=true,$method=&#39;GET&#39;,$header=array(),$data=null){
	// 创建一个新cURL资源
	$ch = curl_init();
	
	// 设置URL和相应的选项
	curl_setopt($ch, CURLOPT_URL, $curl);    //要访问的网站
	//curl_setopt($ch, CURLOPT_HEADER, false); 
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

	if($https){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  
		//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
	}
	if($method == &#39;POST&#39;){
		curl_setopt($ch, CURLOPT_POST, true);  //发送 POST 请求
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	
	
	// 抓取URL并把它传递给浏览器
	$content = curl_exec($ch);
	if ($content  === false) {
	  return "网络请求出错: " . curl_error($ch);
	  exit();
	}
	//关闭cURL资源,并且释放系统资源
	curl_close($ch);
	
	return $content;
}

//检查是否是链接格式
function checkUrl($C_url){  
    $str="/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\&#39;:+!\.#\w]*)?$/";  
    if (!preg_match($str,$C_url)){  
        return false;  
    }else{  
		return true;  
    }  
}  

//检查是不是HTTPS
function check_https($url){
	$str="/^https:/";
	if (!preg_match($str,$url)){  
        return false;  
    }else{  
		return true;  
    }  
}

if($_SERVER[&#39;REQUEST_METHOD&#39;] != &#39;POST&#39;) exit(&#39;请求方式错误!&#39;);


//发送请求
function curl_query(){
	$data = array(
		$_POST[&#39;key1&#39;] => $_POST[&#39;value1&#39;],
		$_POST[&#39;key2&#39;] => $_POST[&#39;value2&#39;],
		$_POST[&#39;key3&#39;] => $_POST[&#39;value3&#39;],
		$_POST[&#39;key4&#39;] => $_POST[&#39;value4&#39;],
		$_POST[&#39;key5&#39;] => $_POST[&#39;value5&#39;],
		$_POST[&#39;key6&#39;] => $_POST[&#39;value6&#39;]
	);
	//数组去空
	$data = array_filter($data);					//post请求的参数
	if(empty($data)) exit(&#39;请填写参数&#39;);
	
	$url = $_POST[&#39;curl&#39;];							//API接口
	if(!checkUrl($url)) exit(&#39;链接格式错误&#39;);		//检查连接的格式
	$is_https = check_https($url);   				//是否是HTTPS请求

	$method = $_POST[&#39;method&#39;];						//请求方式(GET POST)
	
	$header = array();								//携带header参数
	//$header[] = &#39;Cache-Control: max-age=0&#39;;
	//$header[] = &#39;Connection: keep-alive&#39;;
	
	if($method == &#39;POST&#39;){
		$res = ihttp_request($url,$is_https,$method,$header,$data);
		print_r(json_decode($res,true));
	}else if($method == &#39;GET&#39;){
		$curl = $url.&#39;?&#39;.http_build_query($data);	//GET请求参数拼接
		$res = ihttp_request($curl,$is_https,$method,$header);
		print_r(json_decode($res,true));
	}else{
		exit(&#39;error request method&#39;);
	}

}

curl_query();

?>
Copy after login

The writing is very simple, and the functions are not very comprehensive. The POST and GET requests under normal circumstances can still be satisfied. At least the local test results are no problem. Friends who need it can download the code. , and then modify and improve the functions according to your own needs.

Related recommendations:

PHP API interface testing gadget

The above is the detailed content of PHP API interface testing. 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles