Hello, today I’ll be continuing my efforts while learning more about API interfacing.
This is day 3 of attempting to integrate a third-party api into my Rails project, and I must say that I haven’t made much progress. That being said, I will be covering the
URI documentation to try and gain a better grasp on issuing requests and handling response data when interacting with an api.
Net::HTTP provides a library used to build HTTP user-agents, or software that acts on our behalf. In order to gain access to the methods that this library provides to communicate, all we have to do is add
require 'net/http' to the top of the file we’re using to interface with the api.
URI is a module providing class methods to handle URIs. We don’t have to add
require 'uri' to our file if we’ve already required
'net/http' as its automatically done for us.
Lets briefly go over what some of these methods do.
There are a couple of ways to read information from an api using this library. We can gain access directly to the URI through
Net::HTTP.get('example.com', '/index.html'), passing in the host and URI as separate arguments. There is also the option of passing a uri to
get where uri is assigned the complete url string like so:
There are parameter options we can add to our URI as well. To add them, we can just store them in a hash like so:
There are three features listed in the URI documentation:
This module provides a few methods that will identify different parts of a URL.
You can actually just go into irb in your terminal and try these out. Remember to
require 'net/http' once irb starts up as this will include both libraries we’re covering today.
Here’s a look at the output from my window:
In addition to these methods, you can also join, split and extract strings. Here’s a quick example using
And if you know of any up-to-date resources for better understanding how to interface with apis leave a comment! Here are a couple of resources that I’ve found useful or plan to read/purchase in the near future.
More to come, stay tuned…
Categories: Ruby on rails