# API gem 方法的响应结构不一致

**URL:** https://meta.discourse.org/t/api-gem-methods-have-inconsistent-response-structures/311269
**Category:** Development
**Tags:** rest-api
**Created:** [2024年六月9日 02:05 UTC](https://meta.discourse.org/t/api-gem-methods-have-inconsistent-response-structures/311269 "2024-06-09T02:05:13Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![simon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon/32/339122_2.png) [@simon](https://meta.discourse.org/u/simon)
#### Post date: [2024年六月9日 02:05 UTC](https://meta.discourse.org/t/api-gem-methods-have-inconsistent-response-structures/311269/1 "2024-06-09T02:05:13Z")

</div>

我不确定这是否值得一提，但在解析 gem 的 `create_topic` 和 `edit_post` 方法的响应时，我今天卡在了这里。

`create_topic` 调用 `post` 方法。该方法返回 `response.body` 或引发 `DiscourseApi::Error`：

```ruby
    def post(path, params = {})
      response = request(:post, path, params)
      case response.status
      when 200, 201, 204
        response.body
      else
        raise DiscourseApi::Error, response.body
      end
    end

```

`edit_post` 调用 `put` 方法。该方法返回一个 `Faraday::Env` 对象：

`#<struct Faraday::Env method=:put, request_body="post%5Braw%5D=It%27s+a+minor+thing%2C+but+it+comes+up+a+lot.+I%27ll+do+some+tests....`

对于使用该 gem 的应用程序来说，这意味着 `post` 和 `put` 请求返回的响应需要区别处理。要处理 `put` 请求，发出请求的应用程序必须执行类似 api gem 为 `post` 请求所做的操作：

```ruby
  def update_topic_from_note(markdown:, post_id:)
    response = @client.edit_post(post_id, markdown)
    case response.status
    when 200, 201, 204
      response.body
    else
    # ...

```

这也不是世界末日，但确实令人惊讶。我知道 API 代码的更改很难做。
