Farm Stack Explained

Alongside the other stacks, like MERN and MEAN, another stack is rapidly picking up popularity: the FARM stack.

The FARM stack has a learning curve similar to the MEAN stack and MERN stack due to its utilization of technologies like MongoDB and React. Using a combination of FastAPI, React, and MongoDB, it greatly enhances application performance, speed, and ease of development.

Table of contents:

FARM stack explained

FARM stack is a technology stack that brings four of the most popular technologies together:

  • FastAPI — a Python-based, back-end framework
  • React — front-end JavaScript library
  • MongoDB — the flexible schema NoSQL database

Technology stack

A technology stack is a stack of various front-end, back-end, and database technologies that work together to create an end-to-end application, like a web application. A technology stack can be pre-built — like the MEAN, MERN, and FARM stacks — or customized depending on your specific business use cases.

The FARM stack is a full technology stack that uses the front end (React), back end (Fast API), and database (MongoDB). A good tech stack should be scalable, cost-effective, and optimized for speed and performance.

An image breaking down Farm Stack.

Typically, the front end (the user-/client-facing side) of an application is built from technologies like HTML, CSS, and JavaScript. React is a library built on these technologies that provides an enhanced developer and user experience.

The back end consists of a web server and the server-side programming language. This is where the application’s business logic resides. In the FARM stack, we use the FastAPI, a lightning-fast web framework built on top of the Starlette framework.

FastAPI is quickly gaining momentum due to its striking features, like in-built data validation and automatic interactive API documentation. Fast API is based on Asynchronous Server Gateway Interface (ASGI) which means it supports asynchronous programming, making it incredibly fast.

The bottom layer of the stack is the database layer that acts as a storage hub for all the data. Due to the nature of today’s data — which can come from multiple sources, be in different formats, and is huge in nature — we need a database that can handle such unstructured data with flexibility.

MongoDB, the most popular NoSQL database, provides the perfect platform to store, process, analyze, and retrieve the big data that businesses want to capture. MongoDB’s rich query language, aggregations, and many other features ensure your application gets exactly the data that you are looking for, saving developers from writing code for extensive manipulations and transformations on the data.

Features that make the FARM stack different

FARM stack has a combination of powerful technologies that allow for rapid development, can easily handle multiple concurrent connections through coroutines, and are easy to learn.

  • FastAPI is built on top of the Starlette library that uses the ASGI to build async web services in Python. Async applications allow for concurrent connections and can work on a large number of requests in parallel. They are well-suited for high-performance applications.
  • FastAPI provides in-built data validation using the pydantic library and uses the swagger UI to create API documentation automatically, thus eliminating the need for any other tools to test or run the application.
  • Using React makes applications more interactive and dynamic. React breaks down the front end into smaller components and provides features like JavaScript Syntax Extension (JSX), hooks, and virtual DOM, which make building user interfaces easier and faster. React is the most popular library for creating single-page applications.
  • Unlike traditional databases, MongoDB lets you store data in a flexible structure, so as your data grows or changes, you can easily accommodate data changes or schema changes without server downtime. Further, you can store data in a JSON-like format, which makes it easy to retrieve and present data across various layers. MongoDB also offers horizontal scaling as your user base grows, through sharding.

How does the FARM stack work?

The FARM stack is simple to understand with a minimal learning curve. You only need to be familiar with JavaScript, Python, and MongoDB, and you can easily build projects. These technologies are useful for many other stacks and businesses as well, so learning these could prove to be essential for your career.

An image breaking down how farm stack works with MongoDB.

A user can perform one of the following operations on the application:

HTTP Request

  • POST
  • GET
  • PUT
  • DELETE

Corresponding CRUD operation

  • C = Create/Insert
  • R = Read
  • U = Update
  • D = Delete

 

Whenever the user places an HTTP request for any of these, React constructs the request with the necessary parameters and sends it to the back-end server. In the back end, FastAPI routes the request to the appropriate method and invokes the appropriate database method to perform the operation. Once the query is successfully executed at the database level, the response is received and processed by the back end and sent to the React front end. React then displays the success/failure message to the user.

React front end

The React JS library expedites the development of production-ready, front-end applications by providing many out-of-the-box common utilities and components that can be reused. As part of the FARM stack, React is used to send HTTP requests to the back end and display the back end response to the front end.

React JS uses virtual DOM, which updates only the modified parts of the application and not the entire tree structure. This makes the application fast. Another notable feature is the JSX (JavaScript Extension) syntax, through which you can add JavaScript elements inside HTML tags. So, any change in the value of the element is immediately reflected without the need for a refresh or server restart.

Consider a simple HTTP request placed by a user to update their mobile number. React stores the data entered by the user using a simple hook (useState).

React

This data will be sent to the application layer using the PUT request in JSON format.

React

As the FARM stack supports asynchronous programming, we can use the axios JS library that is promise-based and supports all browsers. By using axios, we can abstract the complexity of creating and configuring HTTP requests.

Although React accepts many data formats, JSON format is most preferred as it is lightweight and uses less bandwidth.

FastAPI

FastAPI is an asynchronous web framework based on Python. In the FARM stack, Fast API acts as the middleware that processes the HTTP requests received from the React app and sends the response back. FastAPI runs on the uvicorn server, which is based on the ASGI server specification for asynchronous web servers.

Fast API leverages non–blocking I/O operations to take care of multiple concurrent loads through coroutines. For example, if there are multiple requests coming in to update a mobile number on an online portal, instead of blocking resources, FastAPI will create a coroutine, where it can parallelly process multiple requests.

Suppose there are five concurrent requests to update a mobile number. If each of them were to be processed one by one, it would be a waste of CPU and time. Using the async keyword from the asyncio library of Python, we can start processing the requests in parallel. Let’s say the first request is waiting for the fetch results (finding the mobile number to update). This wait time can be used to initiate the second request, and so on. This way, each request is completely independent of others and there is no block or wait.

An image example of how FastAPI works.

In the above coroutine, main() is the entry point of the program following which each request is processed asynchronously as a separate coroutine.

The web framework provided by FastAPI provides:

  • Full support for asynchronous programming, thus giving high performance.
  • Dependency injection, i.e., declaring the project dependencies and injecting them during runtime.
  • Data validation and serialization using the pydantic library.
  • Asynchronous programming using the asyncio python library.
  • Automatic API documentation for the API endpoints using Swagger.
  • Type hinting and annotations.

An image example of how FastAPI application framework.
Creating REST APIs using FastAPI

We can use Python decorators (@app.get, @app.put, and so on) to define the HTTP requests and routing paths.

Python

Next, you can access the input data using the path or query parameters of the request. Using the pydantic library will take care of the data validation.

You can then create the asynchronous function which updates the mobile number in the MongoDB database collection:

React

In a real-world case, you most likely want to update the mobile number based on some criterion, like a customer_id. In that case, you can add a path parameter in the FastAPI endpoint (routing URL):

Python

The asynchronous function to update the mobile number will take the customer_id along with the mobile number to update, as a parameter:

React

The “result” is a BSON document, which is automatically converted to a Python dictionary by the asynchronous driver motor. FastAPI then converts it to a JSON response.

You can also construct a custom response based on the result, in the FastAPI code.

React

The React application uses hooks to set a variable state, so you can simply set the response into the variable and React will display it on the front-end page:

React

FastAPI uses dependencies to provide built-in support for managing permissions and role-based access control — for example, authenticating a user or authorizing access to a route.

Asynchronous Server Gateway Interface (ASGI)

ASGI provides specifications to build asynchronous applications and servers in Python. This allows applications to perform I/O operations like database queries or network requests without blocking other operations. ASGI is designed to handle long-lived connections in addition to the usual HTTP request and response. This feature makes them useful for real-time applications, where bidirectional communication between the client and server is necessary.

Uvicorn web server

Uvicorn is an asynchronous web server based on the ASGI specifications. It provides high performance and is much suited to efficiently handle high application loads. Python developers using Fast API can use the uvicorn server to deploy and manage their applications. Uvicorn also supports web sockets. FastAPI is compatible with a few other servers, like Hypercorn and Quart, but uvicorn is preferred due to its performance and stability.

Motor async driver

motor is an async driver to connect FastAPI (Python) and MongoDB. It is similar to the pymongo driver but for asynchronous applications. motor works well with the community or enterprise version of the MongoDB server too. To learn more about motor, visit the documentation page.

MongoDB data platform

MongoDB is the data layer that stores and retrieves data as required by the application.

MongoDB is a document database that stores data in a JSON-like format known as BSON (Binary JavaScript Object Notation). Due to its document model, MongoDB provides high flexibility in storing data and easily accommodates any schema changes.

MongoDB databases come in various flavors — the MongoDB enterprise database, the MongoDB community database, and the cloud database (Atlas). With MongoDB Atlas, you do not need to install anything. Just create a free account and you can spin up a cluster.

MongoDB provides efficient data modeling options to optimize performance while keeping data consistency and flexibility intact. For example, to create data models for your FARM stack application, you can define the workload and identify the different types of relationships between the main entities — a 1:1, 1:many, or a many:many relationship. Based on this, you can decide on your document structure. MongoDB follows a simple rule that data that is accessed together should be stored together. You can choose to embed all the relevant details of an entity into a single document, or normalize the data and reference it using identifiers (like in a relational database).

MongoDB Atlas is a cloud data development platform that provides comprehensive features to manage modern applications — for example, built-in high availability and fault tolerance, automated backup and restore, vertical and horizontal scalability, automated server provisioning, setup, configuration, and patching.

MongoDB’s rich aggregation framework coupled with Python’s extensive scientific libraries are best suited for today’s AI and machine learning use cases, like fraud detection, real-time data analysis, targeted customer recommendations, analyzing user behavior, and so on. Using MongoDB Atlas gets you access to additional features like Atlas Search, MongoDB Charts, App Services, BI tools Connector, data federation, stream processing, and much more.

To create a MongoDB connection from the FastAPI back end, you simply set the URL and then open the database collection:

React

Once you establish the connection and get the database, you can use them to perform any CRUD operations using the appropriate methods — for example, the update_one() method we used in the FastAPI section.

You can create a complete FARM stack application using our TODO application for guidance on the end-to-end code and setup required for building your application.

Full Stack FastAPI App Generator for Python developers

MongoDB provides the Full Stack FastAPI App Generator for Python developers. Previously, Python developers had to manually integrate components like authentication, testing, and integration into the main application. The MongoDB Full Stack FastAPI App Generator provides a well-structured app skeleton, thus making the initial project setup simple. Some of the key features of the app generator are:

  • A complete web application stack by integrating front-end and back-end components.
  • A built-in authentication system.
  • Operational and monitoring tools.

FARM stack vs MERN stack

Both the FARM and MERN stacks use React and MongoDB which provide high flexibility and performance. The difference comes in the use of Node.js vs FastAPI, and choosing one of the two stacks depends on your business use case or personal preference.

  • The MERN stack has a shorter learning curve as a developer only needs to learn and write JavaScript code for both the back end and front ends, whereas for the FARM stack, one needs to learn Python as well. Further, the MERN stack provides a unified experience and better code readability and maintainability.
  • Node.js enjoys more community support and has a wealth of documentation for a large number of use cases and domains.

That said, FastAPI scores much better when it comes to data analysis and data science support:

  • Python has a vast ecosystem of advanced libraries for data science and machine learning tasks, making it easy to add analytics and data processing pipelines into web applications. While Node.js does support these libraries, they are not as exhaustive as Python libraries.
  • FastAPI's intuitive API design, automatic OpenAPI documentation generation, and built-in support for data validation simplify API development and make it accessible to developers of all skill levels. Node.js might be tricky to learn for a beginner due to the concepts of callback-based programming and the complexity of managing dependencies.
  • While Python is strictly typed, JavaScript is loosely typed, which could lead to runtime errors.

Use cases for the FARM stack

The FARM stack is suitable for a wide range of use cases in various domains and industries, some of which are listed below:

  • Building dynamic and interactive websites and web pages: On the front end, React provides an interactive and real-time experience to users, while the back-end FastAPI lets you create robust REST APIs to handle authentication, authorization, and transactions. MongoDB, due to its flexible schema, easily accommodates evolving application requirements and varying data structures — for example, e-commerce platforms and content management systems.
  • AI and data analytics: Using the power of the MongoDB aggregation framework and the Python data science libraries, the FARM stack provides a robust foundation for developers to build systems for data processing, real-time analytics, deriving practical insights, and visual report generation. React front-end can be utilized for interactive dashboards and data exploration.
  • IoT (Internet of Things) applications: By using React, developers can create a smooth interface for remote monitoring and control. FastAPI handles services like data ingestion, device communication, and routing. MongoDB can store the sensor data, metadata, and logs and can be used for analysis and anomaly detection.
  • Chat applications: React’s real-time rendering capabilities enable smooth, real-time communication between the chat agent and users. FastAPI’s routing capabilities and websocket support allow for handling HTTP requests for authentication, real-time messaging, and bi-directional communication. MongoDB’s flexible and scalable architecture makes it highly suitable for handling dynamic and evolving chat data.

Summary

The FARM stack is a promising technology stack and offers a powerhouse of features to build highly flexible, scalable, and performant applications. In the coming days, you can expect more innovations and advancements in the technologies, with more focus on enhancing the developer experience and productivity, automation, and integration with other technologies to facilitate new use cases and applications. To get started with the FARM stack, watch the MongoDB.live tutorial.

FAQs

Get Started With MongoDB Atlas

Illustration of the database.