The OpenAI API lets a Python application send a request to a model and read its response. ChatGPT is the user-facing application; API access is a separate developer service. This guide explains authentication, a Python environment and the request-response flow.
The code below uses the Chat Completions interface and preserves the original GPT-3.5 example. OpenAI recommends the Responses API for new text-generation applications. Use this walkthrough to understand the existing code rather than selecting its older model by default.
We will create an API key, install the Python SDK, send a question and extract the answer text. The captured output and screenshots belong to the original example. Check the model lifecycle before running it: the legacy GPT-3.5 aliases used here are scheduled for shutdown on October 23, 2026.
1. Prerequisites
You need API access, a supported Python version and a code editor. Check the installed SDK’s Python requirement; the original Python 3.7 baseline below is historical and does not describe current SDK support.
- A Python release supported by your installed OpenAI SDK
- An OpenAI API key, which can be obtained by signing up for an OpenAI account
- A code editor, such as PyCharm (recommended), to write and run Python code
2. Obtaining an OpenAI API Key
The OpenAI API exposes models through authenticated HTTP endpoints. The Python SDK builds those requests and returns typed response objects. Your application supplies the input and decides what to do with the output.
Typical uses include answering questions, classification, extraction and summarization. A first successful response proves connectivity, not accuracy for your task. Choose the model and add evaluation examples before relying on it in an application.
An API key authenticates requests for a project or account. Requests may incur API charges; a ChatGPT subscription does not by itself provide an API usage budget. Review project billing and limits before experimenting.
Open the OpenAI Platform, select the intended project and find its API key settings. The screenshot shows the earlier interface, so navigation labels may differ.
Create a key with only the permissions needed for the application. Keep key management separate from usage monitoring and billing, which have their own project pages.
Create a new secret key in the selected project. The screenshot below illustrates the original key-creation screen:

Copy the secret when it is shown and store it securely. Set OPENAI_API_KEY in the process environment for this example. Do not embed the value in source, commit it to Git or send it to a browser client; revoke it if exposed.
3. Setting Up the Python Development Environment
Set up Python and an isolated project environment before installing the SDK. The steps below use PyCharm, but a terminal and another editor work too. An IDE is convenient rather than required.
- Installing Python
- Installing the PyCharm IDE
- Installing pip
- Setting up a virtual environment
- Installing the required Python packages
3.1. Installing Python
Install a Python release supported by your chosen SDK from python.org. Verify the interpreter your project actually uses, especially when several Python installations are present.
3.2. Installing PyCharm IDE
Choose an editor you are comfortable with. PyCharm provides an interpreter selector, terminal and debugger, which are useful when learning the request flow.
Install PyCharm from the JetBrains download page. Product packaging may differ from the older screenshots; any supported setup that runs your project interpreter is sufficient.
3.3. Setting Up a Python Virtual Environment
A virtual environment keeps this project’s Python packages separate from other projects. Create one in the project directory, select it as the interpreter and install openai into that environment.
PyCharm can create and select the virtual environment when you create a project. Confirm the interpreter path rather than relying only on a default selection.

The environment directory contains its own interpreter and installed packages. Its presence alone does not prove the terminal is using it; check the selected interpreter before installing dependencies.
3.4 The pip Package Installer
pip installs Python packages. Using python -m pip helps tie the installer to the interpreter selected for the project.
Check the selected interpreter with python -m pip --version. The reported path should correspond to the project environment.
If that interpreter has no pip, follow the official Python packaging installation instructions. The older installation example below is retained for context; use the method supported by your Python distribution.
- Download the get-pip.py script from the official Python website: https://bootstrap.pypa.io/get-pip.py.
- Save the file to a location on your computer, such as your desktop or downloads folder.
- Open a command prompt or terminal and navigate to the directory where you saved the get-pip.py file.
- Execute the following command in the terminal to install pip: python get-pip.py
- Once the installation is complete, you can verify that pip is installed by typing pip into the command prompt or terminal and pressing Enter.
Once pip works in the project environment, install the SDK there so imports and execution use the same interpreter.
4. Getting Started with ChatGPT API
Create the project and open a terminal using its virtual environment. Install the SDK with the command below, then confirm that OPENAI_API_KEY is available to the process that runs your script.
pip install openai
The original program creates an OpenAI client, builds messages, calls Chat Completions and prints the returned object. Use a model available to your account and verify its supported parameters before running a request.
- Create a new Python file in your PyCharm project.
- In the file, import the openai library. Also, you’ll need to provide your OpenAI API key.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY")
)
- Ask the user for a question using the input() function. The input() function is used to prompt the user to input a question they would like to ask the ChatGPT API. When the user types their question and presses Enter the input() function will return the string that the user typed. This string is then assigned to the question variable.
question = input("Ask me anything: ")
- Send the question through
client.chat.completions.create()in this historical example. Themodelselects the backend model,temperaturecontrols sampling where supported,max_tokenslimits generated output,nrequests alternatives andstopsupplies optional stopping sequences. Parameter ranges and support depend on the model; the context window is a separate limit. - The function returns a JSON object containing the generated response from the ChatGPT API which then can be accessed and printed to the console in the next line of code:
response = client.chat.completions.create(
messages=[
{
"role": "user",
"content": question
}
],
model="gpt-3.5-turbo",
temperature=0,
max_tokens=1024,
n=1,
stop=None
)
print(response)
Here is the original program. Its model selection is historical, as explained above; the environment-variable key pattern avoids placing a secret in the file.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY")
)
question = input("Ask me anything: ")
response = client.chat.completions.create(
messages=[
{
"role": "user",
"content": question
}
],
model="gpt-3.5-turbo",
temperature=0,
max_tokens=1024,
n=1,
stop=None
)
print(response)
5. Run the Program
Run app.py with the project interpreter. In PyCharm, use the file’s Run action and check that the run configuration includes the required environment variable.
The program first prompts for a question. If authentication or model availability fails after submission, inspect the API error before retrying.

After you enter a question, the original example prints a ChatCompletion object. The captured response below illustrates its structure; your model, response identifiers, usage and wording will differ.
ChatCompletion (id='chatcmpl-8TRL77QbIuITjDXKpR5DJGs0jLoaw', choices=[Choice(finish_reason='stop',
index=0, message=ChatCompletionMessage(content="Sure, here's a classic one for you:\n\nWhy don't scientists trust atoms?\n\nBecause they make up everything!",
role='assistant', function_call=None, tool_calls=None))], created=1702027297,
model='gpt-3.5-turbo-0613', object='chat.completion', system_fingerprint=None,
usage=CompletionUsage(completion_tokens=23, prompt_tokens=11, total_tokens=34))
The following fields describe the captured non-streaming response:
- The choices field contains an array of objects with the generated responses, which in this case only contains one response object as the parameter n=1.
- The message field within the response object contains the actual response generated by the GPT model.
finish_reasonexplains why generation ended. A value ofstopmeans a normal stopping condition, whilelengthindicates an output limit. It does not establish that the answer is correct.- The created field specifies the Unix timestamp of when the response was created.
ididentifies this completion resource.modelidentifies the model that produced the response.objectidentifies the response resource type; the captured Chat Completions response useschat.completion.- The usage field provides information about the resource usage of the API request. It contains information about the number of tokens used for the completion, the number of tokens in the prompt, and the total number of tokens used.
For a normal text answer in this example, read choices[0].message.content. The response object also contains metadata and usage, which are useful for diagnostics and cost tracking.
answer = response.choices[0].message.content
print(answer)

This accessor retrieves message text when it is present. Other responses can contain tool calls or no text, and output limits can truncate an answer. Check the response type and finish reason before treating it as a complete answer.
6. Summary
The essential workflow is small: authenticate with an environment-variable key, use the intended Python interpreter, send a request and inspect both the output and metadata. For a new project, follow the current Responses API guide and choose a supported model. The preserved Chat Completions example explains the older application flow.
Happy Learning !!