API gem methods have inconsistent response structures

I’m not sure if this is worth mentioning, but I got stuck on it today when parsing responses from the gem’s create_topic and edit_post methods.

create_topic calls the post method. That method returns either response.body or raises a DiscourseApi::Error:

    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 calls the put method. That method returns a Faraday::Env object:

#<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....

For application’s using the gem, it means the responses returned from post and put requests need to be handled differently. To handle a put request, the app that’s making the request has to do something like what the api gem is doing for post requests:

  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
    # ...

It’s not the end of the world, but it was surprising. I know it’s difficult to make changes to API code.

2 Likes