How to create an array in OpenAPI with 3 elements and 2 enums

Abstract: Define an OpenAPI array with exactly three items where each element is restricted to specific enum values using minItems, maxItems, and items constraints.

Created: 2026-10-24 by
To define an array in OpenAPI with exactly three items where two are enum values, you must use the items keyword inside a type: array definition. The structure requires specifying minItems: 3 and maxItems: 3 to enforce the length constraint. For the enum elements, you can either reference a shared $ref or define inline enum lists within a oneOf or anyOf construct depending on whether the enums share the same type or distinct schemas. This approach ensures strict validation of both the collection size and the specific allowed values for each position if necessary.

Understanding Array Constraints in OpenAPI

OpenAPI (formerly Swagger) provides robust tools for validating request and response bodies. When dealing with arrays, the primary keywords are type, items, minItems, and maxItems. To create an array that holds exactly three elements, you set both minimum and maximum item counts to 3. This prevents clients from sending arrays with fewer or more than the required number of items. The challenge arises when you need specific elements within that array to be enums. In standard JSON Schema, which OpenAPI uses, the items keyword applies a single schema to all elements in the array. This means every element must match the same type and constraints. If you need different enums for different positions, you cannot simply list them under a single items object. Instead, you must use advanced schema composition techniques like prefixItems (in Draft 2020-12) or tuple validation logic. For most common use cases involving simple enums, users often mean that the array contains items that are drawn from a set of enum values. If all three elements are of the same type but restricted to specific enum values, the solution is straightforward. You define the items with an enum list. However, if the requirement implies that the first two items must be from one enum and the third from another, or if they are distinct types, the schema becomes more complex. We will cover the most common scenario first: an array of identical enum types.

Defining a Simple Enum Array

If your goal is to have an array of three strings, where each string must be one of two possible values (e.g., "active" or "inactive"), you can define this directly. This is the simplest interpretation of "2 enums" if it means two possible values.
components:
  schemas:
    StatusArray:
      type: array
      minItems: 3
      maxItems: 3
      items:
        type: string
        enum:
          - active
          - inactive
In this example, the items schema defines that every element in the array must be a string and must be either "active" or "inactive". The minItems and maxItems ensure the array has exactly three entries. This is valid OpenAPI 3.0 and 3.1 compliant syntax. It is clear, concise, and easy to understand for developers consuming the API. If you are working with integer enums, the process is identical, just changing the type to integer. For instance, if you have status codes 1 and 2, you would list those integers in the enum block. This method is ideal when the order of elements does not matter, and any combination of the allowed values is acceptable across the three slots.

Handling Distinct Enums per Position

Sometimes, "2 enums" might imply that the array contains items of different types or distinct enum sets at specific indices. For example, the first item might be a string enum, the second an integer enum, and the third a boolean. OpenAPI 3.0 does not natively support tuple validation in the same way JSON Schema Draft 2020-12 does with prefixItems. However, you can simulate this using allOf or by defining separate schemas for each position and combining them in a description, though true validation requires client-side checks or stricter server-side logic. A more robust way to handle mixed types in OpenAPI 3.0 is to use a union type if supported by your validator, or to define a single object that contains these fields if the order is fixed. But if you strictly need an array, you might define the items as anyOf containing the different schemas. This allows any item to be any of the defined types, which is less strict than positional enforcement.
components:
  schemas:
    MixedArray:
      type: array
      minItems: 3
      maxItems: 3
      items:
        anyOf:
          - $ref: '#/components/schemas/StringEnum'
          - $ref: '#/components/schemas/IntEnum'
This approach allows flexibility but sacrifices positional precision. If you need precise control over which enum goes where, consider restructuring your API to use an object with named properties instead of an array. Arrays are best for homogeneous data. If you must use an array, ensure your backend validation enforces the positional rules after parsing the JSON.

Common Pitfalls and Validation

When implementing these schemas, ensure your API gateway or validation library supports the specific version of OpenAPI you are using. Some older validators may not fully support minItems and maxItems together, or may mishandle enum constraints. Always test your schema with a tool like Swagger Editor or OpenAPI Validator. Another common issue is confusing enum with const. Use enum when there are multiple allowed values. Use const if the value is fixed for all items, which is rare in array contexts unless you are creating a constant-length array of identical constants. For related technical challenges, such as managing access controls or debugging terminal issues, see Remove Sharing Restriction: A Step-by-Step Guide and TTY doesn't go up: Common tech support issues. These resources provide broader context on system configuration and troubleshooting.

Frequently Asked Questions

Can I use different enums for each index in an array?

OpenAPI 3.0 does not support positional validation for array items directly. You must use anyOf or oneOf in the items schema, which allows any item to be any of the specified types. For strict positional validation, consider using an object with named fields instead of an array.

What happens if I send an array with only 2 items?

The API will reject the request with a 400 Bad Request error. The minItems: 3 constraint ensures that the payload must contain at least three elements. The validation engine checks the array length before checking the item types.

How do I define an enum for integers?

Set the type to integer inside the items schema and list the allowed integer values in the enum array. For example, enum: [1, 2] allows only the integers 1 and 2 as valid values for each item in the array.

Is it better to use an object or an array for fixed data?

An object is generally better for fixed data with distinct meanings per field, as it allows named properties. Arrays are suited for ordered collections of similar items. Using an array for distinct enums can lead to ambiguity and harder-to-maintain code.

Do I need OpenAPI 3.1 for prefixItems?

Yes, prefixItems is a feature introduced in JSON Schema Draft 2020-12, which OpenAPI 3.1 adopts. OpenAPI 3.0 relies on older JSON Schema drafts that do not include prefixItems, so you must use workarounds like anyOf or restructure the data.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More