It’s easier to ask for forgiveness than permission(EAFP)

The above statement is an expression of a common coding style in Python. It is based on the assumption that the things you are looking for(keys or attributes) already exist and you can ask for them straight away without trying to check first, then ask later.

In the case that the assumption is wrong, you deal with the consequences of your assumption(by catching exceptions).

Consider this imaginary conversation between you and I:

Scenario one:

You:  What is the meaning of EAFP?

Me: It means “Easier to ask for Forgiveness than Permission”.

You: Thank you.

scenario two:

You: What is the meaning of EAFP?

Me: I don’t know!!

You: Oh, sorry for asking

Scenario three:

You: Do you know the meaning of EAFP?

Me: Yeah, sure.

You: What is the meaning of EAFP?

Me: It means “Easier to ask for Forgiveness than Permission”.

You: Thank you

Scenario four:

You: Do you know the meaning of EAFP?

Me: No, I don’t.

You: Oh, sorry for asking

 

In the first two scenarios you ask the question based on the assumption that I know the answer. This is clean and fast and ensures minimal conversation between us(saving both of us some time).

In the last two scenarios, you check first then ask later. In the case that I know the answer, you have to ask twice to get the answer from me.

From the above scenarios we can conclude by agreeing with the title that it is better than ask for forgiveness than permission.

Another advantage this style provides is the avoidance of race conditions(in theory at least). The assumption being that between the time you checked for availability(do I know the answer?) and the time you accessed the item(asking me to give you the answer) someone else has gotten ahead of you to ask for the same thing. And I have given it away to him/her  just before you asked.

 

Django’s get_or_create method

From the official django docs:

get_or_create(defaults=None, **kwargs)

is a convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.

So imagine we have a Customer model that has first_name, last_name and phone_number fields. Also imagine, and reasonably so, that we do not want to have duplicate customer entries in our database. We can achieve that by checking that the customer object we want to add to the database does not already exist.

To achieve that, and also assuming we are getting customer objects from say, our frontend, we can do something like this:;

try:
    obj = Customer.objects.get(**kwargs)

except Customer.DoesNotExist:

    obj = Customer(**kwargs)

    obj.save()

 

Note that  **kwargs  as used above expands the dict object passed into inndividual key-value pairs, similar to how the spread operator for object literals works in Javascript.

The above is what the get_or_create method is doing behind the scene. In doing so, it returns a tuple containing the object and a boolean that is set to true if the object was created and false if it already existed in the database. A simple implementation for our customer model would look like this:

def get_or_create(self, **kwargs):
    try:
        obj = Customer.objects.get(**kwargs)
    except Customer.DoesNotExist:
        obj = Customer(**kwargs)
        obj.save()
        return obj, True 
    return obj, False 

Of course, the real implementation in Django is much more robust and advanced than this as it takes into consideration when all the model fields have default values defined, in which case kwargs can be empty, among other things.

 

P.S. I see some weird formatting differences in the code blocks above. I do not know why. At this point, I find it convenient to blame the wordpress platform for that 🙂

Iterables, iterators, generators, oh my!

What is a Python iterable?

According to the Python official documentation:

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as liststr, and tuple) and some non-sequence types like dictfile objects, and objects of any classes you define with an __iter__() method or with a __getitem__()method that implements Sequence semantics.

What then is an iterator?

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream.

I am just shamelessly lifting up the definitions from the Python documentation. Don’t let that bother you 🙂

What is the difference/relationship between iterable and iterator?

Well, passing an iterable to the iter() function produces an iterator, a stream of data

that you can access  it’s items one by one( by calling the iterator’s __next__() method).

This is what happens when you pass an iterable through a for loop for example. Behind the scenes, the for statement calls iter() on the container object, which (as noted already) creates an iterator object that implements the __next__() method.

What is a generator?

It is a function that creates/returns an iterator.  Wait, I can explain. Normally, to create an iterator, you will need to implement the iterator protocol. That means you need a class that defines an __iter__() method which returns an object with a __next__() method.  Something like this(lifted again from the official doc):

class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

In general, generators do the same thing. Except for two cases:

  1. In a generator, the __iter__() and __next__() methods are created automatically.
  2. In a generator,  local variables and execution state are automatically saved between calls. What this implies is that each time thenext() method is called on a generator iterator, it resumes from where it left off.

An example generator:

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

 

What is a generator expression.

An expression that returns an iterator. An example of a generator expression:

(i*i for i in range(10)

 

 

Learning to run before you walk with Django

Landing a job recently as a back end developer means I am having to write APIs using the Django rest framework. First off, let me say I’m loving it so far. The framework packs a lot of features that make developing and deploying web APIs a breeze. But diving into the framework before I had the chance to fully learn Django, its parent web framework if I may use that term, seems to me as learning to run before I can walk with Django. That has not been very easy.

To clear up any misunderstanding, I do have an experience with Python. To be specific, I have written a few small projects, including a REST API with Flask. And without any fear of equivocation, I can say I love Flask. Profusely. The easy setup and great documentation, among other things, greatly lowered the entry barrier for me. Before you could say “Simple is better than complex”, I was already working through the amazing mega-flask tutorial by Miguel Grinberg. Basically, I was hooked.

And with my little experience writing Express apps in Nodejs, I did not feel the need to learn Django. Forget that I had read about its great documentation, batteries-included approach and other amazing things about it, I was not ready to Django.

Until the job came. The mention of Django by the recruiter lowered my interest in the job. Call me lazy, but I did not really want to learn Django. Not at that point in time at least. So I told him I knew only Flask. He also mentioned requiring someone with the knowledge of Vuejs. I did not know <vuejs. I told him I knew React though, and that not very much. Basically, I was trying to get him to look somewhere else.

Well he insisted I come for the interview. I reluctantly went. Few questions on Python, React, Redux and we were done. You will hear from us, I was informed. At this point, I was hooked. I prayed I would hear from them.

The phone rang. I picked it. Few minutes later I dropped it. I had heard from them. I had been taken. When can you come to the office so we can discuss? I gave them a convenient date. The date arrived. At the appointed time I arrived at their office. Few questions and answers about this and that. And that was it. You can start work tomorrow. I started work tomorrow.

My journey with Django had begun. At my first day at work, I was learning to run before I could walk with Django.

 

Handling side effects with redux-saga

I start with the introduction paragraph from the redux saga docs:

redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures.

I want to prove the above is true by showing a simple user authentication flow using redux-saga. The idea is pretty basic: we have a simple app, powered by an imaginary REST API backend, which allows the user to register/login to use the app. In reality, this backend does exist as a part of a project I’m working on(It’s written using the hapijs framework) and I hope to write a follow-up article on that part later.

Let’s take the user login process as a case study. When a user visits our app and is shown the login form, he goes to work filling it and submits it afterwards. On clicking the submit button, we take the data he has supplied and send it off as a post request to our backend. Then we wait.

If all goes well at the backend side of this story and the user is found, we get an access token as a response from the server, which we store(in the browser’s localstorage for example) and consequently log the user in. Here log the user in means that we set the token we just received as an authorization header in making a request to the user dashboard/profile endpoint.

If however, the user is not found(for whatever reason) or the server is not feeling too well at the request time, an error is returned instead, and we dutifully show the user this error and hope it helps him in making the next decision about using our app.

What I have explained above tells me that to keep note of the state changes during the login flow, I should better have an initial state that looks like this:

const initialState = fromJS({
  accessToken: null,
  requesting: false,
  authenticated: false,
  errors: null
})

By the way, and since you are asking what is fromJS, where does it comes from and why are we using it,  it actually comes from facebook’s immutable library, which I also happen to be using in the project I mentioned earlier. I will have my reducer update the state accordingly.

Now,  permit me to drop the login saga and then say a word or two about it later. Cool? Here it is:

import * as types from './actionTypes';
import *  as utils from './utils';

function* loginUserSaga(action) {
  try {
    const data = yield call(utils.loginUser, action.user);
    sessionStorage.setItem('accesToken', JSON.stringify(data.id_token));
    yield put({ type: types.LOGIN_SUCCESS, data });
  } catch(error) {
    yield put({ type: types.LOGIN_ERROR, error });
  }
}

So yes, redux-sagas are implemented as generator functions. Yay! Oh wait, no yay! yet.

The imports above the function contain the action types and some utility functions for making the api requests to our server. So our loginUserSaga function, in a general sense, tries to login the user and store the access token in the local storage if that succeeds, or yields an error (technically, dispatches an action type of LOGIN_ERROR, with the error) to the redux store.

Please note that call, and put are all redux-saga specific functions and so have to be imported. In fact, here is the line that does just that.

import { put, call, takeEvery} from 'redux-saga/effects';

Now that we have the saga, what next? I’m glad you asked that. Because, at this point, that loginUserSaga function above is useless and that is not good. The next step, therefore is to register or connect the saga to the redux store. Just before we do that, I export the loginUserSaga or rather I use it with the help of the code below:

export default function* rootSaga() {
  yield takeEvery(types.LOGIN_REQUEST, loginUserSaga)
}

So the rootSaga function that we are actually exporting ( and which we will hook up to the redux store soon) will watch the redux store for every action type called LOGIN_REQUEST and call the loginUserSaga function every time that action occurs. That’s what the takeEvery api from the redux-saga library does. It’s even clear from its name.

Now, here is where the hook up to the redux store happens. You are my witness.

import { createStore, applyMiddleware } from 'redux';
import { combineReducers } from 'redux-immutable';
import createSagaMiddleware from 'redux-saga';

import authRootReducer from '../components/Auth/reducer';
import rootSaga from '../components/Auth/sagas';

const reducer = combineReducers({
  auth: authRootReducer
});

const sagaMiddleware = createSagaMiddleware();

const middlewares = [
  sagaMiddleware
]

function configureStore(callback) {
  const store = createStore(reducer,
    applyMiddleware(...middlewares)
  )
  sagaMiddleware.run(rootSaga);

  callback(store);
}

export default configureStore;

Lots of imports going on here but I hope it’s all clear what they are for.

Finally, my index file looks like this:

import configureStore from './store/configureStore';

import { Provider } from 'react-redux';

configureStore(store => {
  ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
    document.getElementById('root')
  );
})

And boom! Everything is set up hopefully.

 

References

  1. redux-saga docs. 
  2. From action creators to sagas.
  3. managing side effects in react + redux using sagas.
  4. Build an image gallery using react, redux and redux-saga.
  5. react and redux-saga authentication app tutorial

 

Higher Order Components in React

What is a higher-order component (HOC) ? You ask. Well, a higher-order component is a function that takes a component and returns a new component, as per the official React doc. Right. The next logical question should then be: what is it used for and where? I’m glad you asked, or wanted to ask that question. Let us start with the first question. What in the world is a HOC used for?

At a high level HOC enables you to:

  • Code reuse, logic and bootstrap abstraction
  • Render Highjacking
  • State abstraction and manipulation
  • Props manipulation

Now, if the above does not make sense, don’t worry. It does not make much sense for me too 🙂 Let us take a look at some practical examples of HOCs instead and see if that does not help. I found one great example from the react-router doc. And I invite you to consider it carefully with me:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

What this does is that it wraps the component, and renders it if the user is authenticated. Please note that it is returning a Route component from react-router. This makes it so that that if a user navigates to the specified route, we first check if he is authenticated. If yes, kudos, we let him see the content of the wrapped content(render the component). If not, too bad, we send him to the Login page to sort himself out there. Note also that for that, we are using the Redirect component, which, as you might have guessed by now, is from the react-router library too. In fact, to set things in order , here is how we would usually import those components.

import React from 'react';
import { Route,Redirect } from 'react-router-dom';

Yes, and we are need React to be in scope for us to use the JSX syntax, as we have above.

Now that we have defined the PrivateRoute HOC, we can go ahead and use it like this.

import { BrowserRouter as Router }  from 'react-router-dom';

const App = () => (
  <Router>
    <ul>
      <li><Link to="/public">Public Page</Link></li>
      <li><Link to="/protected">Protected Page</Link></li>
    </ul>
    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>
  </Router>
)

We are pretending that all  the components used above exist of course. If you don’t like to pretend with me, they do actually exist. On the react router doc page, that is.

Well, I hope this example helped clarify what a higher-order component is and how it can be practically used in your React app. The links in the references below have more use cases for it too. I do hope you check them out. I hope to check them out myself too.

References

  1. A gentle introduction to React’s Higher Order Components. 
  2. Reusable State with Higher Order Components. 
  3. Higher Order Components – React’s official doc.
  4. React Router doc.
  5. React Higher Order Components in depth.

Simple REST API using Express and mySQL

This is a simple demo of building a REST API using Express and mySQL. You can grab the full code on github.

To make writing SQL query easier and more intuitive, I’m using a mySQL query builder.

Add it to your dependency by running npm i -S mysql-qb. Of course, you will need the mysql driver as well. That too is just npm i -S mysql away. You can change the above commands to npm install --save [module_name_here] if you prefer. But remember the save. It’s what adds the module as a dependency to your project.

But why go through all that hard work? All the dependencies are in the package.json file. Just git clone https://github.com/mekicha/nodejs-rest-apiscd nodejs-rest-apis and npm install. That’s all!

Next, lo and behold the user model we will be interacting with.

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(40) NOT NULL,
  `email` varchar(40) NOT NULL,
  `createdAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updatedAt` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  `role` enum('admin','moderator','member') NOT NULL DEFAULT 'member',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Let’s pretend we are trying to build some kind of a forum or maybe a user management system. Even though we are not.

What’s next? After creating the above table in a database, it’s time to write our API.

Create a users.js file and put let’s put these things inside.

var express = require('express');
var router = express.Router();
const queryBuilder = require('mysql-qb');
const config = require('./config');

const mqb = new queryBuilder(config);

We require express, query builder and the database configuration settings. The configuration looks like this:

module.exports = {
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: '',
  database: 'test'
}

It’s all pretty simple. We are building a pretty simple REST API.

Why don’t you just show us the first endpoint, and quit beating about the bush?

Well, my friend, here it is. A GET request handler.

router.get('/:id', (req, res) => {
  const id = parseInt(req.params.id, 10);
  if (!isNumeric(id)) {
    return res.json({
      data: [],
      error: 'id must be numeric'
    });
  }

  const query = mqb.select('*')
    .from('users')
    .where('id', id)
    .exec();

  makeResponse(query, res);
});

Everything makes sense right? All it knows to do is handle a request by Id. If I give you an Id of 2 and ask you to go find me the user with that Id, you probably would not know what to do. But that block of code you are looking at knows what to do. First, it will check that what is passed to it is truly an integer and nothing else. It calls a helper function to help it do the checking, since that’s not really it’s area of specialization.

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

If the checking succeeds, that is to say, what you gave was really an integer, it will pass it on to the database, who checks to see if it has a user with that Id. If it does, it retrieves all the information it has about that user and sends it to our request handler. Our request handler makes that into a response using the makeResponse function and sends us the result.

Here’s the makeResponse() function:

function makeResponse(query, res) {
  let response = {};
  response.data = [];
  response.errors = null;
  return query.then(result => {
    response.data = result;
    res.json(response);
  }).catch(error => {
    response.errors = error;
    res.json(response);
  });
}

The makeResponse function is actually the guy our request handler hired or begged to send the request to the database. So if the database returns an error, makeResponse will return that to our request handler too.

Here is a sample response from the handler:

{
    "data": [
        {
            "id": 1,
            "username": "agbo",
            "email": "eme@kachi.com",
            "createdAt": "2017-08-25T10:39:54.924Z",
            "updatedAt": "2017-08-25T10:39:54.924Z",
            "role": "admin"
        }
    ],
    "errors": null
}

Now, I must show you the POST request because it’s really interesting to look at:

router.post('/', (req, res) => {
  // create a new user.
  req.checkBody('username', 'username is required').notEmpty();
  req.checkBody('email', 'email is required').isEmail();

  req.getValidationResult().then((result) => {
    const errors = result.array();
    if (errors.length > 0) {
     return res.status(400).end();
    }
  });

  username = req.body.username;
  email = req.body.email;

  const query = mqb.insert(
    'users', {
      username: username,
      email: email
    }
  ).exec();

  query.then(result => {

      return res.json({
        data: [{
          username,
          email
        }],
        id: result.insertId,
        errors: null
      });
    })
    .catch(error => {
      response.errors = error;
      return res.json({
        data:[],
        error:'error saving data'
      });
    });

});

The post request handler does not trust the user too. So it’s checking what the user sent to make sure it’s what it’s expecting. If all goes well, it takes what the user sends and hands it over to the database. The database will save it, and will respond with an insertId among other things. That’s like saying: Hey, I just saved the data and here is the Id you should use if you want to GET the data from me. Post handler takes that, mixes it with what the user sent and sends it back to the user.

Here is what we get if we don’t supply the expected params:

{
    "data": [],
    "errors": [
        {
            "param": "username",
            "msg": "username is required"
        },
        {
            "param": "email",
            "msg": "email is required"
        }
    ]
}

And when we supply the needed data:

{
    "data": [
          {
            "username": "max"
          }
        ],
    "id": 1,
    "errors": null
}

To prevent this post from getting out of hand, I beg you to check out the source files yourself and see how the PUT handler works. And by the way, there is no handler for DELETE. I’m not saying you should write it, but honestly it’s not hard.

To run the app at this stage, just node bin/www and you are good to go. If you are going to be poking around with the code on your machine, install nodemon instead to help you reload automatically when you make changes.

What else can I say? Make a pull request if you find any mistakes, or you want to add anything.

See you next time.

Function Declaration vs Function Expression in Javascript.

I’m writing this to help clear the misunderstanding the initial time I came across function declaration and function expression. It turned out, after perusing a few materials, some of which I link to in the reference section below, that it was not really had as I had thought. So here goes:

From MDN:

function declaration defines a function with the specified parameters.

function add(x, y) {
    return x + y;
}

A function declaration is, well, a declaration.  It is is processed when execution enters the context in which it appears, before any step-by-step code is executed.  This is made possible by a mechanism called hoisting.  Hoisting enables us to use a function before its declaration. Like so:

console.log(add(5, 8)); //  13
function add() {
    return x + y;
}

Function expression

The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions.

A function expression can be anonymous or named(useful if you want to refer to the function inside the function body, like in the case of recursion). Also worthy of note is that a function expression is not hoisted, but only evaluated by the Javascript engine.

const subtract = function (x, y) {
    return x - y ;
};
subtract(16,4); // 12

Below is an example of a named function expression, from the StackOverflow

var z = function w() {
    console.log(typeof w); // "function"
};
console.log(typeof w);     // "undefined"

That’s about it about function declaration and expression. Check out the links below for more details.

 

references

  1. Function Declaration

2.  Comparison on StackOverflow

3. Named function expressions demystified

REST PARAMETERS vs SPREAD OPERATORS in ES6

Rest parameters and the spread operators, both new features added to the ES6 language specification have greatly simplified how some tasks in Javascript can be accomplished. But it can be initially confusing which one is in use, since both of them are represented by three dots. At least it was for me. In this post, I give a brief overview of the two features, show some examples of each, and at the end, link to some resources I found useful in trying to understand them. So, let’s get started.

REST PARAMETERS

According to MDN

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Well, an example might make that clearer.

function hasAllSubstrings(string, ...keys) {
  for (var key of keys) {
    if (string.indexOf(key) === -1) {
      return false;
    }
  }
  return true;
}
hasAllSubstrings('This is a demo of rest parameter', 'is', 'rest', 'parameter'); // true

Above, we have defined a function which takes a string and checks if it contains a number of substrings. If the string contains all the given substrings, the function returns true. Otherwise, it returns false. When we call the function, the first parameter This is a demo of rest parameter gets assigned to string, while the rest of the parameters is gathered into an array and assigned to keys.  An alternative way would have been to use the arguments object, which is not optimal in readibility and sometimes in performance.

One thing to note is that only the last parameter of a function can be designated as a rest parameter. As we have seen, the rest parameters gather all the remaining arguments so this constraint makes sense.

The Spread Operator

If the rest operator gathers arguments into one array, the spread operator does the opposite, that is, it takes an iterable or an object and ‘scatters’ them into one or more variables. Here are the different scenarios in which spread operators come in handy.

  1. When you want to use the elements of an array as arguments to a function

Example: Finding the max of an array.

let arr = [8, 15, 0, -2];

console.log(Math.max(...arr)); // 15

Spread unpacks arr  into individual arguments, making the function call equivalent to this:

console.log(Math.max(8, 15, 0, -2)); // 15

2. Combine arrays

let arr1= [1, 2, 3];
let arr2 =[4, 5, 6];
let arr3 = [-2,-1, 0];
arr1.push(...arr2) // [ 1, 2, 3, 4, 5, 6 ] End of arr1
arr1.unshift(...arr3) // [ -2, -1, 0, 1, 2, 3, 4, 5, 6 ] Beginning of arr1
let arr4 = [7, 8, ..arr2, 9 ,10] // [ 7, 8, 4, 5, 6, 9, 10 ] Somewhere in the middle

3. Copy arrays

let arr = ['red', 'orange', 'purple'];
let copy = [...arr]; // like arr.slice()

4. In object literals

This example from MDN will do.

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

Well, that is it! This now makes more sense to me. And I hope it does to you too!

 

        Resources

  1. Spread Syntax on MDN
  2. SPREAD vs REST PARAMETER on StackOverflow
  3. Rest and Spread Parameters on Javascript.info
  4. How three dots changed Javascript

 

 

 

The Google geocode api: a first look.

What is geocoding?

From the Google maps documentation:

Geocoding is the process of converting addresses (like “1600 Amphitheatre Parkway, Mountain View, CA”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers on a map, or position the map

This comes in handy in applications where you might need to get location information from the users. In my own case, for example, my aim was to build an application using the Foursquare api through which a user can search for restaurants or other places of interest in their location of choice.

Now, the Foursquare api does include geolocating ability, but hey, I recently completed a course on the Google maps api and thought I should just use it, if not for anything, for the practice.

Now, you will need to get an api key from google if you want to follow along. This link from Google guides you through how to do that. Or in much simpler terms, this stackoverflow thread.

There are client libraries for Google maps web services for a number of programming languages. The one for Python is here. However, for the purpose of this tutorial, I will not be using that. I just thought I should mention it.

Instead, I will be using the httplib2 library for sending the request to the api endpoint. And we will use the json library for loading the result from the api call.

Here is the code that takes an address as an input and returns the the geographic coordinates. We will use the coordinates in our foursquare api call to search our place of interest in a later article.

import httplib2
import json

def getCoordinates(inputString):
    google_api_key = "Put your api key here"
    locationString = inputString.replace(" ", "+")
    url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
    latitude = result['results'][0]['geometry']['location']['lat']
    longitude = result['results'][0]['geometry']['location']['lng']
    return (latitude,longitude)

Here is an explanation what is going on in the code:

    locationString = inputString.replace(" ", "+")

This replaces any space or spaces in the inputString with a ‘+’ sign. This is to ensure there is no break in the url path, which might make the server interpret our input string wrongly.

    url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key))

We now encode the input String and the api key into the url. Having done that, we are set to make our request. That is where we now pull out our httplib2 library.

    h = httplib2.Http()

We create an instance of the Http class, asigning it to the variable h.

    result = json.loads(h.request(url,'GET')[1])

We call the request method of our Http object and pass in our url and the ‘GET’ parameter, duly informing it that all we want to do here is ‘get’ a resource from the server. Nothing fancy there.

That request, if successful, will return an list with two values: the http response and the content. We are only interested in the content here, so we grab it from the list, and hands it over to the json.loads function which parses it into a python dictionary for us. It helps us do things like this:

    latitude = result['results'][0]['geometry']['location']['lat']

That is the latitude from our result. The longitude also came along with the result. Here it is:

    longitude = result['results'][0]['geometry']['location']['lng']

Our function returns the latitude, longitude pair in a tuple. Like so:

    return (latitude,longitude)

 

That is it, basically. Simple and sweet.

In the next article, we will use this result to talk to the foursquare api.