Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using cURL to Interact with OpenAI API

Introduction

This tutorial demonstrates how to use cURL to interact with the OpenAI API. cURL is a command-line tool for transferring data with URLs, allowing you to send requests and receive responses from various web services.

1. Setting Up cURL

Before you start, make sure you have cURL installed. You can check if cURL is installed by running the following command in your terminal:

curl --version
                    

If cURL is not installed, you can download and install it from the cURL website.

2. Sending a Request

To send a request to the OpenAI API, use the following cURL command. Replace YOUR_API_KEY with your actual OpenAI API key:

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "text-davinci-003",
    "prompt": "Translate English to French: Hello, how are you?",
    "max_tokens": 60
  }'
                    

3. Understanding the Request

Let's break down the cURL command:

  • curl https://api.openai.com/v1/completions: This specifies the endpoint URL for the API request.
  • -H "Content-Type: application/json": This sets the content type of the request to JSON.
  • -H "Authorization: Bearer YOUR_API_KEY": This sets the authorization header with your API key.
  • -d '{ ... }': This specifies the data to be sent in the request body.

4. Sending the Request

Run the cURL command in your terminal. You should see a response from the OpenAI API containing the requested completion.

5. Example Response

Here is an example of what the response might look like:

{
  "id": "cmpl-2dNXXbq2b9M8q",
  "object": "text_completion",
  "created": 1614639648,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "\n\nBonjour, comment ça va?",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 7,
    "total_tokens": 16
  }
}
                    

In this example, the response contains the translated text "Bonjour, comment ça va?".