Author

Topic: [RUBY] EXAMPLE API CALL => HTTP POST with HEADERS (Read 457 times)

hero member
Activity: 1204
Merit: 531
Metaverse 👾 Cyberweapons
Hello beginners!

On our forum a lot of projects offer working APIs and with them innovative approaches and new possibilities, but I experienced that many of these opportunities remain unused because many of you do not know how to benefit from them. I understand that you may be casual to coding so I am trying to keep it simple and explain a code that you will be able to easily use.

You can communicate with APIs in requests and responses and you should find in each API's documentation what request it uses. In my experience, most APIs with extended features use HTTP POST requests so in this example I am using HTTP POST. Each request should result in a response and the body of the response is based on the request ( HTTP Post request in this case ) that you called the API with.

You can see a basic HTTP POST call in Ruby in the following code

Code:
#!/usr/bin/ruby
require 'net/http'
uri = URI('http://examplesite.com/api')
response = Net::HTTP.post_form(uri, 'method' => 'getticker')
puts response.body

Simple as that, it is a working code to most APIs for unauthenticated method calls.

APIs, however, could necessitate authentication in order to accept certain calls. An example of this kind of call could be a method that you can ask your addresses with at an exchange site. It necessitates authentication because each user has his own list of addresses and you are interested in your own list of addresses. In authentication, additional information could be required in the post form and even headers.

You can see an authenticated HTTP POST call with extended post form and headers in the following code

Code:
#!/usr/bin/ruby
require 'net/http'
http = Net::HTTP.new('www.examplesite.com',80)
path = '/api'
data = 'method=getmyaddresses&nonce=17720701081'
headers = {
  'Sign' => '44bd89b41f248e1b24a74d3395e459936fa6c0065d2e8ce8a5f9bf92383306dcab70ea43787f55efce994aa1d39932268a047a36c69c25ad99c7656b2272c52f',
  'Key' => '94167de94b3b44ba4980113ad2af9112528d0764'
}
response = http.post(path, data, headers)
puts response.body

That will be good to begin with, I think. You can use these codes with minimal changes to call APIs of providers here on BCT.

And why do you need this knowledge? It helps automatization, timed requests, terminal scripting, application and website development and many more ways of usage.

Good luck on your journey into the matrix!
Jump to: