如何用PHP/Python编写脚本整合GET与PUT API请求(替代Postman)
Solution: Combine GET and PUT API Calls in Python or PHP
I’ll provide both Python and PHP implementations to replicate your Postman workflow. Both scripts will first fetch the quantity via a GET request, then use that value in a PUT request with your specified XML payload.
Python Implementation (Using requests Library)
First, install the requests library if you haven’t already (pip install requests). This script is straightforward and handles both API calls with basic error handling:
import requests # Configuration - replace these with your actual API details GET_API_URL = "https://your-shop-url.com/api/stock_availables/271" PUT_API_URL = "https://your-shop-url.com/api/stock_availables/1445" PRESTASHOP_API_KEY = "your-api-key-here" def main(): try: # Step 1: Fetch quantity via GET request get_response = requests.get( GET_API_URL, auth=(PRESTASHOP_API_KEY, "") # PrestaShop uses API key as username, empty password ) get_response.raise_for_status() # Trigger error for HTTP status codes ≥400 # Parse JSON and extract the quantity stock_data = get_response.json() quantity = stock_data["stock_available"]["quantity"] print(f"Fetched quantity: {quantity}") # Step 2: Build XML payload with the extracted quantity xml_payload = f'''<?xml version="1.0" encoding="UTF-8"?> <prestashop xmlns:xlink="http://www.w3.org/1999/xlink"> <stock_available> <id>1445</id> <id_product>1406</id_product> <id_product_attribute>0</id_product_attribute> <id_shop>1</id_shop> <id_shop_group>0</id_shop_group> <quantity>{quantity}</quantity> <depends_on_stock>0</depends_on_stock> <out_of_stock>2</out_of_stock> <location></location> </stock_available> </prestashop>''' # Step 3: Send PUT request to update stock put_headers = {"Content-Type": "application/xml"} put_response = requests.put( PUT_API_URL, auth=(PRESTASHOP_API_KEY, ""), headers=put_headers, data=xml_payload ) put_response.raise_for_status() print("PUT request successful! Status code:", put_response.status_code) print("Response content:", put_response.text) except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") if __name__ == "__main__": main()
PHP Implementation (Using cURL)
This script uses PHP’s built-in cURL extension (no extra dependencies needed):
<?php // Configuration - replace these with your actual API details $getApiUrl = "https://your-shop-url.com/api/stock_availables/271"; $putApiUrl = "https://your-shop-url.com/api/stock_availables/1445"; $prestashopApiKey = "your-api-key-here"; // Step 1: Fetch quantity via GET request $ch = curl_init($getApiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, $prestashopApiKey . ":"); // API key as username, empty password curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $getResponse = curl_exec($ch); $getHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($getResponse === false || $getHttpCode >= 400) { die("GET request failed: " . curl_error($ch) . " (HTTP code: " . $getHttpCode . ")"); } curl_close($ch); // Parse JSON and extract quantity $stockData = json_decode($getResponse, true); $quantity = $stockData["stock_available"]["quantity"]; echo "Fetched quantity: " . $quantity . "\n"; // Step 2: Build XML payload with the extracted quantity $xmlPayload = <<<XML <?xml version="1.0" encoding="UTF-8"?> <prestashop xmlns:xlink="http://www.w3.org/1999/xlink"> <stock_available> <id>1445</id> <id_product>1406</id_product> <id_product_attribute>0</id_product_attribute> <id_shop>1</id_shop> <id_shop_group>0</id_shop_group> <quantity>$quantity</quantity> <depends_on_stock>0</depends_on_stock> <out_of_stock>2</out_of_stock> <location></location> </stock_available> </prestashop> XML; // Step 3: Send PUT request to update stock $ch = curl_init($putApiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, $prestashopApiKey . ":"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlPayload); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/xml", "Content-Length: " . strlen($xmlPayload) ]); $putResponse = curl_exec($ch); $putHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($putResponse === false || $putHttpCode >= 400) { die("PUT request failed: " . curl_error($ch) . " (HTTP code: " . $putHttpCode . ")"); } echo "PUT request successful! Status code: " . $putHttpCode . "\n"; echo "Response content: " . $putResponse . "\n"; curl_close($ch); ?>
Key Notes:
- Authentication: Both scripts include basic auth, which is standard for PrestaShop APIs. Replace
your-api-key-herewith your actual API key. - Endpoint URLs: Update the GET/PUT URLs to match your shop’s actual API endpoints.
- Error Handling: Basic error handling is included for HTTP failures—you can extend this to handle specific edge cases (like missing
quantityin the GET response) if needed. - XML Payload: The XML structure matches your Postman request exactly, with the dynamic
quantityvalue inserted.
内容的提问来源于stack exchange,提问作者Fbf




