Chapter 2: Getting Started as a Developer
Practical Exercises Chapter 2
Now that you’ve learned how to create your OpenAI account, generate your API key, set up your development environment, explore the documentation, and secure your credentials, it’s time to get hands-on.
Complete the following exercises to solidify your knowledge and prepare for more advanced development in the upcoming chapters.
Exercise 1: Create Your OpenAI API Key
Go to https://platform.openai.com/account/api-keys and generate a new secret API key.
Name it something descriptive like openai-dev-key
.
Copy the key somewhere safe (or store it in a .env
file).
✳️ No code required for this task, but it’s essential to complete before the next exercises.
Exercise 2: Make Your First API Call Using Python
Write a Python script that sends a prompt to the GPT-4o model asking for a motivational quote.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Give me a short motivational quote for developers."}
]
)
print(response["choices"][0]["message"]["content"])
Run this in your terminal and make sure the response appears in your console.
Exercise 3: Try the Same Prompt in Postman
Use Postman to recreate the previous Python request to GPT-4o.
Steps:
- Open Postman and create a new
POST
request. - Use this URL:
https://api.openai.com/v1/chat/completions
- Under the Headers tab, add:
Authorization
:Bearer your-api-key-here
Content-Type
:application/json
- In the Body tab, choose “raw” and “JSON”, then paste this:
{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Give me a short motivational quote for developers." }
]
}
- Press Send and review the response.
This is an excellent way to experiment with prompt inputs visually.
Exercise 4: Use Node.js to Call the GPT-4o Model
If you're more comfortable in JavaScript, send a GPT-4o prompt using Node.js.
Solution:
require('dotenv').config();
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function run() {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a random historical fact." }
]
});
console.log(response.choices[0].message.content);
}
run();
Save your API key in a .env
file, run the script, and see the result.
Exercise 5: Secure Your API Key Properly
Move your API key into a .env file and refactor your script (Python or Node.js) to load the key from the environment variable.
Python .env
Setup Example:
# .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxx
# Python code (snippet)
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
This will prevent accidental sharing of sensitive data.
Exercise 6: Explore the Documentation
Head over to https://platform.openai.com/docs and locate the following:
- The endpoint used for Chat Completions
- Parameters you can use (like
temperature
,max_tokens
) - Sample code for calling the Chat API in Python and curl
Bonus Challenge: Try changing the temperature value in your script and see how it affects the creativity of the response.
Exercise 7: Test a Curl Command
Run the following curl command in your terminal (replace YOUR_API_KEY):
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Explain how rainbows are formed." }
]
}'
You’ll get a JSON response from the model. Try changing the user prompt and sending it again.
Exercise 8: Create a Multi-Environment Setup
Modify your Python script to support different environments (dev vs. prod) and switch API keys accordingly.
Solution:
import os
from dotenv import load_dotenv
import openai
load_dotenv()
ENVIRONMENT = os.getenv("ENV", "development")
if ENVIRONMENT == "production":
openai.api_key = os.getenv("OPENAI_API_KEY_PROD")
else:
openai.api_key = os.getenv("OPENAI_API_KEY_DEV")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "What’s the difference between development and production environments?"}
]
)
print(response["choices"][0]["message"]["content"])
Try setting the environment variable ENV
to "production" and see how the script switches keys.
These exercises are designed to help you gain confidence not just in calling the API, but in managing it the way professionals do. If you completed all of them—great job! You’re officially set up and ready to build real, useful applications.
You're very welcome! Here’s the Chapter Summary for Chapter 2: Getting Started as a Developer, written in a warm, instructional tone that maintains the clarity and depth of the rest of the book—while naturally exceeding 380 words to give the reader a strong sense of closure and confidence.
Practical Exercises Chapter 2
Now that you’ve learned how to create your OpenAI account, generate your API key, set up your development environment, explore the documentation, and secure your credentials, it’s time to get hands-on.
Complete the following exercises to solidify your knowledge and prepare for more advanced development in the upcoming chapters.
Exercise 1: Create Your OpenAI API Key
Go to https://platform.openai.com/account/api-keys and generate a new secret API key.
Name it something descriptive like openai-dev-key
.
Copy the key somewhere safe (or store it in a .env
file).
✳️ No code required for this task, but it’s essential to complete before the next exercises.
Exercise 2: Make Your First API Call Using Python
Write a Python script that sends a prompt to the GPT-4o model asking for a motivational quote.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Give me a short motivational quote for developers."}
]
)
print(response["choices"][0]["message"]["content"])
Run this in your terminal and make sure the response appears in your console.
Exercise 3: Try the Same Prompt in Postman
Use Postman to recreate the previous Python request to GPT-4o.
Steps:
- Open Postman and create a new
POST
request. - Use this URL:
https://api.openai.com/v1/chat/completions
- Under the Headers tab, add:
Authorization
:Bearer your-api-key-here
Content-Type
:application/json
- In the Body tab, choose “raw” and “JSON”, then paste this:
{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Give me a short motivational quote for developers." }
]
}
- Press Send and review the response.
This is an excellent way to experiment with prompt inputs visually.
Exercise 4: Use Node.js to Call the GPT-4o Model
If you're more comfortable in JavaScript, send a GPT-4o prompt using Node.js.
Solution:
require('dotenv').config();
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function run() {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a random historical fact." }
]
});
console.log(response.choices[0].message.content);
}
run();
Save your API key in a .env
file, run the script, and see the result.
Exercise 5: Secure Your API Key Properly
Move your API key into a .env file and refactor your script (Python or Node.js) to load the key from the environment variable.
Python .env
Setup Example:
# .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxx
# Python code (snippet)
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
This will prevent accidental sharing of sensitive data.
Exercise 6: Explore the Documentation
Head over to https://platform.openai.com/docs and locate the following:
- The endpoint used for Chat Completions
- Parameters you can use (like
temperature
,max_tokens
) - Sample code for calling the Chat API in Python and curl
Bonus Challenge: Try changing the temperature value in your script and see how it affects the creativity of the response.
Exercise 7: Test a Curl Command
Run the following curl command in your terminal (replace YOUR_API_KEY):
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Explain how rainbows are formed." }
]
}'
You’ll get a JSON response from the model. Try changing the user prompt and sending it again.
Exercise 8: Create a Multi-Environment Setup
Modify your Python script to support different environments (dev vs. prod) and switch API keys accordingly.
Solution:
import os
from dotenv import load_dotenv
import openai
load_dotenv()
ENVIRONMENT = os.getenv("ENV", "development")
if ENVIRONMENT == "production":
openai.api_key = os.getenv("OPENAI_API_KEY_PROD")
else:
openai.api_key = os.getenv("OPENAI_API_KEY_DEV")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "What’s the difference between development and production environments?"}
]
)
print(response["choices"][0]["message"]["content"])
Try setting the environment variable ENV
to "production" and see how the script switches keys.
These exercises are designed to help you gain confidence not just in calling the API, but in managing it the way professionals do. If you completed all of them—great job! You’re officially set up and ready to build real, useful applications.
You're very welcome! Here’s the Chapter Summary for Chapter 2: Getting Started as a Developer, written in a warm, instructional tone that maintains the clarity and depth of the rest of the book—while naturally exceeding 380 words to give the reader a strong sense of closure and confidence.
Practical Exercises Chapter 2
Now that you’ve learned how to create your OpenAI account, generate your API key, set up your development environment, explore the documentation, and secure your credentials, it’s time to get hands-on.
Complete the following exercises to solidify your knowledge and prepare for more advanced development in the upcoming chapters.
Exercise 1: Create Your OpenAI API Key
Go to https://platform.openai.com/account/api-keys and generate a new secret API key.
Name it something descriptive like openai-dev-key
.
Copy the key somewhere safe (or store it in a .env
file).
✳️ No code required for this task, but it’s essential to complete before the next exercises.
Exercise 2: Make Your First API Call Using Python
Write a Python script that sends a prompt to the GPT-4o model asking for a motivational quote.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Give me a short motivational quote for developers."}
]
)
print(response["choices"][0]["message"]["content"])
Run this in your terminal and make sure the response appears in your console.
Exercise 3: Try the Same Prompt in Postman
Use Postman to recreate the previous Python request to GPT-4o.
Steps:
- Open Postman and create a new
POST
request. - Use this URL:
https://api.openai.com/v1/chat/completions
- Under the Headers tab, add:
Authorization
:Bearer your-api-key-here
Content-Type
:application/json
- In the Body tab, choose “raw” and “JSON”, then paste this:
{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Give me a short motivational quote for developers." }
]
}
- Press Send and review the response.
This is an excellent way to experiment with prompt inputs visually.
Exercise 4: Use Node.js to Call the GPT-4o Model
If you're more comfortable in JavaScript, send a GPT-4o prompt using Node.js.
Solution:
require('dotenv').config();
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function run() {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a random historical fact." }
]
});
console.log(response.choices[0].message.content);
}
run();
Save your API key in a .env
file, run the script, and see the result.
Exercise 5: Secure Your API Key Properly
Move your API key into a .env file and refactor your script (Python or Node.js) to load the key from the environment variable.
Python .env
Setup Example:
# .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxx
# Python code (snippet)
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
This will prevent accidental sharing of sensitive data.
Exercise 6: Explore the Documentation
Head over to https://platform.openai.com/docs and locate the following:
- The endpoint used for Chat Completions
- Parameters you can use (like
temperature
,max_tokens
) - Sample code for calling the Chat API in Python and curl
Bonus Challenge: Try changing the temperature value in your script and see how it affects the creativity of the response.
Exercise 7: Test a Curl Command
Run the following curl command in your terminal (replace YOUR_API_KEY):
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Explain how rainbows are formed." }
]
}'
You’ll get a JSON response from the model. Try changing the user prompt and sending it again.
Exercise 8: Create a Multi-Environment Setup
Modify your Python script to support different environments (dev vs. prod) and switch API keys accordingly.
Solution:
import os
from dotenv import load_dotenv
import openai
load_dotenv()
ENVIRONMENT = os.getenv("ENV", "development")
if ENVIRONMENT == "production":
openai.api_key = os.getenv("OPENAI_API_KEY_PROD")
else:
openai.api_key = os.getenv("OPENAI_API_KEY_DEV")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "What’s the difference between development and production environments?"}
]
)
print(response["choices"][0]["message"]["content"])
Try setting the environment variable ENV
to "production" and see how the script switches keys.
These exercises are designed to help you gain confidence not just in calling the API, but in managing it the way professionals do. If you completed all of them—great job! You’re officially set up and ready to build real, useful applications.
You're very welcome! Here’s the Chapter Summary for Chapter 2: Getting Started as a Developer, written in a warm, instructional tone that maintains the clarity and depth of the rest of the book—while naturally exceeding 380 words to give the reader a strong sense of closure and confidence.
Practical Exercises Chapter 2
Now that you’ve learned how to create your OpenAI account, generate your API key, set up your development environment, explore the documentation, and secure your credentials, it’s time to get hands-on.
Complete the following exercises to solidify your knowledge and prepare for more advanced development in the upcoming chapters.
Exercise 1: Create Your OpenAI API Key
Go to https://platform.openai.com/account/api-keys and generate a new secret API key.
Name it something descriptive like openai-dev-key
.
Copy the key somewhere safe (or store it in a .env
file).
✳️ No code required for this task, but it’s essential to complete before the next exercises.
Exercise 2: Make Your First API Call Using Python
Write a Python script that sends a prompt to the GPT-4o model asking for a motivational quote.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Give me a short motivational quote for developers."}
]
)
print(response["choices"][0]["message"]["content"])
Run this in your terminal and make sure the response appears in your console.
Exercise 3: Try the Same Prompt in Postman
Use Postman to recreate the previous Python request to GPT-4o.
Steps:
- Open Postman and create a new
POST
request. - Use this URL:
https://api.openai.com/v1/chat/completions
- Under the Headers tab, add:
Authorization
:Bearer your-api-key-here
Content-Type
:application/json
- In the Body tab, choose “raw” and “JSON”, then paste this:
{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Give me a short motivational quote for developers." }
]
}
- Press Send and review the response.
This is an excellent way to experiment with prompt inputs visually.
Exercise 4: Use Node.js to Call the GPT-4o Model
If you're more comfortable in JavaScript, send a GPT-4o prompt using Node.js.
Solution:
require('dotenv').config();
const { OpenAI } = require('openai');
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function run() {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a random historical fact." }
]
});
console.log(response.choices[0].message.content);
}
run();
Save your API key in a .env
file, run the script, and see the result.
Exercise 5: Secure Your API Key Properly
Move your API key into a .env file and refactor your script (Python or Node.js) to load the key from the environment variable.
Python .env
Setup Example:
# .env file
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxx
# Python code (snippet)
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
This will prevent accidental sharing of sensitive data.
Exercise 6: Explore the Documentation
Head over to https://platform.openai.com/docs and locate the following:
- The endpoint used for Chat Completions
- Parameters you can use (like
temperature
,max_tokens
) - Sample code for calling the Chat API in Python and curl
Bonus Challenge: Try changing the temperature value in your script and see how it affects the creativity of the response.
Exercise 7: Test a Curl Command
Run the following curl command in your terminal (replace YOUR_API_KEY):
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Explain how rainbows are formed." }
]
}'
You’ll get a JSON response from the model. Try changing the user prompt and sending it again.
Exercise 8: Create a Multi-Environment Setup
Modify your Python script to support different environments (dev vs. prod) and switch API keys accordingly.
Solution:
import os
from dotenv import load_dotenv
import openai
load_dotenv()
ENVIRONMENT = os.getenv("ENV", "development")
if ENVIRONMENT == "production":
openai.api_key = os.getenv("OPENAI_API_KEY_PROD")
else:
openai.api_key = os.getenv("OPENAI_API_KEY_DEV")
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "What’s the difference between development and production environments?"}
]
)
print(response["choices"][0]["message"]["content"])
Try setting the environment variable ENV
to "production" and see how the script switches keys.
These exercises are designed to help you gain confidence not just in calling the API, but in managing it the way professionals do. If you completed all of them—great job! You’re officially set up and ready to build real, useful applications.
You're very welcome! Here’s the Chapter Summary for Chapter 2: Getting Started as a Developer, written in a warm, instructional tone that maintains the clarity and depth of the rest of the book—while naturally exceeding 380 words to give the reader a strong sense of closure and confidence.