AI models handle programming automation very well. Advanced prompt engineering techniques let you generate not just simple functions but complex program structures that can involve talking to databases, processing large volumes of data or working with APIs.
Task:
Automatically produce a Python script that talks to a REST API, including authorization and data retrieval.
Prompt:
Write a Python script that connects to a REST API using an authorization token, sends a GET request to fetch a list of users and saves the result as JSON in a file called 'users.json'.
Result:
import requests
import json
# Set the API URL
url = 'https://api.example.com/users'
# Set the authorization token
token = 'your_auth_token_here'
# Build the headers with the authorization token
headers = {
'Authorization': f'Bearer {token}'
}
# Send the GET request
response = requests.get(url, headers=headers)
# Check the response status
if response.status_code == 200:
# Parse the response as JSON
users = response.json()
# Save the result to 'users.json'
with open('users.json', 'w') as f:
json.dump(users, f, indent=4)
else:
print(f"Error: failed to fetch data. Status: {response.status_code}")Spell out every key detail in the prompt: the request type, whether authorization is needed and the storage format. That helps the model generate code that is as accurate and ready to use as possible.