0
0
Prompt Engineering / GenAIml~20 mins

Why API access enables integration in Prompt Engineering / GenAI - Experiment to Prove It

Choose your learning style9 modes available
Experiment - Why API access enables integration
Problem:You want to use a powerful AI model in your own app or website, but you don't know how to connect your app with the AI model easily.
Current Metrics:No integration yet, so no AI features in your app.
Issue:Without API access, it is hard to connect your app to the AI model, making it impossible to use AI features dynamically.
Your Task
Learn how API access allows your app to send requests to the AI model and get responses, enabling smooth integration.
Use only the provided API endpoint and key.
Do not modify the AI model itself.
Keep the integration simple and clear.
Hint 1
Hint 2
Hint 3
Solution
Prompt Engineering / GenAI
import requests

# Define the API endpoint and your API key
api_url = 'https://api.example-ai.com/v1/generate'
api_key = 'your_api_key_here'

# Prepare the input data
input_text = 'Explain why API access enables integration in simple words.'

# Set headers including the API key for authorization
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}

# Prepare the JSON payload
payload = {
    'prompt': input_text,
    'max_tokens': 50
}

# Send POST request to the API
response = requests.post(api_url, headers=headers, json=payload)

# Check if the request was successful
if response.status_code == 200:
    result = response.json()
    # Extract the generated text from the response
    generated_text = result.get('choices', [{}])[0].get('text', '')
    print('AI Response:', generated_text)
else:
    print('API request failed with status code:', response.status_code)
Added code to send a request to the AI model using API endpoint.
Included API key in headers for authorization.
Prepared input prompt and sent it as JSON payload.
Handled the response to extract and print AI-generated text.
Results Interpretation

Before: No AI features in the app because no connection to AI model.

After: App sends requests to AI model via API and receives responses, enabling AI-powered features.

API access acts as a bridge allowing your app to communicate with AI models easily, making integration possible without changing the AI itself.
Bonus Experiment
Try integrating the API call into a simple web page using JavaScript fetch to show AI responses live.
💡 Hint
Use fetch() with the same API endpoint and handle JSON response to update the page content dynamically.