Python FastAPI Tutorial: Build a REST API in 15 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hey everyone, welcome to this tutorial where I'm going to show you how to use FastAPI. FastAPI 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 FastAPI. It's really easy to learn, as you'll see. 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 backend. In this video, we're going to learn how to install FastAPI and use it to build our first app. We'll also check out some of its in-built features, like the interactive documentation. Let's get started. To install FastAPI, open your terminal and run the following commands. You'll need to install both FastAPI and Uvicorn. Uvicorn is going to be the server that we use to test and run our FastAPI 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 FastAPI and then use it to create a new app. And this is how we define a path in FastAPI. This is an app decorator and it defines a path for the HTTP GET method. And the path is going to be this "/". 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 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 a user. That is a route. So let's see how we can add that next. In FastAPI, 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. 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. 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 /items/item_id inside the curly brackets. This is a way to say that if we go to a path, like for example, /items/1 or /items/2, 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 0 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 itemId 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 FastAPI 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 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. FastAPI 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's 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's looking for a specific item that the server doesn't know about. 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 FastAPI. 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 FastAPI. 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. FastAPI 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, type in 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 3, it's going to return the first 3 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 3, I'm getting the first 3 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 the string. Luckily, FastAPI 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 BaseModel from Pydantic. Then extend this BaseModel 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 FastAPI is that you can really easily just create a validation for your server as well. So far, we've looked at how to model the request data and the input payload to FastAPI. 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 FastAPI. By doing this, it makes it really easy to work with front-end frameworks like React or NextJS, 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 FastAPI, especially if you're just starting out. This is the interactive documentation feature. Whenever you start a FastAPI 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 FastAPI server and then add this "/docs" to the end of your URL, you'll 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 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 "/redoc" instead 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 FastAPI 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. So this is really useful if you want 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 FastAPI 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, FastAPI is async by default, so it can handle a lot more concurrent requests right out of the box, which I think is nice. 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 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 with community support, so you know that using fast at least it's reliable and you can build on it and there's a lot of resources. FastAPI is still new, although it's gaining popularity quite quickly. I think some of these points compare to Django as well, except that Django is a heavyweight framework, so if your use case is going to be a very lightweight backend, then FastAPI is probably the choice to pick in that case. Hopefully this video has helped you to get started with FastAPI. If you're wondering where to go next, you could look into databases, integrating things like SQL with your FastAPI server, or if you want to build an app for users, have a user system, or secure certain endpoints, you could look at authentication mechanisms such as JWT tokens. And if you've built your FastAPI app and you want to learn how to deploy 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 FastAPI application on AWS. Otherwise, I hope you found this useful and and thank you for watching.
Info
Channel: pixegami
Views: 9,554
Rating: undefined out of 5
Keywords: python, fastapi, python fastapi, python tutorial, fastapi tutorial, how to use fastapi, fastapi python tutorial, api tutorial, api development, fastapi installation, python programming tutorial, defining routes, python web framework, python api development, modeling responses, pydantic models, python programming, python web app, interactive documentation, python backend, python apps, backend development, python api, path parameters, python web development, python libraries
Id: iWS9ogMPOI0
Channel Id: undefined
Length: 15min 16sec (916 seconds)
Published: Mon Sep 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.