반응형
Rails 및 HTTParty를 사용한 API에 대한 POST JSON
Ruby on rails 앱 내 사용자가 외부 티켓 관리 시스템인 squishlist.com에 티켓을 제출할 수 있도록 하고 싶습니다.다음과 같은 API와 지침이 있습니다.토큰을 인증 및 취득한 후 토큰과 함께 티켓을 전송해야 합니다.스퀴시 리스트에서.
# 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에 대해 정말 잘 몰라.쉬울지도 모르는 걸 써야 하나?이걸 제출하려면 에이잭스를 사용해야 하나요?어떤 도움이라도 대단히 감사합니다.난 이 동네가 너무 좋아
이 문제를 해결하려면.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
반응형
'source' 카테고리의 다른 글
| 로컬 호스트가 WooCommerce를 업로드 및 설치하기 위한 Wordpress FTP 연결 설정 (0) | 2023.02.11 |
|---|---|
| AngularJS UI-Router는 뷰 내에서 현재 상태를 가져옵니다. (0) | 2023.02.11 |
| templateUrl을 즉시 변경할 수 있습니까? (0) | 2023.02.11 |
| AngularJS: Reverse 체크박스 상태 (0) | 2023.02.11 |
| 제출 시 또는 사용자 입력 시에만 양식 필드 확인 (0) | 2023.02.11 |