In this tutorial, we’ll create a web app using AngularJS framework. In this web app we’ll implement Python REST API Authentication using Flask API. This tutorial assumes the reader to have basic knowledge of Python and AngularJS programming. If new to Python Flask and AngularJS, I would recommend reading Python Web Application Development Using Python Flask and Creating a Simple AngularJS App For Beginners.

Creating Python API Using Flask

Getting Started

First make sure that you have Python2.7+ and Flask0.10+ installed in your system. Once you have both, navigate to the terminal and install the Flask API.

pip install Flask-API
pip install markdown

We have installed markdown for browsable API support.

Create a project directory called FlaskAPI. Navigate to the project directory and create a file called app.py. Inside app.py paste the following code:

from flask.ext.api import FlaskAPI
app = FlaskAPI(__name__)

@app.route('/getData/')
def getData():
    return {'name':'roy'}

if __name__=="__main__":
    app.run(debug=True)

In the above code, we have imported the FlaskAPI and created an app using it. We have defined a method a route called /getData/ which would return a JSON data. Save the above code and start the application.

python app.py

Navigate to the following URL http://127.0.0.1:5000/getData/ and you should be able to view the response.

Python REST API Authentication Using AngularJS App

Creating Python REST API for Authentication

Let’ started by creating a new route in app.py called Autheticate.

@app.route('/Authenticate',methods=['POST'])

We have defined a new route with POST method. Add the corresponding method to call on the above /Authenticate request.

@app.route('/Authenticate',methods=['POST'])
def Authenticate():
    return {'username':request.form['username'],'password':request.form['password']}

Import the request library from Flask at the top of the app.py file.

from flask import request

Save the above changes and restart the server.

python app.py

We’ll make use of Postman client to make a POST request to the API. Here is how request and response of the REST API call to Authenticate API.

Python REST API Authentication Using AngularJS App

Previous: Google Apps Script Tutorial on Creating a Feedback Form

Enabling CORS in Python Flask API

We need to enable CORS (Cross Origin Resource Sharing ) in our Authenticate API so that our AngularJS app can make an AJAX call to the API. We’ll make use of Flask CORS to enable CORS in our API. From the official docs,

A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.

This package has a simple philosophy, when you want to enable CORS, you wish to enable it for all use cases on a domain. This means no mucking around with different allowed headers, methods, etc. By default, submission of cookies across domains is disabled due to the security implications, please see the documentation for how to enable credential’ed requests, and please make sure you add some sort of CRSF protection before doing so!

Install Flask CORS using pip.

pip install -U flask-cors

In app.py file, import the required cors library and enable CORS

from flask.ext.cors import CORS
app = Flask(__name__)
CORS(app)

Now the AngularJS app should be able to make request to the Flask API.

Making Python REST API Authentication Call

Now let’s create an AngularJS app using which we’ll make a REST API call to the Python Flask Authenticate API. To get started we’ll make use of the angular seed project. Clone the angular seed project from GitHub.

git clone --depth=1 https://github.com/angular/angular-seed.git AngularFlaskAPI

Navigate to the project directory AngularFlaskAPI and install the required dependencies.

npm install

Once the dependencies have been installed, start the server using :

npm start

Point your browser to http://localhost:8000/app/ and you should have your AngularJS application running. Let’s create a new view for our Authentication purpose called Home. Create a new folder called home in app folder. Inside home folder create a file called home.js and home.html. Here is how home.js looks like:

'use strict';

angular.module('myApp.home', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/home', {
    templateUrl: 'home/home.html',
    controller: 'HomeCtrl'
  });
}])

.controller('HomeCtrl', [function() {

}]);

Here is how home.html looks like:

Inject the new module dependency in the app.js file.

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.home',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

Add the new script reference in the index.html page.

Inside HomeCtrl in home/home.js, inject the $http module and make an AJAX call to the Authenticate API.

.controller('HomeCtrl', ['$http','$scope',function($http,$scope) {
    $scope.callData = function($event){
        $event.preventDefault();
        
        $http({
            method:'POST',
            url:'http://127.0.0.1:5000/Authenticate',
            headers: {
               'Content-Type': 'application/json;charset=utf-8'
            },
            data:{username:'jay',password:'jay'}
        })
        .then(function(resp){
            console.log(resp);
        },function(error){
            console.log(error);
        });
    }
}]);

Now since we are sending in JSON data from AngularJS app to the Flask API, we need to modify the API method code to receive data from the AngularJS app. Import jsonify libray in the app.py file.

from flask import request,jsonify

Here is the modified Authenticate API method:

@app.route('/Authenticate',methods=['POST'])
def Authenticate():
    content = request.json
    return jsonify({'username':content['username'],'password':content['password']})

Now try running your application and press the SignIn button. You should be able to see the response logged in the browser console window.

Wrapping It Up

In this tutorial, we created a web app using AngularJS framework and implemented Python REST API Authentication using Flask.

This tutorial just shows how to go about making a call from AngularJS app to Flask API using the $http AngularJS service. Do let us know your thoughts, suggestions or corrections in the comments below.

Also see : Creating an AngularJS app powered by Python Flask RESTful API