2014-06-24 62 views
0

我很努力將操作鏈接導入我的資源以履行HATEOAS。REST中的動作鏈接將根據現有資源創建資源

我想創建一個基於現有資源的新資源,並且仍然實現一個合理的超媒體策略。在我的情況下,在通用服務器端作業隊列中追加一個現有的測試請求。

爲此我的當前流程(爲了清晰起見簡化)不使用超媒體鏈接實際排隊test_request(在作業集合上創建作業資源)的操作。

創建test_request資源

POST http://example.org/api/v1/test_request 

{ 
    'name': 'Some example tests', 
    'test': 'test1' 
} 


201, CREATED 

{ 
    'id': 3 
    'name': 'Some example tests', 
    'test': 'test1', 
    'links': [ 
     { 
      'rel': 'self', 
      'href': 'http://example.org/api/v1/test_request/3', 
      'method': 'GET', 
     }, 
     { 
      'rel': 'remove', 
      'href': 'http://example.org/api/v1/test_request/3', 
      'method': 'DELETE', 
     }] 
} 

生成作業資源

POST http://example.org/api/v1/jobs 

{ 
    'type': 'test_request', 
    'id': 3 
} 


201, CREATED 

{ 
    'id': 12, 
    'type': 'test_request', 
    'status': 'new', 
    'links': [ 
     { 
      'rel': 'self', 
      'href': 'http://example.org/api/v1/jobs/12', 
      'method': 'GET', 
     }, 
     { 
      'rel': 'remove', 
      'href': 'http://example.org/api/v1/jobs/12', 
      'method': 'DELETE', 
     }] 
} 

爲了滿足我的REST API的超媒體的標準,我真的很想增加對test_request操作鏈接資源,以便爲此創建新的作業資源。

改性test_request表示

{ 
    'id': 3 
    'name': 'Some example tests', 
    'test': 'test1', 
    'links': [ 
     { 
      'rel': 'self', 
      'href': 'http://example.org/api/v1/test_request/3', 
      'method': 'GET', 
     }, 
     { 
      'rel': 'remove', 
      'href': 'http://example.org/api/v1/test_request/3', 
      'method': 'DELETE', 
     }, 
     { 
      'rel': 'http://example.org/rels/queue', 
      'href': 'http://example.org/api/v1/test_request/3/queue', 
      'method': 'PUT', 
     }] 
} 

所以,第一個例子是(希望)的RESTful是我與隊列動作第二種方法是也許更多unRESTful。不過,在test_request表示中有一個鏈接非常好,該鏈接明確指出了進行下一個轉換的操作。

這裏最好的做法是什麼?

回答

1

你的問題不是非常清楚,所以我要去解釋你在問什麼,也許這可以幫助你得到答案。

根問題是一個域問題,只有你可以真正回答。能否並且應該在沒有工作的情況下進行測試?你需要考慮你的用例並作出決定。如果一個測試是一個弱的實體,那麼你應該只允許通過作業創建。

關於您爭取RESTful架構。我建議從您的API中刪除id字段的概念。自我鏈接就是ID。當您創建作業時,您可以提供想要包含在作業中的測試的鏈接集。類似

POST http://example.org/api/v1/jobs 

{ 
    'type': 'test_request', 
    'links': [ 
     { 
     rel : "test", 
     href : "http://example.org/api/v1/test_request/3", 
     }, 
     { 
     rel : "test", 
     href : "http://example.org/api/v1/test_request/4", 
     } 
    ] 
} 

注意:我不確定您的超文本格式如何處理同一關係的多個鏈接...我做了一個猜測。

我認爲主鍵和外鍵不應該存在於RESTful API中。應始終使用鏈接。