Introducing FastAPI: A Modern Python Web Framework
Hello everybody and welcome back to another tutorial series. In this series, I'm going to be talking about FastAPI.
FastAPI is a relatively new Python framework that enables you to rapidly develop an API or back-end for your web or mobile application. If you've developed web applications in Python before, you probably use something like Flask or Django. Now, these frameworks are great and have been around more than a decade and will more than meet your needs, but you may be looking for something new.
I've recently been tasked with creating a new back-end for a new project and I wanted to see what's out there these days to use besides Flask and Django. And I recently discovered FastAPI, and after reviewing the documentation and building a sample application with FastAPI, I came away very impressed. The project seems—even though it hasn't been around that long, it seems very mature. The documentation is great, it has a lot of powerful features, and it seems a little bit easier to me to set up a nicely structured API using FastAPI.
So I thought I would check it out. And also, since I haven't seen a lot of videos or screencasts and tutorials out there on the web for FastAPI, I thought I'd contribute something back to the community for this framework and see if we can increase the adoption of FastAPI.
Project Demo: Building a Stock Screener Application
Since the main focus of this channel so far has been on building financial utilities and applications, I thought we'd build a web-based stock screener as an example application that uses FastAPI. So I'm going to do a quick demonstration of the final application that we'll be building.
We're going to be building a web-based stock screener. So I can click this 'add symbols' button and just add a bunch of ticker symbols. So let's say I choose Apple, Microsoft, Corning, and Procter & Gamble. I can click the 'add symbols' button and we're going to have FastAPI launch a background task that scrapes data from Yahoo Finance and pulls in the key statistics for each of these ticker symbols. And so now you can see in a table I'm displaying the last closing price, forward profit-earnings ratio, dividend yield, and the 50 and 200-day moving averages for each of these stock tickers.
We've added all the symbols to a SQLite database and also retrieved information from Yahoo Finance and updated all those records with key statistics. We also will allow you to query the database. So we can for instance enter 10 for the forward P/E and click filter, and it'll show us all the tickers in our database that have a forward profit-to-earnings ratio of less than 10. Do the same with dividend yield, all the stocks that have a dividend yield greater than 2%. And then we can also show, for instance, stocks above the 50-day or 200-day moving average. So you can see Microsoft has held up relatively well considering how far the market is down.
And we can add as many ticker symbols as we want. If you go to our GitHub repository at github.com/financetax, we do have datasets. So if you wanted to add all the stocks in the S&P 500, you can go in datasets here and I've already provided a dataset of all the ticker symbols in the S&P 500 if you want to load all of these. And so sp500_tickers has all those symbols, and you can basically build as large of a stock database as you want. You can determine other key statistics that you want to track and filter on and build whatever you need. This tutorial series will give you all the tools you need to be able to do that.
Tutorial Roadmap & Source Code
And if you don't want to follow along directly, you can look in the repository. I've already committed the code for 'stock_screener' and you can check out this code here and just get a head start. But I mean, in this series, I'm going to be building everything from the ground up, starting with an empty notepad.
But this is the final product. And I'm going to walk you through all these steps: from stubbing out the endpoints, mocking up the UI, designing the database, adding some real endpoints, and then wiring up the home screen and the modal and the filters in the UI to query our database. So feel free to follow along.
Key Feature: Automatic Data Validation with Pydantic
Now, back to FastAPI. Before I get started building this application, I'm going to show you a few of the features I like specifically about FastAPI. The first thing that FastAPI has that I like is it uses Pydantic, which allows you to define these schemas for auto-validation.
So whatever requests come in, it can automatically validate that that request has certain values and certain attributes. So if someone posts some JSON to your API, you can define a schema like this, like Item. And so you can define this model and say, oh, that payload needs to have a name that's a string, a description, a price, and a tax, right? And so if you do that and define all these schemas, then you know all the data that gets to your API is good, and it's validated for you automatically.
So in this create_item function, you can see I can specify a data type. So the request that comes in needs to be of type Item and needs to have all of these attributes.
Key Feature: Auto-Generated API Documentation
The second thing I like is that FastAPI is built on some open standards like JSON Schema and OpenAPI. And so you get this nice, automatically generated API documentation.
So this stock screener that I built—I just built my application like I would normally—but now I get this URL, /docs, and you see I have an automatically generated API docs here. So if I want to show the POST endpoint for adding a stock, I can experiment with my API from a UI on the web that's generated for me. And then I know this needs a payload with a symbol of type string. So it knows all this information because I've defined this signature on my function and said I need a certain Stock type, and its symbol has to be a string. And I can even use this API directly from the web and send it JSON and see what the response looks like.
Flask and Django can provide this functionality if you install some additional libraries and dependencies, but a nice thing about FastAPI is that a lot of this stuff is well thought out for you, and you don't have to go around searching for the right libraries to integrate with your web framework. You get this out of the box.
Key Feature: Simplified Dependency Injection
Another feature of FastAPI that I like so far is dependency injection. So if you've used frameworks like Flask, you need to bootstrap an application and import all these different functions and libraries and blueprints, and the structure can be actually a little confusing, and you can often run into weird circular dependency issues. But FastAPI seems to have had a well-thought-out solution to this out of the box.
And so if you look at some of the examples under dependency injection, you can see that you can specify a route which maps to a function, and you can say this function depends on some other function that runs first. So I'm saying commons depends on common_parameters, which will execute this function and do a little bit of work in advance. And you can use this for other things, like getting a database connection in advance or making sure the user is authenticated, so running some authentication logic before you get to the core functionality of this route.
Key Feature: Easy Background Tasks
Another feature of FastAPI I like is background tasks. If you'll notice earlier in the example application that I demoed, I added a number of symbols using this modal. I clicked 'add symbols' and I got an instant response. Now, I got that instant response even though in the background it fetched a lot of information from Yahoo Finance and went through each of the symbols, found the profit-to-earnings ratio, EPS, etc, etc. And it also had to update the database with all that information. Nonetheless, I didn't block the UI. I gave the user some instant feedback and was able to perform those tasks without really interrupting the flow.
So what enables that is the background tasks here. So in any function, I can also say background_tasks of type BackgroundTasks, and then I can add a new task and give it a function to run in the background. So in this example, they add a task to write some information to a log file.
Advanced Features and the Starlette Foundation
In addition to these features, FastAPI also has a ton of other advanced features that you may use, including WebSockets, GraphQL, JSON Web Tokens, support for any database libraries, etc, etc. So I'm not going to go over every feature that FastAPI has, but I will mention that FastAPI has a lot of out-of-the-box functionality because it's built on top of another framework called Starlette.
So Starlette is an application framework that was created by the author of the Django REST framework. And so it has a lot of features already and it's based on a lot of experience on building REST APIs using the Django REST framework. So a lot of this stuff is already really well thought out. So you can see Starlette here already had support for WebSockets, GraphQL, and testing, a lot of other functionality that you can dive into later.
Your First FastAPI App: A 'Hello, World' Example
The final thing I want to mention that I like about FastAPI is how easy it is to learn. I was familiar with Flask already and so learning FastAPI has been super easy so far. And to prove that, I'll show you the 'Hello, World' example real quick before we get started with a larger application.
So I'm going to go to the home page, and a few lines of code here I'll put up. And so I'm going to go to a new text editor, and main.py is what we're calling it. If you import FastAPI after installing it—so you install it with pip3 install fastapi. And if you install it, and you also install the web server called Uvicorn, it'll install that. And you can see all you got to do is import FastAPI, you create a new instance of FastAPI for your app, and you can map a route to a function just like Flask. So I say get / and then I just return a JSON response.
So all I'll do here is run the application. So I do uvicorn main:app --reload. And if I do that, we have a running API. And so I can do localhost:8000, it returns 'Hello World'. And then also you can see where you can define specific parameters. So if I pass in an item_id, so I'm defining a new route called /items/{item_id}. And if I do /items/3, we have it echo back the results, so it returns the item_id that's passed in.
This also demonstrates how you can access the query string in the URL. So if I go to /items/5?q=abc, you can see it picks up this named query parameter and we can do whatever we want with it in the function. This is just displaying it back to the user.
So you can see in about 30 seconds, we're able to get an API up and running using FastAPI. We're able to accept a couple simple requests and return some JSON to the user. So stay tuned for the next video in the series, and I'm going to go ahead and build out this stock screener application using FastAPI. And in the process, we're going to demonstrate all these features and how they come together. So thanks a lot, and stay tuned for the next video. Thanks.