Movatterモバイル変換


[0]ホーム

URL:


Packt
Search iconClose icon
Search icon CANCEL
Subscription
0
Cart icon
Your Cart(0 item)
Close icon
You have no products in your basket yet
Save more on your purchases!discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Profile icon
Account
Close icon

Change country

Modal Close icon
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timerSALE ENDS IN
0Days
:
00Hours
:
00Minutes
:
00Seconds
Home> Web Development> Full Stack Web Development> Full Stack FastAPI, React, and MongoDB
Full Stack FastAPI, React, and MongoDB
Full Stack FastAPI, React, and MongoDB

Full Stack FastAPI, React, and MongoDB: Fast-paced web app development with the FARM stack , Second Edition

Arrow left icon
Profile Icon Marko AleksendrićProfile Icon Shrey BatraProfile Icon Rachelle PalmerProfile Icon Shubham Ranjan
Arrow right icon
$59.99
Full star iconFull star iconFull star iconFull star iconFull star icon5(1 Ratings)
eBookAug 2024312 pages2nd Edition
eBook
$59.99
Paperback
$74.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Marko AleksendrićProfile Icon Shrey BatraProfile Icon Rachelle PalmerProfile Icon Shubham Ranjan
Arrow right icon
$59.99
Full star iconFull star iconFull star iconFull star iconFull star icon5(1 Ratings)
eBookAug 2024312 pages2nd Edition
eBook
$59.99
Paperback
$74.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$59.99
Paperback
$74.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Table of content iconView table of contentsPreview book icon Preview Book

Full Stack FastAPI, React, and MongoDB

Web Development and theFARM Stack

Websites are built using a set of technology that is often called astack. Every component of the stack is responsible for one layer of the application. While in theory, you could combine any type of frontend technology with any type of backend technology and, thus, end up with a custom stack, some have proven their worth in terms of agility and reduced development time. If you are a web developer or an analyst who must put some data online from time to time, or you just want to broaden your developer horizons, this chapter should give you some perspective on this set of tools, and how they compare toalternative technologies.

This chapter provides an overview of today’s web development landscape in terms of the available technologies and demands, and at the end of this chapter, we will make a case for using theFARM stack—a combination ofFastAPI for the REST API layer,React for the frontend, andMongoDB asthe database.

This book focuses on the high-level concepts of the technologies that constitute the FARM stack. By learning these concepts, you will be able to develop your next web development project at a fast pace and with modern capabilities. For now, we will not go into details or concrete examples, but rather compare the selected stack components (MongoDB, FastAPI, and React) with theirpossible counterparts.

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 is a great fit for web apps that have fluid specifications—both in terms of the data handled anddesired functionalities.

This chapter will cover thefollowing topics:

  • What is the FARM stack and how do the componentsfit together?
  • Why use MongoDB fordata storage?
  • Whatis FastAPI?
  • The frontend—React

Technical requirements

For this book, you’ll need a few things to aid you in your journey. The followingare recommendations:

Let’s begin with a very basic understanding of what the FARMstack is.

What is the FARM stack?

Stacks are sets of technologies that cover different parts of a modern web app, blended and well integrated. The right stack will enable you to satisfy certain criteria while building a web application, with considerably less effort and in less time than building itfrom scratch.

First, let’s see what you need to build a functionalweb application:

  • An operating system: Usually, thisis Unix/Linux-based.
  • A storage layer: A SQL or NoSQL database. In this book, we’lluse MongoDB.
  • A web server: Apache and NGINX are quite popular, but we will talk about Python solutions for FastAPI, such as Uvicornor Hypercorn.
  • A development environment: Node.js/JavaScript, .NET, Java,or Python.

Optionally, and often, you 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 compliance with standards. In addition, user expectations have shifted over time. There are unsaid standards for what logins, buttons, menus, and other website elements should look like, and how they function. Using a framework will make your application more consistent with the modern web and go a long way towarduser satisfaction.

The most famous stacks areas follows:

  • MERN:MongoDB + Express.js + React + Node.js (MERN)is probably one of the most popular stacks 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 such as Electron.js for desktop apps, a product can encompass virtually every platform while relying solelyon JavaScript.
  • MEAN:MongoDB + Express.js + Angular.js + Node.js (MEAN) is similar to the previously mentioned MERN, with Angular.js managing the frontend in a more structuredModel–View–Controller (MVC) way.
  • LAMP:Linux + Apache + MySQL + PHP (LAMP) is probably the first stack acronym to gain popularity and one of the most widely used in the past 20 years. It is still quitepopular today.

The first two 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 suchas Nest.js.

Since this is a Python book, we will also go through some important Python frameworks. The top three most popular frameworks for Python developers areDjango,Flask, andFastAPI. Using the Django web framework and the excellentDjango REST Framework (DRF) for building REST APIs in a modern and logical way is very popular. Django itself is very mature and well known among Python developers. It also has an admin site, the possibility of customizing and serializing REST responses, the option to choose between functional and class-based views,and more.

FastAPI, on the other hand, is a relative newcomer. First released in December 2018, this alternative, lightweight framework was fast to gain advocates. Almost immediately, these advocates had created a new acronym for FastAPI within thetech stack—FARM.

Let’s understand what FARMstands for:

  • FA stands for FastAPI—in technology years, a brand-new Pythonweb framework
  • R stands for React, the most popularUI library
  • M denotes the data layer—MongoDB, which is the most popular NoSQL databaseavailable today

Figure 1.1 provides a high-level overview of the integrations between the constituent parts involved in theFARM stack:

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

Figure 1.1: FARM stack with its components

As you can see in the preceding diagram, the FARM stack is composed ofthree layers:

  1. The user performs an action using the client, which, in our case, will be based on React—this ultimately creates a bundle of HTML, Cascading Style Sheets (CSS),and JavaScript.
  2. This user action (a mouse click, a form submit, or some other event) then triggers an HTTP request (such asGET,POST,PUT, or another HTTP verb witha payload).
  3. Finally, this request gets processed by the REST APIservice (FastAPI).

The Python part is centered around FastAPI and optional dependencies and is served byUvicorn—a fast Python-based server. The backend is responsible for dispatching the appropriate database calls to MongoDB using various commands and queries (such asfindOne,find,create,update, and more) and using 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. If you useMotor, which is an asynchronous Python driver for MongoDB, these calls will behandled asynchronously.

Finally, returning to the diagram inFigure 1.1 and the arrow labeledJSON, 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 virtualDOM tree.

The next few sections will talk about the motivations behind the birth of the FARM stack. Why these technologies and, more importantly, why these technologies together? You will get a detailed introduction to 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, the sections will provide a high-level overview of each choice and underline the benefits that it can provide to a modern webdevelopment workflow.

Why the FARM stack?

The flexibility and simplicity of the stack, along with its components, give a real boost in terms of development speed, extensibility, and maintainability while allowing 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. This might be crucial if your product needs 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 canexperiment with.

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 typeof computing.

Why use MongoDB?

MongoDB is a free, fast, and scalable database with a JSON format and simple syntax. It enables flexible schemas and, thus, iterative and rapid development. MongoDB is able to accommodate data structures of varying complexities. Additionally, 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 such as Motor. 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 adecade ago.

The following are some other features that will be detailed for use inthis book:

  • 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, you can embed all comments into the blog post they respond to). Denormalizationis encouraged.
  • Simple, intuitive syntax: The methods for performing basiccreate,read,update,delete (CRUD) operations, coupled with powerful aggregation frameworks and projections, allow you to achieve almost all data reads quite easily through the use of drivers. The commands should be intuitive for anyone with a bit ofSQL experience.
  • Community and documentation: 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 everyprogramming language.

Of course, MongoDB is not a silver bullet, and some challenges are worth noticing upfront. On the one hand, the schema-less 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. You will see howPydantic—an excellent Python validation and type-enforcement library—can help you with stronger data integrity. The absence of complex joins, which are present in the SQL world, might be a dealbreaker for some typesof applications.

Now that you understand what MongoDB brings to the table in terms of scalability and flexibility, with its schema-less approach, take a look at the REST API framework of choice, FastAPI, and learn how it can help you implement that schema-less approach and simplify your interactions withthe data.

Why use FastAPI?

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

If you are not familiar with APIs, let’s get into it in more depth by understanding what an API is. Anapplication programming interface (API) is used to enable some kind of interaction between different pieces of software, and they communicate usingHypertext Transfer Protocol (HTTP) through a cycle of requests and responses. Therefore, an API is, as its name suggests, an interface. Via this interface, humans or machines interact with an application or a service. Every API provider should have an interface that is well suited for the type of data that they provide; for instance, a weather forecasting station provides an API that lists the temperatures and humidity levels for a certain location. Sports sites provide statistical data about the games that are being played. A pizza delivery API will provide you with the selected ingredients, the price, and the estimated timeof arrival.

APIs touch every aspect of your life, for example, transmitting medical data, enabling fast communications between applications, and even used in tractors in fields. APIs are what make today’s web run and, put simply, are the best form ofinformation exchange.

This chapter will not go over the rigorous definitions of REST APIs, but just list some of their mostimportant features:

  • 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 thesession itself.
  • Layered structure: 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 improvingoverall security.
  • Client-server architecture: APIs should be able to connect different systems/pieces of software without limiting their own functionalities—the server and the client have to stay separate and independent fromeach other.

There are numerous reasons why MongoDB chose FastAPI for their REST API layer, even though it’s new compared to other Python frameworks. Here are some ofthe reasons:

  • High performance: FastAPI can 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.jsand 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, you can use complex data validations, deeply nested JSON objects, and hierarchical models (using Python lists and dictionaries), and this relates very well with the natureof MongoDB.
  • Faster development: Development becomes more intuitive, with strongintegrated development environment (IDE) support, which leads to faster development time andfewer bugs.
  • Standards compliance: FastAPI is standard-based and fully compatible with open standards for building APIs—such as OpenAPI andJSON schema.
  • Logical structuring of apps: The framework allows the structuring of APIs and apps into multiple routers and allows granular request and response customization, and easy access to every part of theHTTP cycle.
  • Async support: FastAPI uses anasynchronous 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 theasyncio moduleinto Python.
  • Dependency injection: The dependency injection system in FastAPI is one of its biggest selling points. It enables the creation of complex functionalities that are easily reusable across your 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 theREST endpoints.
  • Great documentation: The documentation of the framework itself is excellent and second to none. It is both easy to followand extensive.
  • Automatic documentation: Being based on OpenAPI, FastAPI enables automatic documentation creation, which essentially means that you get your API documented for freewith Swagger.

Also, getting started isrelatively simple:

pip install fastapi

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

# main.pyfrom fastapi import FastAPIapp = 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 aGET request with the messageHello world. You can instantiate a FastAPI class and use decorators to tell the server which HTTP methods should trigger which function fora response.

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 andFlask 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 asbottle.py andCherryPy.

DRF is a plugin 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 isvery 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 enablingasync 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 havebeen created.

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

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 developer surveys1, FastAPI is quickly becoming one of the most popular and most lovedweb frameworks.

In later chapters of this book, you’ll go over the most important features of FastAPI, but at this point, we’ll 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, spitting out data to a frontend, and managing authentication and authorization, this Python pipeline enables you to quickly integrate and easily carry out frequently required tasks such as background jobs, header and body manipulation, response and request validation, and more through the dependencyinjection system.

The book will try to cover the absolute minimum necessary for you to be able to build a simple FastAPI system, but along the way it will consider various web server solutions and deployment options (such as Deta, Heroku, and DigitalOcean) for your FastAPI Python-based backend, while trying to opt forfree solutions.

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

After reviewing the backend components, it is time to finalize your stack and work on the frontend. The next section gives you a brief introduction to React and discusses what distinguishes it from other (alsovalid) solutions.

The frontend – React

The changes in the world of the web are most visible when talking 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, CSS was introduced and the web started looking a little nicer. Legend has it that the 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 theservers, too.

In May 2013, React was presented in the US and the web development world was able to witness 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. 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 issignificantly smaller.

Why use React?

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 application 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 userswant more.

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 utilized by the biggest companies such as Uber, X (formally known as Twitter),and Airbnb.

This book does not explore React in depth because we want to focus on how all the different parts of the FARM stack connect and fit within the bigger picture. Additionally, 81% of developers already use React2 and are familiar with its features, so we assume our readers have a level of familiarity with thisframework already.

Most developers want a streamlined and structured way of building UIs. React enables 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 UI and interactions into smaller, moremanageable steps.

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

  • Performance: By using the React virtual DOM, which operates in memory, React apps provide smooth andfast performance.
  • Reusability: Since the app is built by using components that have their own properties and logic, you can write out components once and then reuse them as many times as needed, cutting down development timeand 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 likeLEGO bricks.

React and frameworks based on React empower you, as a developer, 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. Knowing your way around React enables you 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 asReact Remix).

Inversion 16.8, the React library introducedHooks, which enable 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 successfully tackles different issues—it enables the reusability of stateful logic between components and simplifies the understanding and management ofcomplex components.

The simplest React Hook is probably theuseState Hook. This Hook enables you 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-schoolclass-based components.

For instance, a very simple component that could be used to filter search results when a user is trying to find the right car might contain the desired brand, model, and a 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 ofthis implementation.

The following block of code creates a simple functional component with a single stateful string value—an HTMLselect element that will update the stateful variablenamedbrand:

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, calledbrand, and provides you with a setter function that can be used inside the component to set thedesired value.

There are many Hooks that solve different problems, and this book will go over the followingfundamental ones:

  • Declarative views: In React, you do not have to worry about transitions or mutations of the DOM. React handles everything, and the only thing you have to do is declare how the view looksand reacts.
  • No templating language: React practically uses 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 manipulationand 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.

Ultimately, 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. Most of the examples shown in this book make use of the Context API—a React feature that enables passing objects and functions down the component tree without the need to pass props through components that do not need it. Coupled with a Hook—theuseContext Hook—it provides a straightforward way of passing and maintaining stateful values in every part ofthe app.

React uses (although it is not imperative) the newest features of functional JavaScript, ES6, and ES7, particularly when it comes to arrays. Working with React improves understanding of JavaScript, and a similar thing could be said of FastAPI andmodern Python.

The final piece of the puzzle will be the choice of a CSS library or framework. Currently, in 2024, there are dozens of CSS libraries that play nice with React, including Bootstrap, Material UI, Bulma, and more. Many of these libraries merge with React to become meaningful frameworks of prebuilt customizable and parameterized components. We will use Tailwind CSS as it is simple to set up—and it is intuitive once you get the hangof it.

Keeping the React part to a bare minimum should allow you to focus more on the true protagonists of the story—FastAPI and MongoDB. You can easily replace React, should you wish to do so, be it Svelte.js, Vue.js, or vanilla handcrafted ECMAScript. However, by 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 topof React.

Arguably, Next.js is the feature-richest server-side rendering React framework that enables fast development, filesystem-based routing,and more.

Summary

This chapter laid the background for the FARM stack, from describing the role of each component to their strengths. Now, you will be confident in choosing the FARM stack and you know how to implement it within the context of a flexible and fluid web development project. Since you’re reading this, I’ll assume that my case was compelling—that you’re still interested and ready to explore theFARM stack.

The next chapter will provide a fast-paced, concise, and actionable overview of MongoDB, and then set up your data storage layer for your FARM application. As you go along, we are confident that you will find the combination of FastAPI, React, and MongoDB to be the best choice for your nextweb application.

Left arrow icon

Page1 of 9

Right arrow icon
Download code iconDownload Code

Key benefits

  • Learn the basics of MongoDB to be able to model any type of data
  • Explore the powerful Python web development ecosystem with Pydantic and FastAPI
  • Future-proof your applications by integrating ChatGPT or other LLMs
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Discover how to harness the power of the FARM stack—FastAPI, React, and MongoDB—to develop production-ready web applications of varying complexity. Written by a team of industry experts, including MongoDB champions and product leaders, this fast-paced, hands-on guide equips beginners with essential skills to build web applications efficiently.Introducing each element of the stack, the book demonstrates how to seamlessly integrate them to create a medium-sized web application. You'll set up MongoDB as a document store, construct a simple API with FastAPI, and build an application using React. The guide also covers enhancing application security through authentication and authorization with JSON Web Tokens.Beyond mastering the stack, you'll get to grips with integrating Large Language Models (like ChatGPT) for advanced functionality, such as automated email sending. Additionally, you'll learn how to make the most of Next.js 14, a robust full-stack framework offering improved developer experience.By the end of the book, you'll have created functional applications and gained the foundation to explore diverse and more specialized domains, expanding your development horizons.

Who is this book for?

The book is for intermediate web developers with basic JavaScript and Python knowledge who want to enhance their developer skills, master a powerful and flexible stack, and write better applications faster.

What you will learn

  • Set up and manage MongoDB databases and collections, and model data
  • Leverage the power of FastAPI to write complex APIs using pure Python
  • Create frontends of varying complexity with the React library
  • Build and deploy robust and secure backends using FastAPI and MongoDB
  • Ship production-ready applications with Next.js 14, applying your React and backend knowledge
  • Integrate Large Language Models, send emails, and do much more with the flexible FARM stack

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date :Aug 23, 2024
Length:312 pages
Edition :2nd
Language :English
ISBN-13 :9781835886779
Vendor :
MongoDB
Languages :
Tools :

What do you get with eBook?

Product feature iconInstant access to your Digital eBook purchase
Product feature icon Download this book inEPUB andPDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature iconDRM FREE - Read whenever, wherever and however you want
Product feature iconAI Assistant (beta) to help accelerate your learning
OR

Contact Details

Modal Close icon
Payment Processing...
tickCompleted

Billing Address

Product Details

Publication date :Aug 23, 2024
Length:312 pages
Edition :2nd
Language :English
ISBN-13 :9781835886779
Vendor :
MongoDB
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

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

Frequently bought together


Building AI Intensive Python Applications
Building AI Intensive Python Applications
Read more
Sep 2024298 pages
eBook
eBook
$59.99
$74.99
Full Stack FastAPI, React, and MongoDB
Full Stack FastAPI, React, and MongoDB
Read more
Aug 2024312 pages
Full star icon5 (1)
eBook
eBook
$59.99
$74.99
Python Feature Engineering Cookbook
Python Feature Engineering Cookbook
Read more
Aug 2024396 pages
eBook
eBook
$31.99$35.99
$44.99
Stars icon
Total$194.97
Building AI Intensive Python Applications
$74.99
Full Stack FastAPI, React, and MongoDB
$74.99
Python Feature Engineering Cookbook
$44.99
Total$194.97Stars icon

Table of Contents

13 Chapters
Chapter 1: Web Development and the FARM StackChevron down iconChevron up icon
Chapter 1: Web Development and the FARM Stack
Technical requirements
What is the FARM stack?
Why the FARM stack?
Why use MongoDB?
Why use FastAPI?
Python and REST APIs
The frontend – React
Summary
Chapter 2: Setting Up the Database with MongoDBChevron down iconChevron up icon
Chapter 2: Setting Up the Database with MongoDB
Technical requirements
The structure of a MongoDB database
Installing MongoDB and related tools
Installing MongoDB and Compass on Windows
Installing the MongoDB Shell (mongosh)
MongoDB Database Tools
Installing MongoDB and Compass on Linux: Ubuntu
Setting up Atlas
MongoDB querying and CRUD operations
Querying in MongoDB
Summary
Chapter 3: Python Type Hints and PydanticChevron down iconChevron up icon
Chapter 3: Python Type Hints and Pydantic
Technical requirements
Python types
Type hinting
Pydantic
Summary
Chapter 4: Getting Started with FastAPIChevron down iconChevron up icon
Chapter 4: Getting Started with FastAPI
Technical requirements
FastAPI in a nutshell
Building a showcase API
Summary
Chapter 5: Setting Up a React WorkflowChevron down iconChevron up icon
Chapter 5: Setting Up a React Workflow
Technical requirements
Creating a React app using Vite
Components and building blocks of JSX
Communicating with APIs and the outside world using useEffect
Exploring React Router and other useful packages
Summary
Chapter 6: Authentication and AuthorizationChevron down iconChevron up icon
Chapter 6: Authentication and Authorization
Technical requirements
Understanding JSON Web Token
FastAPI backend with users and dependencies
Authenticating the users in React
Summary
Chapter 7: Building a Backend with FastAPIChevron down iconChevron up icon
Chapter 7: Building a Backend with FastAPI
Technical requirements
Introducing the application
Creating an Atlas instance and a collection
Scaffolding a FastAPI application
CRUD operations
Uploading images to Cloudinary
Adding the user model
FastAPI middleware and CORS
Deployment to Render.com
Summary
Chapter 8: Building the Frontend of the ApplicationChevron down iconChevron up icon
Chapter 8: Building the Frontend of the Application
Technical requirements
Creating a Vite React application
React Hook Form and Zod
Authentication context and storing the JWT
Summary
Chapter 9: Third-Party Services Integration with FastAPI and BeanieChevron down iconChevron up icon
Chapter 9: Third-Party Services Integration with FastAPI and Beanie
Technical requirements
Project outline
Building the backend with FastAPI and Beanie
Summary
Chapter 10: Web Development with Next.js 14Chevron down iconChevron up icon
Chapter 10: Web Development with Next.js 14
Technical requirements
Introduction to Next.js
Creating a Next.js 14 project
Authentication and Server Actions in Next.js
Deployment on Netlify
Summary
Chapter 11: Useful Resources and Project IdeasChevron down iconChevron up icon
Chapter 11: Useful Resources and Project Ideas
MongoDB considerations
FastAPI and Python considerations
Testing FastAPI applications
React practices
Other topics
Some project ideas to get started
Summary
IndexChevron down iconChevron up icon
Index
Why subscribe?
Other Books You May EnjoyChevron down iconChevron up icon
Other Books You May Enjoy
Packt is searching for authors like you
Download a free PDF copy of this book

Recommendations for you

Left arrow icon
Full-Stack Flask and React
Full-Stack Flask and React
Read more
Oct 2023408 pages
Full star icon3.8 (5)
eBook
eBook
$27.99$31.99
$39.99
Real-World Web Development with .NET 9
Real-World Web Development with .NET 9
Read more
Dec 2024578 pages
Full star icon3.5 (4)
eBook
eBook
$35.98$39.99
$49.99
Django 5 By Example
Django 5 By Example
Read more
Apr 2024820 pages
Full star icon4.6 (40)
eBook
eBook
$35.98$39.99
$49.99
React and React Native
React and React Native
Read more
Apr 2024518 pages
Full star icon4.3 (10)
eBook
eBook
$31.99$35.99
$43.99
Scalable Application Development with NestJS
Scalable Application Development with NestJS
Read more
Jan 2025612 pages
Full star icon4.5 (6)
eBook
eBook
$27.99$31.99
$39.99
Responsive Web Design with HTML5 and CSS
Responsive Web Design with HTML5 and CSS
Read more
Sep 2022504 pages
Full star icon4.5 (57)
eBook
eBook
$31.99$35.99
$44.99
$49.99
Modern Full-Stack React Projects
Modern Full-Stack React Projects
Read more
Jun 2024506 pages
Full star icon4.8 (9)
eBook
eBook
$31.99$35.99
$44.99
Learning Angular
Learning Angular
Read more
Jan 2025486 pages
Full star icon4 (6)
eBook
eBook
$29.99$33.99
$41.99
Right arrow icon

Customer reviews

Rating distribution
Full star iconFull star iconFull star iconFull star iconFull star icon5
(1 Ratings)
5 star100%
4 star0%
3 star0%
2 star0%
1 star0%
EmiruAug 31, 2024
Full star iconFull star iconFull star iconFull star iconFull star icon5
i have just started this book stumbled on it during a React Js class and was hesitant at first. I was blown away by the first few paragraphs and how the writter takes the time to explain why each of the technologies. I have just installed MongoDB and i can see this book being my companion for many years to come. Thank you.
Subscriber reviewPackt

About the 4 authors

Left arrow icon
Profile icon Marko Aleksendrić
Marko Aleksendrić
LinkedIn icon
Marko Aleksendrić is an analyst, a scientist, and a freelance self-taught web developer with over 20 years of experience. Marko has authored the book Modern Web Development with the FARM Stack and Mastering MongoDB 7.0, published by Packt Publishing. With a keen interest in backend and frontend development, he has been an avid MongoDB user for the last 15 years for various web and data analytics-related projects and has built numerous Python and JavaScript web applications and tools.
Read more
See other products by Marko Aleksendrić
Profile icon Shrey Batra
Shrey Batra
LinkedIn iconGithub icon
Shrey is the Founder of Cosmocloud, a MongoDB Champion, and a software developer by passion. As a tech startup founder building a No-Code backend with MongoDB, he combines his passion for both MongoDB and building applications at scale. Working in the industry for over 8 years, he is also an active contributor to the technical community, speaks at various world conferences and meetups, and writes his own newsletter, System Design and Architecture, which has 50K+ subscribers. He is also a distributed algorithm patent holder for his work at LinkedIn on its Search and Discovery platform.
Read more
See other products by Shrey Batra
Profile icon Rachelle Palmer
Rachelle Palmer
LinkedIn icon
Rachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the Director of the Technical Services Engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.
Read more
See other products by Rachelle Palmer
Profile icon Shubham Ranjan
Shubham Ranjan
LinkedIn icon
Shubham Ranjan is a Product Manager at MongoDB for Python and a core contributing member to AI initiatives at MongoDB. He is also a Python developer and has published over 700 technical articles on topics ranging from data science and ML to competitive programming. Since joining MongoDB in 2019, Shubham has held several roles, progressing from a Software Engineer to a Product Manager for multiple products.
Read more
See other products by Shubham Ranjan
Right arrow icon
Getfree 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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 iconChevron 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.


[8]ページ先頭

©2009-2025 Movatter.jp