Introduction to FastAPI
In this series of videos we're going to learn about FastAPI. This is probably the most popular up-and-coming framework in Python. We have of course, old-timers like Django and Flask which are excellent Frameworks but FastAPI is really making inroads in the Python API space. So we want to present a series here from the ground up where we look at the core features of FastAPI and later we will include things like authentication and authorization. We're going to look at different database utilities like SQL Alchemy, Tortoise ORM, and anything else of course that you want to see. Just leave some comments and let us know what you'd like to see and we'll consider making those videos.
What I'm going to do is dive in and we're going to start looking at FastAPI from the ground up. Now I have the FastAPI documentation open here and if you're not familiar with FastAPI, it's a high performance API framework for Python. And it uses a lot of the modern Python features such as async capabilities and also type hints and it is a very high performance framework as I've said before and it's on a par with NodeJS and Go. And that's thanks to the under the hood functionality provided by Starlette and Pydantic. We'll look at some of those later in this series.
Project Setup and Installation
So to get started, let's go to VS Code and I have an empty folder open here with a terminal at the bottom. What we're going to do to start with is just create a Python virtual environment and install FastAPI into that environment. So to do that, we can run python -m and I'm going to use the built-in venv module and we're going to call this environment vve-fastapi. So we can run that command and that as you can see on the left hand side has created a folder with the name we gave to the environment. And what this means is when we install requirements for this project, they're going to be installed in this environment but they're not going to affect the global Python installation, which is what we want.
So let's clear the terminal and we're going to go back to the documentation here and I'm going to go to the installation section. Now these these links will all be available below the video. And we have different ways of installing FastAPI. We can install it as a single library with the pip install fastapi command. So let's copy this command, we're going to install FastAPI and go back to VS Code.
What we're going to do now is we're going to actually activate the virtual environment. Now in Windows, what we do is we follow the link to the virtual environment's scripts directory and in that directory we have a script called activate. When we run that, that's going to activate the virtual environment and then we can install FastAPI in that environment. So I've installed that directly and as it says on the terminal, you may also want to upgrade pip when you first create a virtual environment, so we can run pip install -U pip in order to do that. And it is considered a best practice to upgrade pip when you create a virtual environment.
Now once that's finished, we have now got FastAPI installed. We're going to install the uvicorn standard package here. And we can do that again by pasting that pip install command in and that's going to install uvicorn alongside a bunch of packages that uvicorn will use.
Creating the First Endpoint
So now at this point, everything we need to get started is installed. What we're going to do on the left hand side is create a file which I'm going to call main.py. And at the top here, we're going to import the FastAPI object. We can do that by importing FastAPI from the FastAPI package. And this object is like the base object or the root object of a FastAPI application. It provides all of the functionality that you need to create an API in Python.
So how do we use the FastAPI object? What we can do is we can create a variable here called app and we're going to instantiate that object. And that basically creates a variable called app that we can then use to create routes in the application, or routes if you're American.
So one example of a route that you might want to create is using the @app.get decorator. So in order to create function based routes in FastAPI, what we're going to do is use these decorators. So we have an app object where we instantiated the FastAPI object. We can then use that as the source of our decorator and that has some methods defined depending on the HTTP method type that we need. So for example, if we need a GET request, we can use app.get, but there are also functions for app.post, put, delete, patch, and so on.
Now when we define this route or this endpoint in our FastAPI application, we need to provide a path. We're just going to use the root path which is just the slash that we see here. And then below that, once we have the decorator, we can write our function in Python. Now this can be an async function and we're going to call it index since it's going to the root path. And what we're going to do in this function is just return some content. I'm going to return a Python dictionary and the key is going to be hello and let's make the value world. So this is a very simple async-ready Python function but this can be the handler for this particular request to the route that we specify here in the decorator.
Running the Server with Uvicorn
And at the bottom we can use the uicorn package that we installed earlier on to create an async server. And what we need to provide to uicorn is the file name where our application is defined, and then we need to point to the app object. We've called that object app. So we separate those with a colon.
And then we can also use the --reload flag in order to reload the server when we make any changes. And this reload flag is very handy in development but it should not be used in production because it uses resources that you don't need on production. When you deploy something to production, that should be somewhat static until the next deployment. So you definitely don't want to be using this in production, but it's very useful for development. So let's execute that.
Testing the API and Response Types
And we can see we now have a server that's running at localhost:8000. We can copy that URL and go to the browser and I'm going to refresh this page and you can see we get back the content. I'm going to make this bigger so we can see it. And if we look at the raw data, we're basically getting JSON as the response here. If we look at the headers again, you can see the content type of the response is application/json. So this endpoint is returning JSON data, and that is automatically converted to JSON by FastAPI when we return this Python dictionary.
Now we can return different types. For example, I can write another function here and let's say that we had an about page in this application's API. So we're going to use the app.get decorator again because this is going to be a GET request and this time the path is /about. Let's write the function for that path. We'll call the name of the function about and this time we're going to return a raw string here. So what can we say about the company? Let's just say, 'an exceptional company', a fairly standard about page here. So we can now save this and go back to the browser and to the URL I'm going to add /about and let's execute this. And this time we get back the string, 'an exceptional company.' If we look at the raw data, it's just the string, we don't have any key value pairs, there's no JSON data. So this is a different type of response. And we could also return things like a Python list to our client and other types. We're going to see much more about that later when we look at pantic integration.
Leveraging Python Type Hints
Now for now, what I want to do is go back to VS Code. And as I said at the start, FastAPI is well integrated with Python's type hinting, and a lot of these modern API packages are relying on types quite heavily in their implementations. So what we're going to do is add some type hints for the returned content from these functions. For example, that first function is returning a dictionary where the keys and the values are both strings whereas the second function, the about function, that is simply returning a string here.
If we go back to the browser now and refresh the pages, we're still going to get the same response and if we change the URL to the root endpoint we're still getting that same response here as well. Now if I change the return type, for example if I'm telling this function that we want to return a list and we go back to the page here you can see we now get an internal server error. So the types have to be correct when we specify this and this can be important when you're doing some type checking or you want to avoid particular errors in the application by using the types.
And also the types that you get from packages like Pydantic, you're giving your application that type safety and you can also define validation constraints on the data coming in or going out of your API. And that can help maintain the correct state of your application. And of course it can also help with finding errors.
So we've defined in this video two very simple endpoints in a FastAPI application, and these endpoints are created with the @app.get decorator which tells FastAPI that it's a GET request to the given route and the function bodies they are async functions that return a dictionary and a string respectively. So a very simple application.
Exploring Auto-Generated Documentation
There's one last thing to show in this video, and that's the automatic API documentation that FastAPI provides when you create these applications. I'm going to go back to the browser and what I'm going to do, I'm going to refresh this page to start with to make sure that that error is gone. And then if we look at the URL, we're at localhost:8000. If we add /docs to the URL we're going to be taken to the Swagger interactive documentation that's provided by FastAPI. And you get this for free out of the box when you use FastAPI. You can see the two endpoints that we have defined in our application here.
We have the URL to the index function and as you can see, we get some details on the type of response we're going to get. We can see that this returns JSON data and we get an example schema here. Now all we've told the function at the moment is that we return a dictionary where the keys and the values are strings, so this example schema just basically conveys that to us in this documentation. And similarly, if we look at the other endpoint, the about endpoint, we can see that that will return a string. So we get a very basic schema here by going to the documentation. And if you want to learn more about this, I'll leave a link to the documentation on this page here. On this page you can learn more about the Swagger UI that's provided by FastAPI and you can also learn about the alternative documentation provided at the /redoc link and that gives you a different type of API documentation.
Conclusion and Next Steps
Whatever you prefer is what you can then share with your team internally or with your other users. And if you're looking for more information in general about what OpenAPI is, you can read this documentation here on the FastAPI site. It gives you a very good good basic overview of what that is and why you might want to use that.
So that's the first video. Any feedback is welcome. I'm going to create some more videos on this very soon. Thanks very much for watching. Please give the video a thumbs up and subscribe to the channel if you've not already done so. And please consider buying the channel a coffee if you're enjoying this content. And as I said before, any suggestions, please let us know in the comments and I'll build in the plan for this series. Thanks again for watching and we'll see you in the next video.