Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Full Stack FastAPI, React, and MongoDB
Full Stack FastAPI, React, and MongoDB

Full Stack FastAPI, React, and MongoDB: Build Python web applications with the FARM stack

Arrow left icon
Profile Icon Marko Aleksendrić
Arrow right icon
$22.99 $33.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
eBook Sep 2022 336 pages 1st Edition
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Marko Aleksendrić
Arrow right icon
$22.99 $33.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (6 Ratings)
eBook Sep 2022 336 pages 1st Edition
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$22.99 $33.99
Paperback
$41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Full Stack FastAPI, React, and MongoDB

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to build web applications without having to know the intricacies of the components
  • Build full stack projects without compromising on development speed and app performance
  • Prepare yourself for the diverse world of web development, analytics, and data visualization

Description

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.

Who is this book for?

This book is for web developers and analysts who want to include the power of a modern asynchronous Python framework, a flexible data store and a powerful UI library with the combination of two of the most important programming languages today in their web development toolkit. Beginners in the field of information presentation will also find this book helpful. You must have a beginner-level understanding of Python, JavaScript, and HTML and CSS to get the most out of this book.

What you will learn

  • Discover the flexibility of the FARM stack
  • Implement complete JWT authentication with FastAPI
  • Explore the various Python drivers for MongoDB
  • Discover the problems that React libraries solve
  • Build simple and medium web applications with the FARM stack
  • Dive into server-side rendering with Next.js
  • Deploy your app with Heroku, Vercel, Ubuntu Server and Netlify
  • Understand how to deploy and cache a FastAPI backend

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 23, 2022
Length: 336 pages
Edition : 1st
Language : English
ISBN-13 : 9781803249445
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 23, 2022
Length: 336 pages
Edition : 1st
Language : English
ISBN-13 : 9781803249445
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 130.97
Building Python Microservices with FastAPI
$46.99
Building Python Web APIs with FastAPI
$41.99
Full Stack FastAPI, React, and MongoDB
$41.99
Total $ 130.97 Stars icon
Banner background image

Table of Contents

16 Chapters
Part 1 – Introduction to the FARM Stack and the Components Chevron down icon Chevron up icon
Chapter 1: Web Development and the FARM Stack Chevron down icon Chevron up icon
Chapter 2: Setting Up the Document Store with MongoDB Chevron down icon Chevron up icon
Chapter 3: Getting Started with FastAPI Chevron down icon Chevron up icon
Chapter 4: Setting Up a React Workflow Chevron down icon Chevron up icon
Part 2 – Parts of the Stack Working Together Chevron down icon Chevron up icon
Chapter 5: Building the Backend for Our Application Chevron down icon Chevron up icon
Chapter 6: Building the Frontend of the Application Chevron down icon Chevron up icon
Chapter 7: Authentication and Authorization Chevron down icon Chevron up icon
Part 3 – Deployment and Final Thoughts Chevron down icon Chevron up icon
Chapter 8: Server-Side Rendering and Image Processing with FastAPI and Next.js Chevron down icon Chevron up icon
Chapter 9: Building a Data Visualization App with the FARM Stack Chevron down icon Chevron up icon
Chapter 10: Caching with Redis and Deployment on Ubuntu (DigitalOcean) and Netlify Chevron down icon Chevron up icon
Chapter 11: Useful Resources and Project Ideas Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(6 Ratings)
5 star 50%
4 star 16.7%
3 star 16.7%
2 star 16.7%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Yondela Myataza Jul 29, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Amazon Customer Oct 28, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Full stack clearly explained, not just code but a proper explanation of the choice of each tool.
Amazon Verified review Amazon
RUI WANG Sep 30, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I love how this book covers both frontend and backend of the application. The author walks you step by step on how to work in MongoDB, so I rarely confused because of the detailed and clear writing. This was my first time reading a coding book and I had a great experience! Very new learner friendly.
Amazon Verified review Amazon
Luiz Eduardo Fonseca Oct 24, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
In this book the author talks about the so-called FARM stack for Web Development. The book goes into detail on how to set environments, MongoDB and friends, CRUD operations, and REST API. Then it shows how to build the backend and frontend and how to tie it all together using authentication. Overall very enjoyable book.
Amazon Verified review Amazon
Tim McKay Dec 19, 2023
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This book was released in August 2022.I worked through it in December 2023.Many of the Python packages used in this book were very out of date, and introduced numerous breaking changes.For instance, Pydandic V2 has several breaking changes from V1 from the book. I had to spend a lot of time and frustration patching the code with snippits online just to get the book examples to run. Chapter 5 is where things really started to fall down.I did learn a lot in this book. In particular, how the requirements.txt works. I wish the book (or GitHub repo for the book) would of included a frozen versioned requirements.txt so that there would have been more success in learning the FastAPI and MongoDB stack, and not wasting time troubleshooting my environments.On top of that, there were NUMEROUS errors in the text of the book. References to code was done haphazardly. Like numerous references to a cars/models.py file, when it was actually models/cars.py.Often long code snippits were broken into pieces so the author could break in to explain. None of the snippits were labelled, so sometimes it was unclear if a new snippit was a continuation or an entirely new .py file.Fundamentally, the book definately delivered on conveying the core essentials of a React, Python/FastAPI, MongoDB application stack. I learned a LOT. I went into this wanting to learn more about the backend side than the front end (I want to use this stack for Flutter mobile app development). Hands down, this author earned big points from me for being aligned perfectly in that regard.Overall, amazing exposure to many core and side topics (redis, machine learning [though, didnt work]). I have a foundation and a working code base that I can start from in order to move my learning forward. I just wish this wasn't my most frustrating technical book experience of the past 20 years. I feel that Frodo had an easier time getting the ring to Mordor.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.