Hey everyone, welcome to this tutorial where I'm going to show you how to use Fast API. Fast API is a web framework designed specifically for building API apps with Python. It's extremely popular and comes with pretty nice features and high performance right out of the box, at least as far as Python web frameworks go. Here are some of the benefits of using Fast API. It's really easy to learn, as you'll see, and it's also fast to develop with because it comes with some really useful abstractions. And finally, it's async by default, so the performance is also pretty good. This makes it a solid choice for building any kind of Python back end. In this video, we're going to learn how to install Fast API and use it to build our first app. We'll also check out some of its inbuilt features like the interactive documentation. Let's get started.
To install Fast API, open your terminal and run the following commands. You need to install both Fast API and Uvicorn. Uvicorn is going to be the server that we use to test and run our Fast API applications.
Once you finish installing it, create a new directory for your project. Open this directory in your code editor and create a file called main.py. In your main.py file, import Fast API and then use it to create a new app. And this is how we define a path in Fast API. This is an app decorator, and it defines a path for the HTTP get method, and the path is going to be this slash. So that's going to be our root directory. So that when somebody visits this, this function is going to be called, and then we can return this Hello World object here. To run your server, go back to the terminal and then use Uvicorn. Your command should look like this: type Uvicorn, and then the name of your file, which should be main, and then the name of your app, and then you can use this reload flag to make the server automatically refresh uh, anytime you make changes to the file. You should see something like this, and if you click to this URL here, you should be able to see the API route. So here we're at the home route and you can see the Hello World object being returned. So now we have a really basic app working. Let's figure out how we can add routes to our application. Routes are going to be this URL when you enter a different thing, for example, you want to see items, or you want to see uh, user, that is a route. So let's see how we can add that next.
In Fast API, routes are used to define the different URLs that your app should respond to. You can create routes to handle different interactions. So let's say we wanted to build a to-do list application. We'll need different routes to add or view the to-do items on the list. Let's go back to our app and start by creating an empty list of items. So this is going to be our to-do items. Next, I'm going to create a new endpoint for our app, and this one is going to be called create item, and users can access this endpoint by sending an HTTP post request to this items path. Uh, and it's going to accept item as an input, so this is going to be a query parameter. So once it receives this item, it's just going to add it to this items list. Uh, and we can actually make it return the item, or we can make it return the whole items list as well, just so that we can see the results of different things we add to the list. To test this, open up a new terminal, and then send this curl request directly to our URL. We're going to pass in the item by using a query parameter like this at the end of the URL. So once you send it, it should return the current list of items, and you can see here we've just added an Apple to that list. But we can modify this and add other items too. So now we've added two items, and this endpoint works for adding new items to the list.
To view a specific item on the list, we're going to create a new endpoint using the get decorator again. The path for this endpoint is going to be slash items slash item ID inside the curly brackets. This is a way to say that if we go to a path, like for example, slash items one or slash items two, then we can actually use that variable and use it to query this items list. Now, be careful because every time you make a change, the server will reload, and this items array will be reset back to this empty array. So before you test this get items endpoint, make sure you create an item first so that there is actually something there. So I've just refreshed my server, and I've added this Apple and this orange item again to my server. And now I can use this get request with this zero index to get the first item. So if I do that, I get Apple. And if I run it again and change this index, I should get the orange. That's because whatever you put here as this index will become this item ID variable, or whatever the name is, in your function, and then you can use that as a parameter. If you specify the type hint here, then Fast API is smart enough to convert the type for you.
Now, what happens if we try to get an item that doesn't exist? So let's go back to the app and try items number three. And we get an internal server error. This isn't really ideal because um, in this specific case, we know exactly what went wrong. But if our users see this internal server error, it's not a very helpful error message. So the next thing we're going to look at is how to raise very useful error messages so that when you're developing the app, you can debug it and figure out what went wrong. Fast API makes it really easy to raise specific errors to handle whatever situation you're dealing with. In this case, we tried to find an item that doesn't exist in our server, and we just got back an internal server error, which isn't really helpful. For situations like this, there is a universal set of HTTP response codes that you can use and everybody will understand. If an item doesn't exist, that's usually a client error because we're saying that the client is looking for a specific item that the server doesn't know about. Um, so let's click into this client error response, and you scroll down, you'll see this 404 not found. So this 404 code is probably the way we'd want to respond in this situation. To do that, scroll to the top of your app and import this HTTP exception from Fast API. And then, down in your handler, we'll modify this to have a condition checking whether or not the item exists. And if it does, we'll return it. Otherwise, we'll raise this HTTP exception. We'll put this 404 status code in, which means that item was not found. And you can even use this detail parameter to give more information about why it wasn't found. Now, if I go back to my terminal and then run the same request again, you'll see that our error has updated to something much more useful.
Next, let's dive a little deeper into how we can send information to Fast API. We're going to look at how you can use request and path parameters. Now, back in our project, we actually already have an example of a path parameter, which is this create items here, because this item appears as a query string in the URL path. But this is probably not the right way to do it, so we're going to turn this into a JSON payload later. But for now, let's create a new endpoint, which I'm going to call list items. This one's going to use a query parameter as well, and this time it's going to be an integer. Fast API is smart enough to convert the type of the parameter for us. So even though when we send a URL request, they're all technically strings, if you type hint this as an integer, then it's going to convert this into an integer. And this particular function is going to take this limit query parameter that we specify and use that to return some number of items from the list. So if we put in limit three, it's going to return the first three items, or if we leave it default 10, then it's going to return 10 items from the list. Let's go ahead and test it out. I've just added 10 items to my list on the server, and now I'm going to use this request on the items endpoint. This is the same endpoint as this one, but because I'm using a different request, it is going to hit this method in the server instead of this first one. So let's go ahead and use that. And then with limit three, I'm getting the first three items back. And if I leave the limits blank or don't specify it, then it's going to use the default value and return all 10 apples. And the default value of course is defined in the function header.
Now, if I want to build a to-do list application, then my items might actually be a more complex data structure than just a string. Luckily, Fast API also supports Pydantic models, which allow you to structure your data and also provide additional validation. This will make things like testing, documentation, and code completion in your IDE a lot easier. To get started, first import base model from Pydantic. Then, extend this base model to create an item class. And because these items are supposed to be items in a to-do list, it's going to have two attributes: a text, which is a string, and is done, which is a boolean. Now we can update our app to use this item model. So for instance, when we create this item, instead of taking a string, we can now pass this item model. And here when we get an item, instead of returning a string, we can also return an item. Now if we try to use the same curl request to create the item, it's not going to work because we have specified the item through the query parameter. But when you use a modeled object like this item here as part of the argument, it's going to expect that to be in the JSON payload of the request. To make it work, we have to send this item data as a JSON payload instead. So this is how you can do it in curl, and we no longer have the query parameter at the end of the URL either. So when you run that, you should see that it now works, and in our response, we no longer get a single string, we actually get an object that conforms to our item model we've defined here. So by default, our is done value is false, and because we didn't specify that here, that's exactly what we got.
Now, if I go back to my model and I want to make one of these fields required, for example, this text here, I can simply delete this default value. And now when I go back to my terminal, and if I try to send it something that doesn't have a text value, for example, I call this title instead, it's going to fail because now it's validating the request model for me. So this is another nice advantage of using Pydantic with Fast API is that you can really easily um just create validation for your server as well. So far, we've looked at how to model the request data and the input payload to Fast API. Let's look at how we can model the response as well. This is actually super easy because all you need to do is just use the same base model from Pydantic for your response. So, for example, let's go here where we list the items or where we get the item. All you have to do is add a new argument to the decorator called response model, and then just put the item class that you'd like returned from this response. Similarly, if you want to put the response model for a list of items, you could do it like this. So now this is just another way to tell our server and our interfaces that the response from this endpoint would be conforming to this model here. And this is really useful if you want to build a front-end client that interacts with Fast API. By doing this, it makes it really easy to work with front-end frameworks like React or Next.js because now you have a defined response structure that you can rely on.
Now, I'm going to show you one of my favorite features of working with Fast API, especially if you're just starting out. This is the interactive documentation feature. Whenever you start a Fast API server, you get a documentation page for free that you can actually interact with and use to test your API. So far, we've been doing all our testing in the terminal, but it can be pretty hard to type out this command over and over again or to make modifications to it. If you go back to your local Fast API server and then add this slash docs to the end of your URL, you get taken to this Swagger UI page where you get to see all of your endpoints, you get to see which HTTP method they accept, and if you click into them, you can also look at the type of parameters they take. You can even test them. So, for example, here, let's test our post request. Click try it out and then just update this request body with whatever you want. Then, when you hit execute, it's going to give you the curl command you need to run to test this out in your terminal, but it's also actually going to send the request um, and you can see the response body here. So this is really useful because you can see how your API is configured, and you can also just test it easily without having to fiddle around with commands in the terminal. And if you type in slash redoc instead, um, as the path, you get this other set of documentation, and I think it's pretty much the same thing, so use whichever one you prefer. And there's a very small link here, but this one's also actually quite useful, but if you click it, you get this JSON file, which is basically everything you need to know about your Fast API server. So here it's got all the paths, all the different schemas of each path, and all the different responses that can be returned. Uh, so this is really useful if you wanted to just export this JSON and build documentation or build a front-end client, maybe in JavaScript or something, that can interact with your server.
Although Fast API is quite popular and easy to use right now, how does it compare to an industry standard framework like Flask, which has been around for much longer and has much wider adoption? Well, Fast API is async by default, so it can handle a lot more concurrent requests right out of the box, which I think is nice. Um, and as you've seen, it's really easy to use. The way you define routes, define response models, validate data, and throw HTTP exceptions, uh, is as simple as it could be. So, with Flask, I don't have a side-by-side comparison at the moment, but if you go trying to do the exact same thing, it's just a little bit more fiddly. Currently though, Flask does have higher adoption, and it is an open-source project uh with community support, so you know that using Flask, at least it's reliable, and you can build on it, and there's a lot of resources. Fast API is still new, although it's gaining popularity quite quickly. I think some of these points compare to Django as well, um, except that Django is a heavyweight framework. So, if your use case is going to be a very lightweight back end, then Fast API is probably the choice to pick in that case. Hopefully, this video has helped you to get started with Fast API. If you're wondering where to go next, you could look into databases, integrating things like SQL with your Fast API server, or if you want to build an app for users, um, have a user system or secure certain endpoints, you could look at authentication mechanisms, such as JWT tokens. And if you've built your Fast API app and you want to learn how to deploy it to a server, so that it's live and anyone in the world can use it, then check out my video here where I show you how to deploy a Fast API application on AWS. Otherwise, I hope you found this useful, and thank you for watching.