Hands-On Activity: Your First API Call

Create an API call using the OpenAI API.

With a solid understanding of the OpenAI API and its documentation, we're ready to make our first API call. By "making the first API call," we mean instructing the OpenAI systems to execute a specified task. These tasks can vary, from generating text and answering questions to completing phrases and much more. In this section, we'll look at the steps required to make that first API call, guiding us through our initial interaction with OpenAI. The notion of "communicating" with OpenAI will transition from a mere concept to a tangible skill you'll acquire.

When it comes to OpenAI, the API call is how we interact with the powerful models it offers. We will first make an API call describing our task and in return, the system will process our request and the model will provide an output that is provided to us.

Components of an API call

An API call primarily consists of three main components. Here are the components as they apply to the OpenAI API.

  1. Endpoint: This designates where the request is directed. It specifies which part of OpenAI we wish to access. For instance, if we aim to generate text, we would utilize the "Completion" endpoint, which is the most frequently used.

  2. Headers: These accompany our API call, providing directives to the system about how the request should be processed. Notably, our API key, which authenticates our request, is included in the headers.

  3. Body: Often regarded as the core message of our call, the body provides detailed instructions. If the endpoint is the address and the header offers directives, then the body is the primary content. Within the context of OpenAI, the body will specify:

    1. The model we wish to employ.

    2. The prompt or question we're posing.

    3. The maximum number of tokens we aim to generate.

Making our first API call

You can implement the steps in the code widget below.

Step 1: Create an OpenAI account

You should already have an OpenAI Account and an API key.

Step 2: Import the OpenAI library

In our Python file, import the OpenAI library and the secret key using the following code (note that this method of using an API key is specific to the Educative platform):

Get hands-on with 1200+ tech skills courses.