Development and Automation of a Web Application Using FastAPI, Jenkin and RobotFramework
Development and Automation of a Web Application Using FastAPI, Jenkin and RobotFramework
Author: Xiaoming Ma
Title: Development and Automation of Web Applications Using
FastAPI, Jenkins, and Robot Framework
Number of Pages: 37 pages
Date: 6 May 2024
The author hopes that this thesis will provide an alternative approach and insights for
web application developers who may not be familiar with these technologies.
List of Abbreviations
1 Introduction 1
5 Case study 13
5.4 Building the Jenkins pipeline for automated testing and deployment 26
6 Conclusion 36
References 37
List of Abbreviations
1 Introduction
Last but not least, this thesis will conduct a demonstrative case study focusing
on developing, deploying, and testing a restaurant web application using
specifically the above-mentioned technologies. It aims to provide inspiration and
guidance for individuals working on their own web development projects.
2
FastAPI, built upon standard Python type hints, represents a modern and high-
performance web framework designed specifically for Python 3.8 and above. It is
ideal for constructing APIs with agility and efficiency. (FastAPI Authors, 2024)
FastAPI emerges as the most recent addition to Python's extensive array of web
applications frameworks (Malhar, 2023). However, it distinguishes itself as a
swift, nimble, and contemporary API framework, offering a smoother learning
experience in contrast to other Python-based web frameworks like Flask and
Django. (Abdulazeez, 2022)
• Fast Performance: Renowned for its exceptional speed, FastAPI rivals the
performance of NodeJS and Go, thanks to its utilization of Starlette and
Pydantic. It stands as one of the swiftest Python frameworks currently
available.
3
• Standards-Based: Aligned with the open standards for APIs, FastAPI fully
embraces OpenAPI (formerly known as Swagger) and JSON Schema,
facilitating interoperability and adherence to industry best practices.
• Python type hints: Python differs from statically typed languages like
C/C++ and Java by being dynamically typed, meaning variable types are
determined by assigned values rather than explicitly declared. Unlike in
4
The above figure shows a directory structure for a FastAPI project called
"planner". Here's what each directory and file represent:
main.py: This is the entry point of the applications where the FastAPI app
instance is created and configured. It may also contain other initialization code.
database/:
routes/:
6
• init.py: Similar to the one in the database directory, this file marks the
directory as a Python package.
• events.py: This file contains route definitions and request handling logic
related to events, which could involve creating, reading, updating, and
deleting event data.
models/:
The Jenkins user interface can be logically segmented into four main sections:
the Header, the Job Table, the Configuration Panel, and the Build Queue and
Executor Status Panel (Jonathan, 2015). Figure 2 depicts each of these four
content regions.
• The job table: this section presents the defined jobs within the system
alongside fundamental status details.
• The build queue and executor status panel: this section gives an insight
into the current job executions and queued tasks within the Jenkins
system.
• Using Blue Ocean: After configuring a Pipeline project in Blue Ocean, its
user interface assists in composing the Pipeline's Jenkinsfile, which can
then be committed to source control.
9
• Through the classic UI: Users can input a basic Pipeline directly within
Jenkins via the classic user interface.
• Via SCM: Users have the option to manually create a Jenkinsfile, which
can be committed to the project's source control repository.
Figure 5. An example Robot Framework test suite file (Robot Framework Author, 2024)
13
The example Robot Framework test suite file from Figure 5 shows typical
sections used in most testing scenario:
• Settings: This section involves importing test libraries, resource files, and
variable files. It also includes defining metadata for both test suites and
test cases.
• Variables: This section is dedicated to defining variables that can be
utilized throughout the test data.
• Test Cases: This section involves the creation of test cases using
available keywords.
• Keywords: This section is for creating user-defined keywords based on
existing lower-level keywords.
To execute the test suite, the robot command should be used, followed by the
path to the test file. This command initiates the test process by interpreting and
running the specified Robot Framework test suite. Test cases are executed as
part of a test suite. When a test suite is created from a single file, it directly
contains test cases. However, test suites created from directories include sub-
suites, which themselves may contain test cases or further sub-suites. Typically,
all tests within a suite are run by default, but specific tests can be selected using
options like --test, --suite, --include, and --exclude. Test suites that do not
contain any tests are not considered in the execution. (Robot Framework
Author, 2024)
5 Case study
This case study project will illustrate the creation of a full-stack restaurant web
applications using conventional techniques HTML, CSS, and JavaScript for the
frontend, and FastAPI for the backend. Subsequently, it will showcase the
implementation of a Jenkins pipeline to automate the execution of Robot
Framework automated tests for the restaurant web applications and facilitate the
deployment process on the server. Given the extensive and longstanding use of
HTML, CSS, and JavaScript for developing web applications frontends, this
14
aspect will not be further elaborated upon in the following sections of the case
study.
Figure 6 illustrates the full work flows about this case study project. Development
of source code is done locally where the frontend (using HTML, CSS, JavaScript)
and the backend (using FastAPI) are developed. Source code also includes test
suites developed with Robot Framework, which comprises graphic user interface
tests and functional tests, managed with Jenkinsfile. After local development,
changes are pushed to a GitHub repository. When the Jenkins pipeline on a
CentOS server is triggered. it will pull the source code from the GitHub repository
and subsequently execute following stages:
• First Stage: Deployment of the web applications to a testing environment
on the server.
15
• Second Stage: Execution of the Robot Framework test suites against the
deployed applications in the testing environment on the server.
• Third Stage: Stop the applications deployed applications in the testing
environment on the server.
• Fourth Stage: If all previous stages succeed, the applications will be
deployed to the production environment on the server.
Finally, the restaurant's customers and owners are able to access the web
applications deployed to the production environment from the server.
This setup ensures that all updates to the web applications are thoroughly tested
and vetted before being made live, minimizing bugs and issues in the production
environment.
Main Objectives:
Before proceeding, ensure that the system has the appropriate version of Python
installed, as FastAPI is a Python-based framework compatible with Python
versions 3.6 and above.
16
Since this FastAPI backend used in this case study project relies on several other
dependencies:
• Uvicorn: A lightning-fast ASGI server, ideal for running FastAPI
applications.
• aiomysql: An asyncio-based library for MySQL databases, allowing
asynchronous interactions with MySQL.
• pydantic: A data validation and settings management library for Python,
used heavily in FastAPI for request and response validation.
• pyjwt: A Python library for JSON Web Tokens (JWT), facilitating secure
communication and authentication.
• python-jose: A library for working with JSON Object Signing and
Encryption (JOSE) standards in Python, often used alongside pyjwt.
• python-dotenv: A Python library for parsing and loading environment
variables from .env files.
• python-multipart: A library for parsing multipart/form-data request bodies,
commonly used for handling file uploads in web applications.
The final step is to install all above-mentioned dependencies with following
command:
pip3 install uvicorn aiomysql pydantic pyjwt python-jose python-dotenv python-
multipart
Figure below shows the directory structure of FastAPI backend created in this
case study.
17
• main.py - The main entry point of the applications where the application is
set up and started. It defines a FastAPI app, mounts directories for serving
static files, specifies CORS settings to manage cross-origin requests,
allowing requests from multiple predefined origins and supporting common
HTTP methods and integrates multiple routers for handling different
aspects of the applications such as login, reservation, menu, promotion,
messaging, and frontend interactions. Finally, the application is set to run
using Uvicorn as an ASGI server on port 8000, accepting connections from
all network interfaces.
18
• static - This directory is used to store static files like menu images which
are used by the applications’ frontend.
• routers - This folder contains different route files that define routes for the
applications. Each route file within this folder corresponds to a different
aspect or feature of the applications, handling the HTTP requests related
to that feature. Figure below shows menu creation endpoint. This endpoint
allows the uploading of a menu image along with data fields for menu
name, menu description, and menu price of a menu item. It processes the
authorization token, saves the uploaded menu image file to a static/
directory, and attempts to create a new menu item in the database using
the create_menu function.
21
Figure 13. Code snippet showing part of the file content of menu.py file
In the folder structure shown in Figure 7, this FastAPI backend includes 6 route
files: frontend.py, login.py, menu.py, message.py, promotion.py, and
reservation.py. Each route file contains different endpoints, offering various
functionalities to the frontend. The functionalities provided by different endpoints
can be divided into 2 categories based on whether an endpoint requires
authentication token or not. The authentication token can only be acquired by an
authorized user, such as the restaurant owners, who is logged into the restaurant
web applications with valid credentials.
• make a reservation.
• send a message to restaurant owners.
• review all restaurant menus.
Given that the test target is a web application, it's necessary to install
SeleniumLibrary as a dependency. SeleniumLibrary is indispensable third-party
library for web testing in Robot Framework, offering essential functionalities and
tailored keywords for seamless interaction with web elements during tests. It
enables testers to navigate, manipulate, and validate web applications behaviour,
ensuring reliable testing and robust functionality validation. The installation can
be done with following command:
23
The test cases will be divided into two groups as shown in Figure 14: graphic
user interface (GUI) tests and functionality tests.
Figure 15. Code snippet showing part of the file content of common.resource file
Figure 16. Code snippet showing part of the file content of common.resource file
24
Figures 15 and 16 both display sections of the file content from the
common.resource file. From Figure 15, it can be seen from Settings section that
4 libraries are utilized: SeleniumLibrary for web browser automation,
OperatingSystem for system interactions, and String and DateTime libraries for
handling string manipulations and date/time operations, respectively. The
Variables section defines several key variables used in the tests: ${URL} points
to a local web application hosted at http://localhost:8000/frontend/index.html.
${BROWSER} specifies the use of a headless Firefox browser for test execution.
${TIMEOUT} establishes a default timeout of 20 seconds for test commands.
${NAVIGATION_BAR} uses an XPath locator for the navigation bar identified by
its web element id "nav". ${ALERT} is an XPath locator for message alerts using
its web element id "messageText". ${CANCEL_BUTTON} and
${DELETE_BUTTON} are XPath locators for buttons within the applications,
identified by the text they contain 'Cancel' and 'Delete'.
GUI_tests folder contains two test files, one for testing the GUI used by customer
and another for the GUI used by restaurant owners.
25
Figure 17. Code snippet showing part of the file content of 01_customer_GUI_test.robot file
Figure 18. Code snippet showing part of the file content of 02_admin_GUI_test.robot file
From Figures 17 and 18, it can be observed that each GUI test file contains a
single test case, which is composed of numerous user-created keywords. Both
test cases encompass web page tests available to both restaurant owners and
restaurant customers, respectively. Each GUI test-related keyword will verify the
visibility of the corresponding web element on the respective web page at the
specified time.
Functionality tests folder contains four test files, each corresponding to a specific
aspect of the applications’ functionality: reservation, messaging, menu and
promotion.
Figure 19. Code snippet showing part of the file content of 01_reservation_test.robot file
26
Figure 20. Code snippet showing part of the file content of 02_message_test.robot file
Figure 21. Code snippet showing part of the file content of 03_menu_test.robot file
Figure 22. Code snippet showing part of the file content of 04_promotion_test.robot file
Figures 19 to 22 show test cases defined in all four functionality test files. The
test case from each test file covers all tests related to its respective functionality.
5.4 Building the Jenkins pipeline for automated testing and deployment
Secondly, add Jenkins repository and import Jenkins repository GPG key with
following commands:
sudo wget -O/etc/yum.repos.d/jenkins.repohttps://pkg.jenkins.io/redhat-
stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
Jenkins isn't included in the standard CentOS repositories. To install Jenkins, it
is required to add the Jenkins repository to the system and import its GPG key to
authenticate the packages.
Fourthly, after the Jenkins installation is completed, start the Jenkins service and
configure it to launch automatically upon system boot with following commands:
sudo systemctl start jenkins
sudo systemctl enable jenkins
Lastly, access the Jenkins web interface and unlock Jenkins. The Jenkins web
interface can be accessed from the URL: http://server_ip:8080, and the Jenkins
Unlock page should open. Unlocking the Jenkins web interface requires retrieving
the initial admin password from the following path
/var/lib/jenkins/secrets/initialAdminPassword on the server. After successfully
unlocking Jenkins, it will subsequently ask to install plugins. Either install
suggested plugins or select specific plugins according to the user's particular
requirements.
• Enter a name for the pipeline to be created and select "Pipeline" as the
project type.
• Click on "OK" to proceed to pipeline configuration.
• Now the user will be redirected to the pipeline configuration page.
• Select “GitHub project” and enter the project's GitHub repository URL.
• Choose "Build periodically" and enter “TZ=Europe/Helsinki H 5 * * 1-5” in
the Schedule input box. This schedule will execute the Jenkins pipeline
job at 5 AM Monday through Friday in the time zone set to Europe/Helsinki.
• Scroll down to the "Pipeline" section and select "Pipeline script from SCM"
as the pipeline definition method.
• Under "SCM", choose Git.
• Enter the GitHub repository URL and GitHub credentials in the
"Repositories" section.
• In the 'Branches to build' section, enter '*/main' to indicate that the 'main'
branch will be pulled from the GitHub repository when the Jenkins job is
triggered.
• Specify a local directory on the server where the GitHub repository will be
checked out and where the Jenkinsfile is located.
• Finally, click the save button to apply the configuration to the newly created
pipeline.
Next a file named Jenkinsfile need to be created. A Jenkinsfile is a text file that
defines the stage configuration of a Jenkins Pipeline. It outlines the sequence of
actions, or stages, to be executed in the pipeline. However, in Declarative
Pipelines, there is a default stage called 'Checkout SCM,' which automatically
pulls code from a version control system, such as a GitHub repository, to a
specific local directory on the server. This stage is provided by default and does
not need to be explicitly defined in the Jenkinsfile. Jenkinsfile is written in Groovy
and resides in the root directory of the project's source code repository. Script
below is the Jenkinsfile used in this case study project.
pipeline {
agent any
stages {
29
post {
always {
step([
$class : 'RobotPublisher',
outputPath : '.',
outputFileName : "output.xml",
reportFileName : 'report.html',
logFileName : 'log.html',
disableArchiveOutput: false,
passThreshold : 95.0,
unstableThreshold : 95.0,
otherFiles : "**/*.png",
])
}
failure {
script {
sh '''
cd /var/www/html/test/backend/
JENKINS_NODE_COOKIE=dontKillMe python3.9 -m uvicorn
main:app --host 0.0.0.0 --port 8000 >> /tmp/server.log 2>&1 &
sleep 5
cd /var/www/html/test/shell_scripts/
./backend_start_verification.sh production
'''
}
}
}
}
Script 1. Jenkinsfile
This Jenkinsfile defines multiple stages for automating the deployment and
testing processes of the case study web applications on server. It starts by
stopping applications in the production environment, deploying the most recent
version of applications in a testing environment. In the next stage it runs Robot
Framework test suites based on the web applications launched in the testing
environment. After the Robot Framework tests are completed, it proceeds to stop
the applications in the testing environment. If all previous stages succeed, the
pipeline proceeds to deploy the most recent version of applications to the
production environment. Otherwise, this deployment stage will be skipped,
ensuring that problematic changes to the source code are not applied to the
applications in the production environment. The post section handles post-build
actions, such as always publishing Robot Framework test results. Additionally, if
31
any stage fails, it restarts the web applications deployed in the production
environment without incorporating any problematic changes from the last Git pull,
guaranteeing there is always a reliable and functional version of the applications
in service. This pipeline automates the deployment and testing processes while
ensuring reliability and consistency in applications deployment.
Initiating a Jenkins pipeline job, also known as triggering, requires starting the
execution of predefined stages within the pipeline. This activation can occur
automatically through different methods like code commits, scheduled intervals,
or manual triggering.
In the context of Jenkins pipelines, evaluate the result from each pipeline job
typically involves analysing the outcome of the pipeline execution to determine
its success or failure. This evaluation phase assesses various factors such as
each pipeline job build status, automated tests results, and any errors
encountered during the pipeline execution. It allows users to review the
effectiveness of the pipeline, identify areas for improvement, and take appropriate
actions based on the results. Overall, the evaluation of pipeline results is crucial
for maintaining the reliability and efficiency of the continuous integration and
deployment workflow.
Each pipeline job build status will be indicate by the background colour applied
to the build number. This colour serves as a visual indicator of the job's status,
33
providing quick insight into whether the build was successful, failed, unstable, or
aborted.
• Blue: Indicates a successful build.
• Red: Indicates a failed build.
• Yellow: Indicates an unstable build, typically meaning that although the
build completed, there were some test failures or other issues.
• Gray: Indicates a pending or aborted build.
As shown in the latest pipeline job's build from Figure 24, the background colour
applied to build number 122 is blue, indicating that the status of this pipeline build
is successful, meaning no errors occurred in any stage. From this pipeline job
build, the source code has been pulled from the GitHub repository. Subsequently,
the web application was successfully deployed in the test environment on the
server, and all Robot Framework test cases, based on the application deployed
in the test environment, have passed. Following this, the application was
successfully deployed in the production environment on the server. In the post-
stage, the results of the Robot tests were successfully published. What is also
satisfying is that the whole process only took less than 3 minutes, meaning it
could be significantly faster than if all stages were executed manually.
Robot Framework test results can be accessed from each pipeline job's build
page as shown from Figure 25.
34
In the Robot Test Summary section, it is evident that all six tests, encompassing
both GUI tests and functionality tests, have passed indicating this restaurant web
application is fully functioning as it was originally designed to be. More detailed
Robot Test results can be accessed by clicking the 'Open log.html' link.
35
As mentioned in the previous chapter, the major obstacle faced in this case study
is maintain consistency of dependencies between the development environment
on the local computer and the testing and production environment on the server.
6 Conclusion
Overall, the essential objectives of this thesis were to enhance the performance
and reliability of modern web applications and streamline the development
workflows by using integrated technologies FastAPI, Robot Framework, and
Jenkins pipeline. The case study project began with utilizing FastAPI for web
application development and crafting automated test cases with the Robot
Framework. It then progressed to automating the execution of Robot Framework
test cases for web applications and deploying the application on the server.
Whole processes clearly demonstrated the seamless integration and
effectiveness of these technologies.
Through both theoretical insights and the successfully executed case study
project, it is anticipated that this thesis will serve as a valuable demonstrative
resource and further inspire the adoption of these techniques in more modern
web application development.
37
References
Manfred, B., Thomas, S., Marc-Florian, W., Stefan, G., Julian,H. and Richard,
S. (2021). Test Automation Fundamentals. [Online]. Rocky Nook, September
2022. URL: https://learning.oreilly.com/library/view/test-automation-
fundamentals/9781681989839/
(Accessed: 26 March 2024)