Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

OpenAI API: Request Structure

Description

Understanding the structure of API requests is crucial for interacting effectively with the OpenAI API. This tutorial covers the components and formatting required in your requests.

HTTP Methods

HTTP methods define the type of action the request wishes to perform. The commonly used methods are:

  • GET: Retrieve data from the server.
  • POST: Submit data to the server to create or update resources.
  • PUT: Update an existing resource.
  • DELETE: Remove a resource from the server.

Example of a POST request:

POST /v1/engines/davinci/completions HTTP/1.1
Host: api.openai.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{ "prompt": "Once upon a time", "max_tokens": 50 }

Request Headers

Headers provide additional information about the request, such as authentication credentials, content type, and more. Required headers often include:

  • Authorization: API key or token to authenticate the request.
  • Content-Type: Specifies the format of the data being sent (e.g., JSON).

Example headers:

Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

Request Body

The request body carries data necessary for the API to process. It's commonly used with POST and PUT requests to send JSON or other formats.

Example JSON request body:

{ "prompt": "Once upon a time", "max_tokens": 50 }

Query Parameters

Query parameters allow you to filter, sort, or paginate responses from the API. They are usually added to the URL after a question mark (?) and separated by ampersands (&).

Example URL with query parameters:

GET /v1/engines/davinci/completions?prompt=Once%20upon%20a%20time&max_tokens=50

Conclusion

Mastering the request structure is fundamental to leveraging the OpenAI API effectively. It ensures that your requests are properly formatted and include all necessary components for successful interaction.