Hi, in this tutorial, we are going to Integrate Angular 7|8|9 with Flask Python over the HTTP Service protocol by calling REST APIs.

Create an Angular Project with Flask Python

So, first, create a new project called AngularFlask. Go inside the AngularFlask folder and look for the app folder which is inside the src folder.

Now, open the app.component.html file and delete all the contents from it. Now first create a heading for our application named Integrate Angular with Flask Python.

For our Angular application, what we want is that as soon as the page loaded or refresh, it automatically fetch the data from the backend server that is from Flask Python Server using REST API calls.

So, before working with the frontend part that is with the Angular side, first, we need to create a rest service in Python which acts as an intermediate between frontend and backend application.

Create RestService in Angular Python

Create a new Folder named Flask outside the Angular Flask folder. Go inside the Flask Folder and create a new Python file named RestService.py.

Installing

Before writing RestService, we need to check whether Flask required libraries are installed or not. So, open a new command prompt and write the following commands one by one in command prompt.

pip install Flask pip install flask_cors

After successfully installed flask commands, let’s import the flask modules in our Rest Service.

from flask import Flask; from flask_cors import CORS;

Now, write the following code as mentioned below to create a basic code that is required by every Flask Python Server file.

app = Flask(__name__) CORS(app) @app.route("/", methods=['GET']) def index(): return "Welcome to CodezUp" if __name__ == '__main__': app.run(debug=True)

For more clarifications of the above code, you can check our previous tutorial on the Basics of Flask Python Application.

Raw Data

Now let’s create some raw data that need to be sent from backend(Flask Python) to frontend(Angular).

Create new variable weather that holds the data array. Create 7 objects inside the data array. Each object has fields like Day, Temperature, Windspeed, and the type of Event going to occur.

weather = { "data": [ { "day": "1/6/2019", "temperature": "23", "windspeed": "16", "event": "Sunny" }, . . ] }

Routing

Now, create a routing named /weatherReport/ so that the Rest Service weather data can be accessed in Angular using REST API calls.

Since we are requesting some data from the backend, we use the GET method type.

Define WeatherReport() function for the route /weatherReport/. Access the variable weather using the global keyword in Python.

Now, the Rest Service in the Angular side accepts the response in JSON format. So for that purpose, import jsonify module into the Rest Service.

from flask import Flask, jsonify;

At last, return the response using jsonify() function to the Angular Service.

def WeatherReport(): global weather return jsonify([weather])

Create Rest Service in Angular

Since we have created RestService in Python. Now what we want is that we need to fetch that data from the backend server(Flask).

So for that purpose, we need to also create RestService in the Angular side and make HTTP Service integrate Angular and Flask Python Application.

Create a Rest Service in Angular named rest.service.ts file using below command.

ng generate service rest

After creating Rest Service, we also need HTTP Service to interact. So, for that, we need to inject the HTTP Service in our application.

For injecting HTTP Service, create a private variable HTTP of type HttpClient in the constructor of rest.service.ts file and also import the HttpClient module inside it.

import { HttpClient } from '@angular/common/http'; . . constructor(private http : HttpClient) { }

Now, we need to create an URL for accessing the Flask Rest Service. So, define weatherUrl variable which holds the URL of the Flask Service.

weatherUrl : string = "http://127.0.0.1:5000/weatherReport/";

Let’s create a function call to the weatherUrl to fetch the data from Flask Rest Service over the HTTP protocol.

Since we already discussed how the HTTP Service returns the response. So, create a new file Weather.ts which holds the Objects returning from Flask Service.

Create Weather File in Angular

Now, define a new class Weather and also define the variables that are in weather array-like day, temperature, windspeed, and event. Also, create a constructor to assign values to the variables declared in the Weather class.

Now come back to rest.service.ts file and define readWeather() function which fetches the data over HTTP Service protocol.

readWeather() { return this.http.get<Weather[]>(this.weatherUrl); }

Fetch Response from Server

Now, after creating Rest Service in Angular, now we need to inject that Rest Service into our application.

For injecting Rest Service, create a private variable rs of type RestService in the constructor of app.component.ts file and also import the file location at top of the file.

import { RestService } from './Services/rest.service'; . . constructor(private rs : RestService){}

Now what we want is that the data we required must be fetch while loading the page or when we refresh the page immediately.

So for that, we need to call the Rest Service API to call in the ngOnInit() method because this method is automatically called initially before any other methods called.

And also for storing the response data, we need to declare an array of variable weather[] of type Weather class. Also, create a header variable holding an array of variables of the Weather class.

headers = ["day","temperature", "windspeed", "event"] weather : Weather[] = []; ngOnInit() { this.rs.readWeather() .subscribe ( (response) => { this.weather = response[0]["data"]; }, (error) => { console.log("No Data Found" + error); } ) }

Displaying Data in Table Form

Since we have successfully fetched the data using API calls and store them in weather[] array. Now, I have already posted a tutorial that how to display data in form of table in Angular. So let’s skip this part and directly add a table in our application.

<table id="weather"> <tr> <th *ngFor="let column of headers"> {{column}} </th> </tr> <tr *ngFor="let row of weather"> <td *ngFor="let col of headers"> {{row[col]}} </td> </tr> </table>

Import Services in AppModule File

Before running the project, we need to import some modules into our project that we have used at different places of our project.

Since we have used HTTP Service in our project, so we need to import HttpClientModule in @NgModule() under the import section.

imports: [ BrowserModule, AppRoutingModule, HttpClientModule ]

And also in our project, we have created our own Rest Service for fetching data, so we need to declare that service in @NgModule() under the providers section.

providers: [RestService]

Now, just save all the files and go to your terminal or command prompt to run the application.

Starting the Angular Server [ Terminal 1 ]

ng serve

Starting the Angular Flask Python Server [ Terminal 2 ]

python RestService.py

At last, go to your browser window and type the URL as http://localhost:4200/. Now as we can see that it successfully fetch the data from Flask and display the data in Angular in form of a table.

Wrapping Up

So, in this tutorial, we discuss step by step how to integrate Angular with Flask Python over HTTP protocol using REST Service APIs.

Source code from this tutorial is available on GitHub.

Hope you guys like this tutorial, feel free to drop any comments in the comment section below.