I want to load a WMS with PyQGIS. I know this is possible on version 2.18 If it is done with the graphical Interface by checking on the **Use contextual WMS legend** [![Load WMS and its legend from QGIS Graphical Interface][1]][1] Now I manage to load a WMS with PyQGIS but I can not figure how to load the WMS and its legend. Below there is partial working code snippet: urlWithParams = "url=http://localhost:8080/geoserver/sf/wms&format=image/png&layers=sfdem&styles=&crs=EPSG:26713" rlayer = QgsRasterLayer(urlWithParams, 'testing', 'wms') rlayer.isValid() QgsMapLayerRegistry.instance().addMapLayer(rlayer) [1]: https://i.sstatic.net/qHzqT.png