If you loveAlfred like me, you will enjoy this tutorial, I will teach you how to build a custom workflow to short URLs usinghttps://bitly.com/ (Free account).
Setting up a Bitly account
First, you will need to signup for aBitly account.
Then create a generic access token (You will need it later).Here are the instructions.
Building the Alfred workflow
This is the code for the workflow, let's talk about it.
require'net/http'require'uri'require'json'uri=URI.parse('https://api-ssl.bitly.com/v4/shorten')# Set parametersparams={long_url:ARGV[0]}# Set headersheaders={'Host':'api-ssl.bitly.com','Authorization':"Bearer#{ENV['BITLY_ACCESS_TOKEN']}",'Content-Type':'application/json','Accept':'application/json'}# Create the HTTP objectshttp=Net::HTTP.new(uri.host,uri.port)# Force SSL requesthttp.use_ssl=true# Build POST requestrequest=Net::HTTP::Post.new(uri.request_uri,headers)# Set request body (As JSON)request.body=params.to_json# Send the requestresponse=http.request(request)# Get link from responseputsJSON.parse(response.body)['link']
As you might know, you can build your own workflows using Ruby and other languages, even bash.
I used three Ruby native dependencies:
- Net::HTTP to make HTTP requests to Bitly
- URI to build URLs
- JSON to parse the response body and be able to extract the shorten link
Theparameters
I'm sending to Bitly come from the user input via Alfred, so in order to access the first and only argument, we have to useARGV[0]
.
For theheaders
it is mandatory to set theAuthorization Bearer
since this is how Bitly knows who is trying to shorten the link. We read the access token from the environment variables.
Alfred will ask for the token when you download the workflow.
We also need to make the request of typehttps
since they Bitly API requires a secure protocol. We not only need to usehttps://
in the request URL, we also have to tellhttp.use_ssl
, otherwise it won't work.
Therequest.body
has to be set up asJSON
as Bitly documentation indicates, so we convert the parameters toJSON
like thisparams.to_json
.
Finally we have to parse the JSON response usingJSON.parse(response.body)
, which returns a hash with keys and values.
The key we need is thelink
, for Alfred workflows, you actually need toputs
the output, if you don't do this the next script won't contain the expected input.
Download the Alfred workflow
You can directly download the workflow from theGithub repository
NOTE: You will be asked to introduce your personal access token.
Final thoughts
I had a really fun time coding this workflow. It was a bit tricky initially since there is not too many examples out there, however the documentation was good enough.
If you liked the workflow please consider giving it a ⭐ onGithub.
Happy coding!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse