Code Examples in Python, PHP, and Node.js
This section provides examples of how to make API requests to the Movies API in different programming languages.
Query
This is the same moviesByTitle
query shown in the Getting Started section. We will use this query in each of the programming language examples.
query {
moviesByTitle (title: "Forrest Gump") {
id
title
revenue
}
}
Python Example
Python example using requests
.
import requests
import json
api_key = "YOUR_API_KEY" # Replace with your actual API key
endpoint_url = "https://jh-data.com/moviesapi/"
headers = {
"Content-Type": "application/json",
"X-API-Key": api_key
}
query = """
query {
moviesByTitle (title: "Forrest Gump") {
id
title
revenue
}
}
"""
payload = {
"query": query
}
response = requests.post(endpoint_url, headers=headers, json=payload)
if response.status_code == 200:
json_response = response.json()
print(json.dumps(json_response, indent=2)) # Pretty print the JSON response
else:
print(f"Error: {response.status_code}")
print(response.text)
JavaScript/Node.js Example
Node.js example using fetch API (Node.js v18+ or with fetch polyfill).
const apiKey = "YOUR_API_KEY"; // Replace with your actual API key
const apiUrl = "https://jh-data.com/moviesapi/";
const graphqlQuery = {
query: `
query {
moviesByTitle (title: "Forrest Gump") {
id
title
revenue
}
}
`,
};
const headers = {
"Content-Type": "application/json",
"X-API-Key": apiKey,
};
fetch(apiUrl, {
method: "POST",
headers: headers,
body: JSON.stringify(graphqlQuery), // Convert GraphQL query to JSON string
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); // Handle HTTP errors
}
return response.json(); // Parse JSON response
})
.then((data) => {
// Pretty print the JSON response to the console for readability
console.log(JSON.stringify(data, null, 2));
})
.catch((error) => {
console.error("Error fetching data:", error); // Handle fetch errors
});
If you are using a Node.js version older than v18, you might need to install node-fetch (a polyfill for fetch) using npm
(npm install node-fetch
), and then import it at the top of your JavaScript file:
const fetch = require('node-fetch'); // Import fetch for older Node.js
PHP Example
Make sure the curl
extension is enabled in your PHP installation. It's usually enabled by default, but if not, you might need to uncomment or enable it in your php.ini configuration file (search for extension=curl).
<?php
$apiKey = "YOUR_API_KEY"; // Replace with your actual API key
$apiUrl = "https://jh-data.com/moviesapi/";
$graphqlQuery = [
"query" => <<<GRAPHQL
query {
moviesByTitle (title: "Forrest Gump") {
id
title
revenue
}
}
GRAPHQL
];
$headers = [
"Content-Type: application/json",
"X-API-Key: " . $apiKey,
];
$postData = json_encode($graphqlQuery); // Encode GraphQL query to JSON
// Initialize cURL session
$ch = curl_init($apiUrl);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string
curl_setopt($ch, CURLOPT_POST, true); // Set as POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); // Set JSON request body
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Set HTTP headers
// Execute cURL request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
$jsonResponse = json_decode($response, true); // Decode JSON response to PHP array
if ($jsonResponse === null && json_last_error() !== JSON_ERROR_NONE) {
echo 'JSON decode error: ' . json_last_error_msg();
} else {
echo "<pre>"; // Use <pre> for formatted output in HTML context if needed
print_r($jsonResponse); // Or var_dump($jsonResponse); for debugging
echo "</pre>";
}
} else {
echo "HTTP error! status: " . $httpCode . "\n";
echo "Response body:\n" . $response; // Output the response body for debugging
}
}
// Close cURL session
curl_close($ch);
?>