没有ID的Grails API更新(PUT)

时间:2014-06-04 23:08:15

标签: json api grails curl http-put

我正在为我的Grails应用程序开发一个API,并尝试做一些非REST(虽然非常有用)。我正在尝试允许“显示”和“更新”操作接受ID 名称。我的URLMappings文件中有以下映射:

"/api/host" (controller:"API", action:"hostList", method:'GET', parseRequest:true)
"/api/host/$id" (controller:"API", action:"hostShow", method:'GET', parseRequest:true)
"/api/host/$id" (controller:"API", action:"hostUpdate", method:'PUT', parseRequest:true)   
"/api/host" (controller:"API", action:"hostCreate", method:'POST', parseRequest:true)

我想要的是让hostShow和hostUpdate控制器操作接受ID 名称作为$ id。使用Show操作可以正常工作,但是当我尝试使用HTTP-PUT时,我收到以下错误:

HTTP/1.1 422 Unprocessable Entity
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8   
{"errors":[{"object":"Host","field":"id","rejected-value":"TEST","message":"Property id must be a valid number"}]}

我似乎无法解决这个错误。我用来尝试执行此操作的CURL命令是:

curl -i -X PUT -H "Content-Type:application/json" -d "{name:NEWTEST}", http://localhost:8080/myapp/api/host/TEST

非常感谢任何反馈或帮助!以下是hostShow和hostUpdate操作的代码:

def hostShow() {
    def hostInstance
    try {
        hostInstance = Host.get(params.id)
    }
    catch(Exception E) {
        hostInstance = Host.findByHostname(params.id)
    }

    if(hostInstance == null)
        respond null, [status: HttpStatus.NOT_FOUND]

    respond hostInstance
}    

@Transactional
def hostUpdate() {
    // Convert incoming JSON to params structure
    request.JSON.each { k,v ->
        params[k] = v
    }    

    // Get by either ID or hostname
    def hostInstance
    try {
        hostInstance = Host.get(params.id)
    }
    catch(Exception E) {
        hostInstance = Host.findByHostname(params.id)
    }

    hostInstance.properties = params   // Set new properties
    hostInstance.save(flush:true)                 

    respond hostInstance, [status: HttpStatus.OK]
}

1 个答案:

答案 0 :(得分:0)

事实证明,这个代码的问题是给我错误的,而不是Grails或API机制本身的问题。

问题在于,当我设置hostInstance.properties = params时,它会尝试将hostInstance.id设置为params.id,在本例中为params.id。我解决了这个问题,即添加以下内容:

params.id = hostInstance.id   // <--- This line solves the problem
hostInstance.properties=params

感谢您的反馈,并抱歉用这么简单的错误提问(回想起来)。