Call Google Tiny URL API in MATLAB

37 views (last 30 days)
Kevin
Kevin on 10 Jun 2016
Edited: Kevin on 21 Jan 2018
Hi everyone,
I am trying to call Google URL Shortener API https://developers.google.com/url-shortener/v1/getting_started#actions in MATLAB to shorten an URL. I know that I can go to https://goo.gl/ and manually paste the long URL into the text box. But I am wondering if I can do that programatically in MATLAB.
I know very little about web programming and this is as far as I can get,
options = weboptions('RequestMethod','post');
data = webread('https://www.googleapis.com/urlshortener/v1/url', 'longUrl', 'http://www.google.com/', options)
Error using readContentFromWebService (line 45)
The server returned the status 400 with message "Bad Request" in response to the request to URL https://www.googleapis.com/urlshortener/v1/url.
Error in webread (line 122)
[varargout{1:nargout}] = readContentFromWebService(connection, options);

Answers (1)

Chi
Chi on 19 Jan 2018
First, you should have a URL shortener API key. It can be generated in the Google Credentials page .
Then, the matlab code:
url='https://www.googleapis.com/urlshortener/v1/url?key={yours}';
options = weboptions('RequestMethod','post', 'MediaType','application/json');
Body = struct('longUrl', 'http://www.google.com/');
response = webwrite(url, Body, options);
  1 Comment
Kevin
Kevin on 19 Jan 2018
Edited: Kevin on 21 Jan 2018
Hi Chi,
Thank you very much for your suggestion. I followed your instruction to click the link "Google Credentials page" to create the key. I got the key and tried out the following MATLAB code. But I got error message from Google.
key = 'this_is_not_the_real_key';
url = ['https://www.googleapis.com/urlshortener/v1/url?key=', key];
options = weboptions('RequestMethod', 'post', 'MediaType', 'application/json');
Body = struct('longUrl', 'http://www.google.com/');
response = webwrite(url, Body, options);
Error using readContentFromWebService (line 46)
The server returned the status 403 with message "Forbidden" in response
to the request to URL https://www.googleapis.com/urlshortener/v1/url?
key=this_is_not_the_real_key.
Seems to me that the key (that I copy-and-paste from Google) does not work. I already set the key to "unrestricted" in Google page.
Kevin

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!