Creating a ArcGIS map service raster layer in PyQGIS

It’s relatively straightforward creating layers programatically in QGIS using PyQGIS. However, the documentation isn’t clear on how to use create a raster layer from a ArcGIS map service.

The list of raster providers can be found by searching for addRasterProviderDialog in qgsdatasourcemanagerdialog.cpp.

There are two mandatory parts to the data source string when specifying the ArcGIS map service, the url and layer, which need to be space separated. For example:

iface.addRasterLayer("url='' layer='5'", "Key road freight routes", "arcgismapserver")

or using the constructor:

layer = QgsRasterLayer("url='' layer='5'", "Key road freight routes", "arcgismapserver")

To understand what data source parameters are supported by the ArcGIS map service provider (AMSProvider), search for dataSource.Param in qgsamsprovider.cpp.