Home Web Development Full Stack FastAPI, React, and MongoDB

Full Stack FastAPI, React, and MongoDB

By Marko Aleksendrić
books-svg-icon Book
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Web Development and the FARM Stack
About this book
If you need to develop web applications quickly, where do you turn? Enter the FARM stack. The FARM stack combines the power of the Python ecosystem with REST and MongoDB and makes building web applications easy and fast. This book is a fast-paced, concise, and hands-on beginner’s guide that will equip you with the skills you need to quickly build web applications by diving just deep enough into the intricacies of the stack's components. The book quickly introduces each element of the stack and then helps you merge them to build a medium-sized web application. You'll set up a document store with MongoDB, build a simple API with FastAPI, and create an application with React. Security is crucial on the web, so you'll learn about authentication and authorization with JSON Web Tokens. You'll also understand how to optimize images, cache responses with Redis, and add additional features to your application as well as explore tips, tricks, and best practices to make your development experience a breeze. Before you know it, you'll be deploying the application to different platforms. By the end of this book, you will have built a couple of functional applications efficiently and will have the springboard you need to delve into diverse and more specialized domains.
Publication date:
September 2022
Publisher
Packt
Pages
336
ISBN
9781803231822

 

Web Development and the FARM Stack

Websites are built using a set of technology that is often called a stack – every component of the stack is responsible for one layer of the app. Although, in theory, you could combine any type of frontend technology with any type of background technology and, thus, end up with a custom stack, some have proven their worth in terms of agility and reduced development time, and they have strong communities and companies backing them.

In this chapter, we will provide an overview of today’s web development landscape in terms of the available technologies and demands, and we make the case for the FARM stack – a combination of FastAPI for the REST API layer, React for the frontend, and MongoDB as the database.

If you are a web developer, an analyst who must put some data online from time to time, or if you just want to broaden your developer’s horizon, this chapter should give you some perspective on this set of tools, the choices that tend to it, and how it compares to alternative technologies.

I will try to give a broad overview of the high-level concepts of the technologies that constitute the FARM stack, and I will discuss the ways that your next web development project might benefit from using this set of tools. For now, we will not go into details or concrete examples, but rather compare the selected stack components (MongoDB, FastAPI, and React) with their possible counterparts and make the case for the FARM stack.

As someone who has begun their journey through web development in what is considered the early days of yore, I remember Microsoft Frontpage and the possibility of turning Word documents into web pages. I remember using tables for layouts, and I remember animated GIF banners popping up everywhere. I also remember the excitement of putting a page online for the world to see.

Today, we have so many options for building websites and apps that it can become overwhelming to navigate and try to figure out the tools that satisfy often contradictory criteria. Websites aren’t just websites anymore – they are living creatures of the web that might evolve into, say, a mobile app or a lightweight CRM solution. Rapid tools such as React Native enable us to reuse the same (backend) code base and deliver a pretty good mobile app with almost all the native app features. Maybe the web app will need to provide some type of analytics that involves some heavy math – statistical analysis (a Spanish political party made great use of a simple statistical mobile app a couple of years ago and made a real impact by enabling its members to participate more directly in the decision-making process at all levels) or a simple recommendation algorithm. Maybe we want to add some fancy interactive charts and graphs displaying the many advanced metrics of our favorite NBA player’s statistics?

In this chapter, we will cover the following topics:

  • What is the FARM stack and how does it fit together?
  • Why use MongoDB for data storage?
  • What is FastAPI?
  • The frontend with React

By the end of this chapter, you will have a good understanding of the benefits that individual FARM stack components bring to a development project, how they relate to each other, and why this particular set of technologies might be a great fit for web apps that have fluid specifications – both in terms of the data handled and desired functionalities.

 

What is the FARM stack and how does it fit together?

It is important to understand that stacks aren’t really special – they are just sets of technologies that cover different parts of a modern web app, blend well together, and enable us to satisfy certain criteria while building web apps. To have a functional web application or site, we need to have a system consisting of the following:

  • An operating system: Usually, this is Unix/Linux-based.
  • A database layer: A SQL or NoSQL solution. In our case, we will use MongoDB.
  • A web server: Apache and Nginx are quite popular, but we will talk about Python solutions for FastAPI, such as Uvicorn or Hypercorn.
  • A development environment: PHP, Node.js/JavaScript, .NET, or Python.

Optionally, and more often than not, we could also add a frontend library or framework (such as Vue.js, Angular, React, or Svelte) since the vast majority of web development companies benefit from adopting one in terms of consistency, development speed, and standards compliance. And let’s face it – it is 2022, and you just cannot afford to handcraft your user interfaces without a library or a framework.

Let’s list the most famous stacks or, at the very least, some of those that have a popular acronym:

  • MERN: MongoDB + Express.js + React + Node.js is still probably one of the most popular ones today. Developers can be comfortable and never leave JavaScript, except when they need to write some style sheets. With the addition of React Native for mobile apps and something like Electron.js for desktop apps, a product can encompass virtually every platform while relying solely on JavaScript.
  • MEAN: MongoDB + Express.js + Angular.js + Node.js is similar to the previously mentioned MERN, with Angular.js managing the frontend in a more structured Model–View–Controller (MVC) way.
  • PERN: Postgres + Express.js + React + Node.js is for those who want the stability and features of a Postgres relational database. Often, it is used in conjunction with an object-relational mapper.
  • LAMP: Linux + Apache + MySQL + PHP is probably the first acronym to gain popularity and one of the most perused in the past 20 years.

The first three stacks run on the Node.js platform (a server-run JavaScript V8 engine) and have a web framework in common – although Express.js is the most popular, there are excellent alternatives in the Node.js universe, such as Koa.js, Fastify.js, or some more structured ones such as Nest.js.

One popular, and very interesting, Python-based combination is using the Django web framework and the excellent Django REST Framework (DRF), which is a toolkit for building REST APIs in a modern and logical way. Django itself is very mature and popular among Python developers and offers flexibility and development speed along with some typical Django goodies: an admin site, the possibility of customizing and serializing REST responses, the option to choose between functional and class-based views, and more.

The choice of the stack should be heavily conditioned by the type and the scope of the project at hand. Startups, but also small internal tools, can often benefit from agile, rapid development with flexibility and potential scalability down the road. Additionally, time-to-market, the availability of developers (the talent pool), and the maintainability and support of individual layers play a key role in the process of stack selection.

FARM is a new acronym, and there aren’t many resources covering it as a whole, though there are excellent resources on MongoDB and React, which have a great degree of adoption and maturity. On the other hand, FastAPI is much newer but provides excellent online documentation.

Let’s dissect this funny acronym. FA stands for FastAPI – a very interesting and, in technology years, brand-new Python web framework. R stands for React, which is, arguably, the most popular UI library, while M denotes the data layer – MongoDB, which is, arguably, the most popular NoSQL database available today. I honestly don’t know if the acronym started as a joke, but it sure sounds great.

The main objective of this chapter is to get you acquainted with the included technologies at a high level and compare them with the alternatives. We will try to set the ground for a simple project that we will be building throughout the book – a used automobile sales website – and then add some functionality while trying to implement some of the best practices in all of the areas. At the end of the chapter, you should hopefully become interested (maybe even excited!) in the proposed technology mix and be able to evaluate whether this type of setup could benefit your future projects and whether it is something useful to add to your web developer’s toolkit.

The following diagram provides a high-level overview of the moving parts involved in the FARM stack:

Figure 1.1 – A Diagram of the FARM stack with its components

Figure 1.1 – A Diagram of the FARM stack with its components

As you can see from the preceding diagram, the FARM stack is composed of three layers. The user performs an action using the client, which, in our case, will be based on React – this ultimately creates a bundle of HTML, CSS, and JavaScript. This user action (a mouse click, a form submit, or some other event) then triggers an HTTP request (such as GET, POST, PUT, or another HTTP verb with a payload) that gets processed by our REST API service (FastAPI).

The Python part is centered around FastAPI and optional dependencies and is served by uvicorn – a fast Python-based server. The backend is responsible for dispatching the appropriate database calls to MongoDB using various commands - queries (such as findOne, find, create, update, and more) and leveraging the MongoDB aggregation framework. The results obtained from the database are interpreted by FastAPI through the Python driver of choice (Motor), converted from BSON into appropriate Python data structures, and finally, output from the REST API server in the form of plain JSON.

Since we will use Motor, which is an asynchronous Python driver for MongoDB, these calls will be handled asynchronously. Finally, returning to the diagram and the arrow denoted by JSON, the data is fed to the UI where it is handled by React and used to update the interface, render the necessary components, and synchronize the UI with React’s virtual DOM tree.

In the following sections, we will go over the motivations behind the birth of the FARM stack. Additionally, we will go over each component and the features that make it a good fit in more detail. After a brief introduction to the benefits of the stack as a whole, I will provide a high overview of each choice and underline the benefits that it can provide to a modern web development workflow.

Why the FARM stack?

I truly believe that the flexibility and simplicity of the stack, along with the components comprising it, could give you a real boost in terms of development speed, extensibility, and maintainability while allowing for scalability (due to the distributed nature of MongoDB on the one hand and the async nature of FastAPI on the other hand) down the road, which might prove crucial should your product need to evolve and become bigger than it was initially supposed to be. The ideal scenario would probably be a small-to-medium-scale web app that you could play with and find the time to experiment with a bit. Finally, I believe that developers and analysts alike could greatly benefit from Python’s ecosystem and extensibility through a rich ecosystem of modules that encompasses virtually every human activity that includes some type of computing.

Evolution in Web Development

The beginning of the 2020s saw an interesting blurring of the borders between classical web development and other types of computing. Data science has lost some of its mystique, much of the science of it has been turned into a craft, and it has descended into the plebs and the not-so-scientifically inclined developers. Now, algorithms such as linear regressions, clustering, even neural networks, and ensemble methods are very easy to embed even in the most mundane systems in order to gain a feature, to achieve a slight performance gain, or add a simple recommendation engine. The visualization toolbox has moved online and classical workhorses such as Ggplot2 (for R) and D3.js, which require a thorough understanding of the underlying technologies, are now being given a run for their money by various combinations of D3.js and Svelte or React, SVG or Canvas - based solutions and more; for example, full-blown Python and React web application frameworks specialized for data visualization such as Plotly - Dash, Streamlit, or simple yet powerful solutions such as Chart.js.

Alternatively, if you just need to create a company or portfolio website with structured content, you can choose from the plethora of popular JAMstack solutions. JAMstack is a relatively new web development paradigm based on not-so-new components – JavaScript, API(s), and Markup (JAM) – and enables developers to develop faster web solutions, achieving blazing performance and a non-techie-friendly admin interface.

Additionally, web hosting costs have rapidly decreased in the last decade and several cloud-based companies have drastically lowered the technical barrier to web development and the creation of internet-based products. In this book we will examine many cloud-based systems that can handle parts of the system well.

Having provided a brief introduction to the contemporary and novel challenges of modern web development, it is time to introduce our database system of choice – MongoDB.

 

Why use MongoDB?

In the following paragraphs, we will go through the main features of our selected database system – MongoDB – and give a high-level overview of the features that make it an excellent fit for our FARM stack. After a brief introduction of some specificities of the database, in the following chapter, we will go over the setup and create a working database environment that will enable us to showcase some basic methods.

MongoDB is the database of choice in the FARM stack. It is a fast, scalable, and document-oriented database that enables flexible schemas and, thus, iterative and rapid development. MongoDB is able to accommodate data structures of varying complexities, and its querying and aggregation methods make it an excellent choice for a flexible REST API framework such as FastAPI, coupled with an official Python driver. It has a high level of adoption and maturity and is one of the pillars of the NoSQL data storage movement that took the web development world by storm a decade ago.

The main features that make MongoDB an ideal candidate for a flexible and fast-paced development environment, prototyping, and iterative development are listed as follows:

  • Easy and cheap: It is easy and fast to set up using an online cloud service that offers a generous free tier, while local installation is always an option.
  • Flexibility: The NoSQL nature of the database enables extremely flexible models and fast iterations and modifications on the fly.
  • Web-friendly format: The native data format – BSON – is practically a binary version of JSON, which, in turn, is the de facto data format of the modern web, so no complex parsing or transformations are necessary.
  • Complex nested structures: MongoDB documents allow other documents and arrays of documents to be embedded, which naturally translates into the data flow of a modern data web app (for example, we can embed all of the comments into the blog post they refer to). Denormalization is encouraged.
  • Simple intuitive syntax: The methods for performing basic CRUD operations (that is, create, read, update, and delete), coupled with powerful aggregation frameworks and projections, allow us to achieve mostly all data reads relatively simply through the use of drivers, and the commands should be intuitive for anyone with a bit of SQL experience.
  • Built with scalability in mind: MongoDB is built from the ground up with several objectives – scalability, speed, and the ability to handle huge (huMONGOus) amounts of data.
  • Community and documentation: Lastly, MongoDB is backed by a mature company and a strong community, and it offers various tools to facilitate the development and prototyping process. For instance, Compass is a desktop application that enables users to manage and administer databases. The framework of the serverless functions is constantly being updated and upgraded, and there are excellent drivers for virtually every programming language.

I believe that in some cases – and this includes a lot of cases – MongoDB should be your first choice, especially when you are designing something that still has a very fluid or vague specification, and let’s be honest, that happens a lot more than we would like to admit.

Of course, MongoDB is not a silver bullet, and some drawbacks are worth noticing upfront. On the one hand, the schemaless design and the ability to insert any type of data into your database might be a bit panic-inducing but translates to the need for stronger data integrity validation on the backend side. We will see how Pydantic – an excellent Python validation and type-enforcement library – can help us with that. The absence of complex joins, which are present in the SQL world, might be a dealbreaker for some types of applications. For analytics-intensive applications that require numerous complex queries, relational databases are a better, and often the only possible, solution. Finally, for mission-critical applications that require adherence to the ACID principles (that is, atomicity, consistency, isolation, and durability) of transactions, MongoDB or any NoSQL database system might not be the right solution.

Now that we understand what MongoDB brings to the table in terms of scalability, but especially flexibility with its schema-less approach, let us take a look at the REST API framework of choice, FastAPI, and learn how it can help us leverage that schema-less approach and simplify our interactions with the data.

 

Introducing FastAPI

Now we will look at a brief introduction to the Python REST-API framework of choice – FastAPI. Additionally, we will go over a high-level overview of the features that make it a protagonist in our FARM stack. I will try to compare FastAPI with Python and JavaScript alternatives and explain why it can be a great fit for a modern and flexible stack.

REST APIs

What is an API? Technically, API stands for Application Programming Interface. APIs are used to enable some kind of interaction between different pieces of software and different systems, and they communicate using HTTP (short for Hypertext Transfer Protocol) through a cycle of requests and responses. In the last couple of decades, APIs have become the standard protocol for communication between various servers and heterogeneous clients, and they can be seen as a sort of vascular system that is fundamental to information exchange on the web.

There are many definitions, more or less formal ones, and application programming interfaces can mean many things, but I like to view them as wirings that expose the business logic through a uniform interface, allowing us to use them from another realm.

An API is, as its name suggests, an interface. It is a way for a human or a machine to interact with an application or a service through an interface. Every API provider will provide an interface that is well-suited for the type of data that they provide, for instance, a weather forecasting station will provide an API that lists the temperatures and humidity levels for a certain period and a certain location. Some sports sites will provide statistical data about the games that are being played and a pizza delivery API will provide you with the selected ingredients, the price, and the estimated time of arrival. APIs are everywhere – inside your TV, your wallet, and, heck, your favorite news site probably uses at least a dozen of them. With the adoption of the Internet of Things, APIs will enter even more aspects of our lives, transmitting biometric and medical data, enabling fast communications between factory machines, tractors in the fields, traffic frequencies, traffic light control systems, and more. APIs are what makes today’s web turn, what generates traffic, and ultimately, what generates revenue. Put simply, we can think of an API as a standardized way of information exchange, with usability, performance, and scalability in mind.

We will not go over the rigorous definitions of REST APIs, but just list some of the most important ones:

  • Statelessness: REST APIs are said to be stateless, which means that neither the client nor the server stores any states in-between. All the requests and responses are handled by the API server in isolation and without information about the session itself.
  • Layered structure: In order to keep the API scalable and understandable, a RESTful architecture implies a layered structure. The different layers form a hierarchy and communicate with each other but not with every component, thus improving overall security.
  • Client-server architecture: APIs should be able to connect different systems/pieces of software without limiting their own functionalities – the server (the system that provides the response) and the client (the system making the request) have to stay separate and independent from each other.

We will be using FastAPI for our REST API layer, and we could say that it checks all the required boxes and then some more.

What is FastAPI?

FastAPI is a modern and performant web framework for building APIs. Built by Sebastian Ramirez, it uses, to best avail, the newest features of the Python programming language, such as type hinting and annotations, the async – await syntax, Pydantic models, web socket support, and more.

There are numerous reasons why FastAPI, though relatively new, will probably see a wider spread in the web development world in the future, so let’s list some of them:

  • High performance: FastAPI is able to achieve very high performance, especially compared to other Python-based solutions. By using Starlette under the hood, FastAPI’s performance reaches levels that are usually reserved for Node.js and Go.
  • Data validation and simplicity: Being heavily based on Python types and Pydantic brings numerous benefits. Since Pydantic structures are just instances of classes the developers define, we can perform complex data validations, deeply nested JSON objects, and hierarchical models (using Python lists and dictionaries), and this relates very well with the nature of MongoDB.
  • Faster development: Development becomes more intuitive, with strong integrated development environment (IDE) support, which leads to faster development time and fewer bugs.
  • Standards compliance: FastAPI is standard-based and fully compatible with open standards for building APIs – OpenAPI and JSON schemas.
  • Logical structuring of apps: The framework allows for structuring of APIs and apps into multiple routers and allows granular request and response customization. and easy access to every part of the HTTP cycle.
  • Async support: FastAPI uses an Asynchronous Server Gateway Interface (ASGI) and, with the use of an ASGI-compatible server, such as Uvicorn or Hypercorn, is able to provide a truly asynchronous workflow without actually having to import the Async.io module into Python.
  • Dependency injection: The dependency injection system in FastAPI is one of its biggest selling points. It enables us to create complex functionalities that are easily reusable across our API. This is a pretty big deal and probably the feature that makes FastAPI ideal for hybrid web apps – it gives developers the opportunity to easily attach different functionalities to the REST endpoints.
  • Great documentation: The documentation of the framework itself is excellent and second to none. It is both easy to follow and extensive.
  • Automatic documentation: Being based on OpenAPI, FastAPI enables automatic documentation creation, which essentially means that we get our API documented for free with Swagger.

In order to get at least a basic idea of what coding with FastAPI looks like, let’s take a look at a minimal API:

# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
    return {"message": "Hello World"}

The preceding few lines of code define a minimal API with a single endpoint (/) that responds to a GET request with the message “Hello world”. We instantiate a FastAPI class and use decorators to tell the server which HTTP methods should trigger which function for a response, just like with the Flask microframework, for example.

Python and REST APIs

Python has been used to build REST APIs for a very long time. While there are many options and solutions, DRF and Flask seem to be the most popular ones, at least until recently. If you are feeling adventurous, you can Google less popular or older frameworks such as bottle.py and CherryPy. DRF is a plug-in system for the Django web framework and enables a Django system to create highly customized REST API responses and generate endpoints based on the defined models. DRF is a very mature and battle-tested system. It is regularly updated, and its documentation is very detailed. Flask, Python’s lightweight microframework, is a real gem among the web-building Python tools and can create REST APIs in a lot of different ways. You can use pure Flask and just output the appropriate format (i.e., JSON instead of HTML) or use some of the extensions developed to make the creation of REST APIs as straightforward as possible. Both of these solutions are fundamentally synchronous, although there seems to be active development in the direction of enabling async support.

There are also some very robust and mature tools, such as Tornado, which is an asynchronous networking library (and a server) that is able to scale to tens of thousands of open connections. Finally, in the last couple of years, several new Python-based solutions have been created.

One of these solutions, and arguably the fastest, is Starlette. Dubbed as a lightweight ASGI framework/toolkit, it is ideal for building high-performance async services.

Like Flask was built on top of a couple of solid Python libraries – Werkzeug and Jinja2 – 10 or more years ago, Sebastian Ramirez built FastAPI on top of Starlette and Pydantic, while also adding numerous features and goodies by using the latest Python features, such as type hinting and async support. According to some recent surveys, FastAPI is quickly becoming one of the most popular and most loved web frameworks.. Undeniably, it is gaining in popularity, and it looks like it is here to stay, at least for the foreseeable future.

In Chapter 3, Getting Started with FastAPI, of this book, we will go over the most important features of FastAPI, but at this point, I just want to stress the significance of having a truly async Python framework as the glue for the most diverse components of a system. In fact, besides doing the usual web framework stuff, such as communicating with a database or, in our case, a MongoDB store, spitting out data to a frontend, and managing authentication and authorization, this Python pipeline enables us to quickly integrate and easily achieve frequently required tasks such as background jobs, header and body manipulation, response and request validation, and more through the dependency injection system.

We will try to cover the absolute minimum necessary for you to be able to build a simple FastAPI system. I will make frequent trips to the official documentation site and try to find the simplest solutions. Lastly, we will consider various web server solutions and deployment options (such as Deta, Heroku, and Digitalocean) for our FastAPI Python-based backend, while trying to opt for free solutions.

So, to cut a long story short, we choose FastAPI because we ideally want the ability and speed to handle requests asynchronously as if we were using a Node.js server while having access to the Python ecosystem. Additionally, we want the simplicity and development speed of a framework that automatically generates documentation for us.

After reviewing the backend components, it is time to finalize our stack and put a face on it. We will now look at a minimal introduction to React and discuss what distinguishes it from other (also valid) solutions.

 

The frontend – React

Let’s start with a bit of context here. Perhaps the changes in the world of the web are most visible when we talk about the frontend – the part of the website that is facing the users. Tim Berners-Lee made the first HTML specification public in 1991, and it consisted of text and under 20 tags. In 1994, we got cascading style sheets and the web started looking a little nicer. Legend has it that a new browser scripting language called Mocha was created in just 10 days – that was in 1995. Later, this language went through numerous changes and became what we know today as JavaScript – a powerful and fast language that, with the advent of Node.js, was able to conquer the servers, too.

Another important concept that has left a strong mark in the development of the frontend is the extensive use of Asynchronous JavaScript and XML (AJAX) – you might remember all those rounded corner web apps with vowel-based URLs. The technology of making asynchronous HTTP requests was known well before the arrival of Web 2.0 but was mostly underutilized. Libraries such as jQuery, but also Scriptaculous, MooTools, and more, began using AJAX and offering desktop-like interactivities in the browser.

One problem that quickly arose was the handling of data across shared views. Backbone, Knockout, and Ember were the most popular libraries that mitigated to solve that problem. In 2010, AngularJS came to light; this was a complex Model View Controller (MVC)-based framework with a very specific and prescribed way of doing things.

In May 2013, React was presented in the US and the web development world was able to witness numerous innovations – virtual DOM, one-way data flow, the Flux pattern, and more.

This is a bit of history to just try and provide some context and continuity because web development, like any other creative human activity, rarely moves in quantum leaps. Usually, it moves in steps that enable users to resolve the issues that they are facing in an, often, suboptimal way. It would be unfair not to mention Vue.js, which is an excellent choice for building frontends that also sports an entire ecosystem of libraries, and Svelte.js, which offers a radical shift in building UIs in the sense that the UI is compiled and the bundled size is significantly smaller.

Why use React?

As of 2022, interactive, attractive, fast, and intuitive UIs are a necessity for any public-facing web application. It is possible, though very difficult, to achieve most or every functionality that even a simple web is expected to provide using just plain JavaScript. FastAPI is more than capable of serving HTML (and static files, such as JavaScript or CSS) using any compatible templating engine (the most widely used in the Python world is probably Jinja2), but we and the users want more:

Figure 1.2 – The FARM stack

Figure 1.2 – The FARM stack

First of all, we want a streamlined and structured way of building UIs. React enables the developers to create dynamic applications in a much easier way by relying on JSX – a mix of JavaScript and XML that has an intuitive tag-based syntax and provides developers with a way to think of the application in terms of components that go on to form other, more complex, components, thus breaking the process of crafting complex user interfaces and interactions into smaller, more manageable steps.

The main benefits of using React as a frontend solution can be summarized as follows:

  • Performance: By using the React virtual DOM, which operates in memory, React apps provide smooth and fast performance.
  • Reusability: Since the app is built by using components that have their own properties and logic, we can write out components once and then reuse them as many times as needed, cutting down development time and complexity.
  • Ease of use: This is always a bit subjective, but React is easy to get started. Advanced concepts and patterns require some level of proficiency, but even novice developers can reap immediate benefits just from the possibility of splitting the application frontend into components and then using them like LEGO bricks.
  • SPAs or SSR: React and frameworks based on React empower us, the developers, to create Single-Page Applications that have a desktop-like look and feel but also server-side rendering that is beneficial for search engine optimization.
  • React-based frameworks: Knowing our way around React enables us to benefit from some of today’s most powerful frontend web frameworks such as Next.js, static site generators (such as Gatsby.js), or exciting and promising newcomers (such as React Remix).
  • Hooks system: In version 16.8, the React library introduced hooks that enable the developers to use and manipulate the state of the components, along with some other features of React without the need to use classes. This is a big change that tackles (successfully) different issues: it enables the reusability of stateful logic between components and simplifies the understanding and management of complex components.

The simplest React hook is probably the useState hook – it enables us to have and maintain a stateful value (such as an object, array, or variable) throughout the life cycle of the component, without having to resort to old-school class-based components.

For instance, a very simple component that could be used for filtering search results when a user is trying to find the right car might contain the desired brand, model, and some production year range. This functionality would be a great candidate for a separate component – a search component that would need to maintain the state of different input controls – probably implemented as a series of dropdowns. Let’s just see the simplest possible version of this implementation. We will create a simple functional component with a single stateful string value – an HTML select element that will update the stateful variable named brand:

import { useState } from "react";
const Search = () => {
  const [brand, setBrand] = useState("");
  return (
    <div>
      <div>Selected brand: {brand}</div>
      <select onChange={(ev) => 
          setBrand(ev.target.value)}>
        <option value="">All brands</option>
        <option value="Fiat">Fiat</option>
        <option value="Ford">Ford</option>
        <option value="Renault">Renault</option>
        <option value="Opel">Opel</option>
      </select>
    </div>
  );
};
export default Search;

The bold line is where the hook magic happens, and it must be within the body of a function. The statement simply creates a new state variable, called brand, and provides us a setter function that can be used inside the component to set the desired value.

There are many hooks that solve different problems, and in this book, we will go over the fundamental ones. In this example, the state variable brand is available inside the component, and it could be tied to a query string that would enable the API to only return the results that conform to the filter defined by the state variable.

  • Declarative views: In React, we do not have to worry about transitions or mutations of the DOM. React handles everything, and the only thing the developer has to do is to declare how the view looks and reacts.
  • No templating language: React practically used JavaScript as a templating language (through JSX), so all you have to know in order to be able to use it effectively is some JavaScript, such as array manipulation and iteration.
  • Rich ecosystem: There are numerous excellent libraries that complement React’s basic functionality – from routers to custom hooks, external library integrations, CSS framework adaptations, and more.

In this book, we will not dive deep into React. Why not? Well, I believe that the UI is as important as any other part of the app – if your app is not user-friendly or downright ugly, nobody will want to have anything to do with it, no matter how much value it brings. However, that is not the emphasis of this book. The idea is just to get the ball rolling and see how all the different parts connect and fit within the bigger picture. So, we will keep the frontend part to a minimum. Another reason to choose React is because of its great community, so you are bound to have to deal with it someday if you haven’t already, and to be quite honest, with the addition of React Hooks, at least for me, it has become very pleasant to work with. Hooks provide React with a new way of adding and sharing stateful logic across components and can even replace (in simpler cases) the need for Redux or other external state management libraries. We will make use of the Context API – a React feature that enables us to pass objects and functions down the component tree without the need of passing props through components that do not need it. Coupled with a hook – the useContext hook – it provides a straightforward way of passing and maintaining stateful values in every part of the app. Just being able to create declarative reusable components and parametrize them into functions was what got me interested – treating visual and UI components like functions with a state if you will. Compared to other frameworks, React is small. It isn’t even considered a framework but a library – actually, a couple of libraries. Still, it is a mature product with over 10 years of development behind it, created for the needs of Facebook, and the biggest internet companies such as Uber, Twitter, and Airbnb use and rely upon it.

Like FastAPI, which is based on the newest and coolest Python features and, thus, makes maximum use of what the language has to offer, React uses (although it is not imperative) the newest features of functional JavaScript, ES6, and ES7, particularly when it comes to arrays. As someone said, working with React improves our understanding of JavaScript, and a similar thing could be said of FastAPI and modern Python.

The final piece of the puzzle will be the choice of a CSS library or framework. In 2022, there are dozens of CSS libraries that play nice with React, ranging from Bootstrap, Material UI, Bulma, and more. Many of these libraries merge with React to become meaningful frameworks of prebuilt customizable and parametrized components. We will use Tailwind CSS as it is simple to set up – all the cool kids are using it, and it is intuitive once you get the hang of it, but more on that later.

Keeping the React part to a bare minimum should allow you, the reader, to focus more on the true protagonists of the story – FastAPI and MongoDB and their dance – and easily replace the React part, should you wish to do so, with anything else that rocks your boat, be it Svelte.js, Vue.js, or vanilla handcrafted ECMAScript.

However, you should know that by embracing or, at the very least, learning the basics of React (and Hooks), you are embarking on a wonderful web development adventure that will enable you to use and understand many tools and frameworks built on top of React.

Arguably, Next.js is the feature-richest server-side rendering React framework that enables fast development, filesystem-based routing, and more. Gatsby, a React-based static site generator, is a great tool for crafting blazingly fast sites and, coupled with a headless CMS, enables us to create simple and streamlined workflows suited for non-technical staff. React-Remix seems to be an interesting project, with a lot of the new React features baked in. Lastly, learning one major frontend framework, be it React, Svelte, or Vue, enables you to switch to another much easier one – the problems they are trying to solve are pretty much the same, and the solutions and underlying philosophies have many things in common even if the implementations might differ drastically.

 

Summary

In this chapter, we laid the background for the FARM stack, from describing the role of each component to their strengths. Hopefully, I have managed to get you interested in exploring the FARM stack. Now you understand how to make a conscious and informed decision and adopt the FARM stack for your next project, and you can justify your choice within the context of a flexible and fluid web development project specification. In the next chapter, we will provide a fast-paced, concise, and actionable overview of MongoDB and its querying and aggregation functionalities, with emphasis on the Python ecosystem.

About the Author
Full Stack FastAPI, React, and MongoDB
Unlock this book and the full library FREE for 7 days
Start now