반응형
Rails 및 HTTParty를 사용하여 API에 JSON 게시
내 Ruby on Rails 앱의 사용자가 내 외부 티켓 관리 시스템 인 squishlist.com에 티켓을 출시 할 수 있기를 바랍니다. 다음과 같은 API가 제공됩니다. 인증하고 토큰을 획득 한 다음 토큰과 함께 티켓을 발급해야합니다. squishlist에서.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
테스트 목적으로 테스트 용 컨트롤러, 경로 및보기 (페이지)를 만들었습니다. 내 컨트롤러에는 다음이 있습니다.
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
@cfg = 'xxxsupport'
@user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
@api_key = 'MrUser411'
@project = 'excelm-manoke'
@url_new_string = 'https://api.squishlist.com/auth/?cfg='+@cfg+'&user_key='+@user_key+'&api_key='+@api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by @url_new_string
response = HTTParty.get(@url_new_string.to_str) #submit the string to get the token
@parsed_and_a_hash = JSON.parse(response)
@token = @parsed_and_a_hash["token"]
#make a new string with the token
@urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+@cfg+'&token='+@token+'&method=squish.issue.submit&prj='+@project
#submit and get a result
@result = HTTParty.post(@urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
그런 다음 컨트롤러 작업의 결과를보기 위해 이동하는 페이지가 다음 코드가 있습니다.
<p><%= @result %></p>
나는 그 과정에서 내가받은 응답 때문에 일반적으로 작동하고 있음을 알고 있습니다. 내 json은 squishlist에서 정의한 필드 때문에 추가와. 누구 든지이 문제에 대해 나를 도울 수 있습니까?
진짜 문제는 json이 어떻게 생겼는지, 심지어 일치하는지 알 수있는 것입니다. 나는 json에 대해 많이 모른다. 쉽게 할 수있는 것을 찾을 수 있습니다. ajax를 사용하기 위해 사용하기 위해 사용합니까? 어떤 도움이 대단히 감사합니다. 저는 여기 커뮤니티를 사랑합니다.
.to_json제목 정보를 추가 하여이 문제를 해결했습니다.
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
이 :query_string_normalizer옵션도 사용할 수 있으며 기본 노멀 라이저를 재정의합니다.HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}
참고 URL : https://stackoverflow.com/questions/7455744/post-json-to-api-using-rails-and-httparty
반응형
'IT' 카테고리의 다른 글
| C #의 'yield'키워드에 해당하는 Java가 있습니까? (0) | 2020.08.15 |
|---|---|
| GCC 및 ld로 사용하지 않는 C / C ++ 기호를 제거하는 방법은 무엇입니까? (0) | 2020.08.14 |
| LastPass가 양식 작성 중지 (0) | 2020.08.14 |
| ES6는 배열을 매핑하여 새 키가있는 배열을 반환합니다. (0) | 2020.08.14 |
| 함수가 생성자로 호출 감지하는 방법은 무엇입니까? (0) | 2020.08.14 |