Slack API Postmessage - ruby

I'm looking at the Slack API for use in teaching API Consumption in Ruby. Does the Slack API require all the parameters as part of the query string or can it take post-Params as well.
Messages like this work:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}" + "&text=#{msg}&channel=#{channel}"
data = HTTParty.post(url)
end
However this does not:
def self.sendmsg(channel, msg)
url = BASE_URL + "chat.postMessage?" + "token=#{TOKEN}"
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}"
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
end

I think the cleanest answer is just this:
url = 'https://someslackwebhookurl/adfdsf/sdfsfsd'
msg = 'We are fumanchu'
HTTParty.post(url, body: {"text":"#{msg}"}.to_json)

I have managed to answer the question with:
data = HTTParty.post(url,
body: {
"text" => "#{msg}",
"channel" => "#{channel}",
"username" => bot_name,
"icon_url" => icon_url,
"as_user" => "false"
},
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' })
It won't work with JSON content oddly enough.

Related

API response not getting in cypress

///<reference types = "cypress"/>
describe('API Test Suite', ()=>{
it('Send GET Request',()=>{
cy.request('http://ptsv2.com/t/fu807-1554722621/post').then((res)=>{
expect(res.body).has.property('username', 'automate')
})
})
})
I'm trying to validate username field but its throwing error
expected '{\r\n "username": "automate",\r\n "password": "everything",\r\n "targetUrl": "http://ptsv2.com/t/7ty82-1554722743/post"\r\n}' to have property 'username'
SAMPLE RESULT on POSTMAN:
{
"username": "automate",
"password": "everything",
"targetUrl": "http://ptsv2.com/t/7ty82-1554722743/post"
}
The body property needs parsing - true, but there are less hacky ways of doing it
cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post')
.its('body')
.then(JSON.parse)
.should('have.property', 'username', 'automate')
or
cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post')
.then(res => JSON.parse(res.body))
.should('have.property', 'username', 'automate')
You can do something like this:
///<reference types = "cypress"/>
describe('API Test Suite', () => {
it('Send GET Request', () => {
cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post').then(
(res) => {
const user = 'automate'
cy.wrap(res.body).should('contain', `"username": "${user}"`)
}
)
})
})
On, digging deeper into your response body, I could see that there are empty spaces and because of which it was failing. So before asserting you have to remove the empty spacing and then apply the has.property assertion.
///<reference types = "cypress"/>
describe('API Test Suite', () => {
it('Send GET Request', () => {
cy.request('GET', 'http://ptsv2.com/t/fu807-1554722621/post').then(
(res) => {
expect(JSON.parse(JSON.stringify(JSON.parse(res.body)))).has.property(
'username',
'automate'
)
}
)
})
})
cy.request yields the response as an object so you can access it using .its()
cy.request('your-request-url')
.its('response.body')
.should('have.property', 'username','automate')
Alternatively, you can use cy-spok to check for properties and values in a more readable code format.
const 'spoke = require('cy-spok')
// in your test
cy.request('your-request-url')
.its('response.body')
.should(spok({
username: 'automated',
password: 'everything',
//other props
})
)

i can't return a response value on my cypress api call

I'm trying to make a cypress api call and get the value to be use on a next stage api call and when i make a return it just send me a big obj of commands
the call im making is
Cypress.Commands.add('getSession', () => {
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/New`,
headers: {
'Client-Type': 'backend'
}
})
.its('body')
.then(json => {
return {
id: json.value.props.id,
name: json.value.props.name
}
})
})
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
const session = cy.getSession()
cy.log('api respond', session.id)
cy.createMember(email, password, session.id)
})
and the response im getting is
[$Chainer] with a big obj
I'm not sure if the return on .then put it on a container but i can't find the value any when if someone can suggest what i have made wrong on the request call, that will be helpful
From the cypress docs:
So the createNew command must be rewritten to respect the async nature of cy commands.
Using then
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
cy.getSession().then( session => {
cy.log('api respond', session.id)
cy.createMember(email, password, session.id)
})
})
Using aliases
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
cy.getSession().as("session")
cy.get("#session").then(session => {
cy.log('api respond', session.id)
})
cy.get("#session").then(session => {
cy.createMember(email, password, session.id)
})

Body parameters in POST request with capitals

I need to send a POST request with HTTParty, in which the body parameter must be shortDescription. Should I use:
payload = { :short_description => "Bla" }
or:
payload = { :shortDescription => "Bla" }
How can I do this?
Pass payload like this:
payload = { :shortDescription => "Bla" }
or:
payload = { "shortDescription" => "Bla" }

angular6 - I can't get response from Scopus API

I want to use the Scopus API to verify that a DOI exists. I'm using the "Cited By" option. I did a test of this "http://api.elsevier.com/content/search/scopus?query=DOI(10.1016/j.stem.2011.10.002)" link in POSTMAN and it works, but when I did the implementation in Angular this is what returns.
Angular code
let headers = new Headers({
'X-ELS-APIKey': apikey,
'Accept': 'application/json',
});
this._http.get('http://api.elsevier.com/content/search/scopus?query=DOI(' + doi + ')', { headers: headers }).pipe(map(res => res.json())).subscribe(
response => {
console.log("Response");
console.log(response);
},
error => {
console.log("Error");
console.log(error);
}
);
Any help is greatly appreciated :)
Finally I solved it, the problem was that the "doi" string needed to go through the encodeURIComponent() function. I leave the code in case someone needs it.
welcome.component.ts:
let doi = encodeURIComponent('10.1017/j.stem.2011.10.002');
this._scopusService.getPublication(doi).subscribe(
response => {
console.log("DOI exists");
},
error => {
console.log("DOI doesn't exists");
}
scopus.service.ts:
public getPublication(doi) {
let headers = new Headers({
'Accept': 'application/json',
'X-ELS-APIKey': this.apiKey
});
return this._http.get('https://api.elsevier.com/content/search/scopus?query=DOI(' + doi + ')', { headers: headers }).pipe(map(res => res.json()));
}

ruby, sinatra, Plivo API: render API call as HTML

I am making an API call to Plivo to list available telephone numbers.
I can access the returned response and print the desired elements in my terminal BUT I do not know how to render them as HTML on my web page. This is my problem.
In the terminal, the response to a successful call is:
{"api_id"=>"23f1f0f0-0808-11e3-a442-22000ac6194a",
"meta"=>
{"limit"=>1, "next"=>nil, "offset"=>0, "previous"=>nil, "total_count"=>1},
"objects"=>
[{"group_id"=>"23928520636825",
"number_type"=>"local",
"prefix"=>"646",
"region"=>"New York, UNITED STATES",
"rental_rate"=>"0.80000",
"resource_uri"=>
"/v1/Account/MAZDQ1ZJIYMDZKMMZKYM/AvailableNumberGroup/23928520636825/",
"setup_rate"=>"0.00000",
"sms_enabled"=>true,
"sms_rate"=>"0.00800",
"stock"=>50,
"voice_enabled"=>true,
"voice_rate"=>"0.00900"}]}
"0.00900"
New York, UNITED STATES
646
The Ajax script which generates the response is:
$(".localsearch").click(function() {
var country_iso = $("#local").val();
var region = $("#region").val();
var prefix = $("#prefix").val();
$.ajax({
type: "GET",
url: "/local/data",
data: { 'country_iso' : country_iso, 'region' : region, 'prefix' : prefix },
success: function(data) {
alert(data)
},
});
});
The alert doesn't help and just shows the entire page.
The ruby code is:
get '/local/data' do
country_iso = params[:country_iso]
region = params[:region]
prefix = params[:prefix]
p = RestAPI.new(AUTH_ID, AUTH_TOKEN)
params = {'country_iso' => country_iso, 'region' => region, 'prefix' => prefix, 'limit' => '1'}
response = p.get_number_group(params)
obj = response.last
pp response.last
#region = obj["objects"][0]["region"]
puts #region
#prefix = obj["objects"][0]["prefix"]
puts #prefix
erb :search
end
So, sorry it's long and to summarize, how do I extract elements from the API response and print them as HTML? Many thanks in advance.
In the view I have tried:
<%= #region %> and <%= obj['region'] %> and <%= obj['objects][0]['region'] %>and none of them work.
Yours is a perfect use case of of rendering a partial through a ajax call.
So what you can do is:
Make your Sinatra action return html using rails like render partial functionality like this
http://steve.dynedge.co.uk/2010/04/14/render-rails-style-partials-in-sinatra/
(to get rails like partial functionality in sinatra you can use this gem also https://rubygems.org/gems/sinatra-partial )
Now since now your sinatra action returns a valid html, in your ajax success function you can just write:
$(".localsearch").click(function() {
var country_iso = $("#local").val();
var region = $("#region").val();
var prefix = $("#prefix").val();
$.ajax({
type: "GET",
url: "/local/data",
data: { 'country_iso' : country_iso, 'region' : region, 'prefix' : prefix },
success: function(data) {
$('unique_identifier_of_your_partial_on_the_html_dom').html(response)
}
});
});
another example of rendering partial in sinatra:
Ruby w/ Sinatra: Could I have an example of a jQuery AJAX request?
extract out the html that you want to populate with the response from this ajax call into a a separate erb file lets say , _my_response_partial.html.erb
now suppose this is your search.html.erb file.
#something somrthing
<%= erb(:my_response_partial, locals => {:region => #region, :prefix => #prefix},:layout => false) %> #pass whatever data you want to pass to a partial using locales
# something something
and in your get action replace the last line with:
erb(:my_response_partial, locals => {:region => #region, :prefix => #prefix},:layout => false)
By this way your action will just return the html required to populate that partial.

Resources