This time I will show you how to test the API interface locally and what are the precautions for testing the API interface locally. The following is a practical case, let's take a look.
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 This is what I did at the beginning. I created a file in the localwampserver running directory, wrote Curl requests in it, and conducted simulated request tests, but every time Each interface requires different parameters. 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:
Online Tools, Apizza, etc. I looked at them and they all do a good job. They are 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.
Ever since, 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 don’t have to consider security issues and can evaluate the results. Convert as you like. 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
request parameters are passed here, and only GET and POST are used for request methods.
<meta> <meta> <title>API接口请求表单</title> <style> .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> <p> </p>
2. Data Processing file post.php
Receive the data passed by the post.html page, and Send a request and then process the request result. All the body request parameters are passed from the front-end page. If you still need Header parameters, you can add them manually in this file.<?php echo '<title>API接口请求响应'; /** * 设置网络请求配置 * @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='GET',$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 == 'POST'){ 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}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\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['REQUEST_METHOD'] != 'POST') exit('请求方式错误!'); //发送请求 function curl_query(){ $data = array( $_POST['key1'] => $_POST['value1'], $_POST['key2'] => $_POST['value2'], $_POST['key3'] => $_POST['value3'], $_POST['key4'] => $_POST['value4'], $_POST['key5'] => $_POST['value5'], $_POST['key6'] => $_POST['value6'] ); //数组去空 $data = array_filter($data); //post请求的参数 if(empty($data)) exit('请填写参数'); $url = $_POST['curl']; //API接口 if(!checkUrl($url)) exit('链接格式错误'); //检查连接的格式 $is_https = check_https($url); //是否是HTTPS请求 $method = $_POST['method']; //请求方式(GET POST) $header = array(); //携带header参数 //$header[] = 'Cache-Control: max-age=0'; //$header[] = 'Connection: keep-alive'; if($method == 'POST'){ $res = ihttp_request($url,$is_https,$method,$header,$data); print_r(json_decode($res,true)); }else if($method == 'GET'){ $curl = $url.'?'.http_build_query($data); //GET请求参数拼接 $res = ihttp_request($curl,$is_https,$method,$header); print_r(json_decode($res,true)); }else{ exit('error request method'); } } curl_query(); ?>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. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
Access directory service permissions of phpstudy2018
ThinkPHP Detailed explanation of the process tutorial for implementing WeChat payment (jsapi payment) _php example
The above is the detailed content of How to test API interface locally. For more information, please follow other related articles on the PHP Chinese website!

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
