How to create an Item per REST API?

I’ve tried to create a new Item in my OH2 System with the REST API Documentation.

I used a PUT to /rest/items/myTestItem
with the Body:
{
“type”: “string”,
“name”: “myTestItem”,
“label”: “Tester”
}

But instead of an 201, which says that the Item was created, I get an 400. which means that the Item is null.

Whats wrong with my Code?

I found my failure. It has to be type String mit upper S slight_smile:

Hi,

Can you post your complete code ?

We did as below but getting CORS error in browser as “Failed to load http://192.168.0.113:8181/rest/items/light25: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.”

Code:

$.ajax({
            url: 'http://192.168.0.113:8181/rest/items/light25',
            headers: {
            "Access-Control-Allow-Origin": "http://192.168.0.113", //"http://192.168.0.113", //http://foo.example
           "Access-Control-Allow-Methods": "*", //"POST, GET, OPTIONS",
           "Access-Control-Allow-Headers": "*" //"X-PINGOTHER, Content-Type"
	   
           //"Access-Control-Allow-Headers": "Content-Type",
	               },
            method: 'PUT',
            //Accept: 'application/json',
            data: {"type": "String","name": "Tueblight1"},
            contentType: 'application/json',
            dataType: 'json',
            success: function(data) {
                  alert('GET completed');
                  $("#resultsdiv").html(JSON.stringify(data));
            },
            error: function(data) { 
                  alert(JSON.stringify(data));
            } 
          });

Nevermind, we got it working as below.

$.ajax({

url: 'http://192.168.0.113:8181/rest/items/light013222',
method: 'PUT',
data: JSON.stringify({"type": "String","name": "light013222"}),
contentType: 'application/json',
dataType: 'json',
success: function(data) {
alert('PUT completed');
$("#resultsdiv").html(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});

Could it be that with openHAB 3.x this wouldn’t work?

I tried:

curl -0 -v -X PUT http://<ip>:8080/rest/items/myTestItem \
-H "Content-Type: text/plain" \
-H 'Accept: application/json' \
--data-binary @- << EOF
{
    "type": "String"
    "name": "myTestItem",
    "label": "tester"
}
EOF

Also I tried it with Postman. I am sure that the curl command should be fine, but maybe not the content.

I got

10:19:08.049 [WARN ] [rs.impl.WebApplicationExceptionMapper] - javax.ws.rs.ClientErrorException: HTTP 415 Unsupported Media Type
        at org.apache.cxf.jaxrs.utils.SpecExceptions.toHttpException(SpecExceptions.java:117)
        at org.apache.cxf.jaxrs.utils.ExceptionUtils.toHttpException(ExceptionUtils.java:168)
        at org.apache.cxf.jaxrs.utils.JAXRSUtils.findTargetMethod(JAXRSUtils.java:565)
        at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:182)
        at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:79)
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
        at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:265)
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
        at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
        at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:225)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:298)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPut(AbstractHTTPServlet.java:234)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:273)
        at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
        at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:550)
        at org.ops4j.pax.web.service.jetty.internal.HttpServiceServletHandler.doHandle(HttpServiceServletHandler.java:71)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
        at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:602)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:235)
        at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1624)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
        at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1434)
        at org.ops4j.pax.web.service.jetty.internal.HttpServiceContext.doHandle(HttpServiceContext.java:294)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
        at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:501)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1594)
        at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
        at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1349)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
        at org.ops4j.pax.web.service.jetty.internal.JettyServerHandlerCollection.handle(JettyServerHandlerCollection.java:82)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
        at org.eclipse.jetty.server.Server.handle(Server.java:516)
        at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:388)
        at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:633)
        at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:380)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
        at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105)
        at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173)
        at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131)
        at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:386)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:883)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1034)
        at java.base/java.lang.Thread.run(Thread.java:829)

Well at least I want to try it with Python… So here my “test” code:

import requests
from requests.auth import HTTPBasicAuth

base_url = "http://<ip>:8080/rest"
auth = HTTPBasicAuth('<user>', '<password>')
headers = {"Content-type": "text/plain"}

url = base_url + "/items/myTestItem"
data = {"type": "String", "name": "myTestItem", "label": "tester"}

try:
    response = requests.put(url, auth=auth, data=data, headers=headers, timeout=8)
    response.raise_for_status()
    print(response)
except requests.exceptions.HTTPError as errh:
    print(errh)
except requests.exceptions.ConnectionError as errc:
    print(errc)
except requests.exceptions.Timeout as errt:
    print(errt)
except requests.exceptions.RequestException as err:
    print(err)

For existing items I can work with GET, PUT and POST. I also use this in other use cases. Hence my assumption that I can no longer create new items in openHAB 3 via the REST API.

And at least I tried it with JSON:

import requests
from requests.auth import HTTPBasicAuth
import json

base_url = "http://<ip>:8080/rest"
auth = HTTPBasicAuth('<user>', '<password>')
headers = {"Content-type": "text/json", "Accept": "application/json"}

url = base_url + "/items/myTestItem"
data = {"type": "String", "name": "myTestItem", "label": "tester"}
data = json.dumps(data)

try:
    response = requests.put(url, auth=auth, data=data, headers=headers, timeout=8)
    response.raise_for_status()
    print(response)
except requests.exceptions.HTTPError as errh:
    print(errh)
except requests.exceptions.ConnectionError as errc:
    print(errc)
except requests.exceptions.Timeout as errt:
    print(errt)
except requests.exceptions.RequestException as err:
    print(err)

Okay, I found the solution on stackoverflow. It worked. You have to use Content-type: application/json and Accept: application/json.

Then following will work:

curl -0 -v -X PUT http://<ip>:8080/rest/items/myTestItem \
-u <USER_NAME>:<PASSWORD> \
-H "Content-Type: application/plain" \
-H 'Accept: application/json' \
--data-binary @- << EOF
{
    "type": "String"
    "name": "myTestItem",
    "label": "tester"
}
EOF

You have to replace <USER_NAME>:<PASSWORD> with the username and password of your openHAB account. You can’t create a new item without authentication.

The working Python script will be:

import requests
from requests.auth import HTTPBasicAuth
import json

base_url = "http://<ip>:8080/rest"
auth = HTTPBasicAuth('<user>', '<password>')
headers = {"Content-type": "application/json", "Accept": "application/json"}

url = base_url + "/items/myTestItem"
data = {"type": "String", "name": "myTestItem", "label": "tester"}
data = json.dumps(data)

try:
    response = requests.put(url, auth=auth, data=data, headers=headers, timeout=8)
    response.raise_for_status()
    print(response)
except requests.exceptions.HTTPError as errh:
    print(errh)
except requests.exceptions.ConnectionError as errc:
    print(errc)
except requests.exceptions.Timeout as errt:
    print(errt)
except requests.exceptions.RequestException as err:
    print(err)