Magento 2 introduced Service Contracts. Those are a great way to use the Magento API without really worrying how things are implemented. Here is how to use them to create product attributes (including ones with options, attribute groups and attribute sets.

As an example is often the best explaination, a fully working module is available here.

This module does the following:

  • Import a fixtures CSV file containing attribute info to be imported into Magento
  • Create the related attributes, attribute groups and attribute sest
  • Add options to the attributes that require them (especially for select and multiselect attributes)

The code of the module is highly commented and architectured in a way that allows you to pick some methods that you may need for your own project.

  • Need to create a single attribute set? Look at the createAttributeSet method.
  • Need to create a single attribute? Look at the createAttribute method.
  • Need to create a single attribute group? Look at the createAttributeGroup method.
  • Need to assign an attribute to an attribute set? Look at the assignAttribute method.
  • Need to add options to an attribute? Look at the addOptionsToAttribute method.
  • Need to import a bunch of attributes and create all the necessary groups and sets? Look at the whole \Herve\ProductAttributes\Setup\InstallData class.