Adressing the REST API through Python

Recently I commented somewhere on how to use Python to address the REST Api. As that comment might not be easily to find (as the title was about something else), It seems best to put it in a separate posting.
There are 2wways to do it AFAIK:
1)
There is in fact a Python -openhab library (written bijthat allows you to read items and set them. (via the REST API) (I think from @sim0nx)
You will find the library here.
Supposedly it is only for openhab 1,but I just tried some stuff with openhab 2 and that works too.
Keep in mind that you after you set an Item with a python command, you also have to send a command to update the state in your openhab UI.
Suppose you have an item called ‘Spotlight’ that you want to turn on from within Python.
then you need to issue the commands:

sl=items.get('Spotlight')
sl.command('ON')
sl.state='ON

if you want to query the state, do that like:
print(sl.state)

‘sl’ is avariable that you have read the specific item into

-2)
Also, it is possible to work with the REST api without the before mentioned library.
Suppose your openhab ip=192.168.1.100
and you want to switch the item ‘Spotlight’ and or read the item ‘Spotlight’
You can do that as follows:

import requests
requests.put('http://192.168.1.100:8080/rest/items/Spotlight/state', 'ON')

g = requests.get('http://192.168.1.100:8080/rest/items/Spotlight/state')
data = g.content
print('Spotlight = '+data)
7 Likes