Understanding Backend Web Frameworks
Have you ever wondered when you place an order on Amazon.com what happens behind the scene? What you see on the website, the Amazon website, is basically called the UI code. When you click on the 'place order' button, it sends an http request to a backend, and in the backend there is a backend server running, a web server running which serves those requests.
Now that web server can be written in a JavaScript framework called Node.js or, if you're using Python, you can use a framework called Flask. Nowadays a new web framework has come up which is called FastAPI. And this video is a beginner video for FastAPI. In this video we will install FastAPI and we'll play with it a little bit to see what benefit it has to offer over Flask.
Installation and First "Hello World" App
Let's install FastAPI on your computer. First, I'm assuming you have Python installed, which comes with pip, so you will run pip install fastapi. And it is as simple as that. You also need to install something called uvicorn. So after FastAPI is installed, you will run pip install uvicorn. This is the server that you'll be using to run your FastAPI server. So pip install fastapi and pip install uvicorn. These are the two commands that you run to complete your installation.
Now I will write my first FastAPI server. I have opened PyCharm. You can use any editor: Sublime, Notepad++, VS Code, any editor that you're comfortable with. And here I'm going to go into Zen mode. I will be meditating, all right?
I will import the FastAPI first by doing this, and then I will create a FastAPI instance. So you're just creating an instance of this class. You can call it app or anything that you feel comfortable with.
Then you will write your first endpoint. So I will explain what that endpoint means. Let's say I'm writing a simple function called hello and that hello endpoint will return me some fixed string. So I'm writing a Python function, it's an async function, okay? And I will say return, for example, "Welcome".
So my code is done. So you see, only five lines of code and I have written my first endpoint.
Running the Server and Hot Reloading
Now to run the server, you will use the Uvicorn command. You will say uvicorn and then the name of the file. The name of this file, by the way, let me show you, is main.py, okay? So that's the file, so I will use uvicorn main. That's the file name, colon app. So you are not using main.py, you're just saying main and then colon app, whatever is a variable name here. And you will do --reload. I will explain what that reload option is. But when you run it, it says "Application startup complete" and your server is available at this port. This is the host and port, okay? So we'll go to the browser now and try to run this link.
I'm using Chrome here and when I run this link, I will say hello. See, I get this thing back. So hello is essentially my entry point, okay?
When you are working on, let's say Amazon placing an order, you know, you might be having URLs like post_order. So post_order is a typical name of the endpoint which will post an order, you know, or place an order. So these are all called endpoints. It could be post_order, it could be get_order, it can be anything. It's up to you, it's not like a fixed list of strings. You can define it to be anything. So here I'm using hello and hello is returning me "Welcome".
I can change my string and say "Welcome to FastAPI tutorial" and I have to just save. I don't need to stop my server and re-run it again. See? I did not stop and re-run it, and it automatically reloaded my new code. And that was the purpose of this option. So now when I go back to my browser and refresh it, you see you can see "Welcome to FastAPI tutorial". So my code changes I'm doing are dynamically getting reflected into my execution.
Path Parameters and Dynamic Endpoints
Now let's make it more interesting. Let's have it such that it takes a parameter where I can say, okay, the world, and it will say "Welcome to FastAPI tutorial, world". How do you do that? Well, here you can supply that parameter. So here I'm saying name, okay? And I'm using this bracket. This is more like a Python format string kind of syntax where you are supplying name here, and you can use the same word as a variable name here.
And now that name that someone is supplying you in a URL is available here in this variable and you can just say this. I will use Python's format string and again, you don't need to reload the server, it's automatically loading those changes on its own. Now when I refresh it... all right, so let me refresh it. So it says, see, the world. You can give any name like say tom, and that this string will be passed into the name variable and it will come back in the message.
Overview of Common REST API Methods
Here we are using the get method. In HTTP REST protocol, there are a couple of other methods as well. So let's go over them one by one. GET is usually used to query data. For example, you are looking for an iPhone case on Amazon website. When you make that query, the website is making a GET request to get you all the iPhone covers.
There could be another request called POST, which is used to create data. So when you place an order on the Amazon website, let's say, you are issuing a POST query. So this GET, POST, etc., these are the REST API protocol endpoints.
The third one is PUT, which will be used to update data. So an existing order you want to update it. And the fourth one, DELETE, obviously if you want to delete any data, like deleting an order, you will use this endpoint.
Now there are other endpoints as well, but these four are the popular ones.
Building a Practical Example with Path Validation
Now, while working on this tutorial, let's say you got hungry and you went to Grubhub to order some food. And let's say you're looking for Indian food, and this is showing you all the Indian restaurants and it might show you all the Indian kind of recipes. So let's say you are a backend engineer working in Grubhub and you want to write an endpoint where you can say something like get_item.
So let me just show you here, you can maybe say, let's say, get_items and indian, and it will return you the Indian food items which are available. Okay? So I'm going to just change this entry point and I will say get_items and this is the name of my cuisine, and that comes here as a variable. This function name can be anything; it doesn't have to be get_items. And let's say, you know, I'm retrieving my item records from a database, but I don't have a database here so I will just use a simple dictionary where I'm saying, okay, indian cuisine means these many recipes. Okay, I love samosa by the way. american means these recipes and so on. And here you can just use food_items.get(cuisine).
So if someone is supplying indian cuisine, it will return this one. So let's try this out really quickly. We are very hungry! Okay, this is hello, hello doesn't work. I will say get_items/indian. get_items/indian is not working... actually it was reloading, I did not wait enough. So when I refresh this, I'm getting, see, Indian items: Samosa and Dosa. All right. Let's try some Italian food. Ah, Ravioli, Pizza. Okay, how about Mexican? Well, we don't have Mexican, so then this get will return null. But this is not ideal. Actually, you want to give the user a message that in my website the only supported cuisines are Indian, American, and Italian.
Benefit 1: Built-in Data Validation
Now let's talk about the benefit of FastAPI over Flask. So the first benefit is that in Flask, if you have to do this kind of data validation, then you will do something like: if cuisine not in... so you will have to write a code like this, where I have just said food_items.keys(), which will be Indian, American, and Italian. And you will say if cuisine not in this then return this message that only valid supported cuisines are Indian, you know, American, and Italian.
Now, see, this is a very simple function. You might have a big function with a lot of validation, and when you are using a framework like Flask, you have to do all this validation yourself, which is not ideal. What if the framework itself gives you some validation? So that's what FastAPI can do for you. It can give this validation for free, and I will explain how.
So I'm just going to remove this code here and I have imported Enum in Python. And Enum is used if you have a fixed category of things. And I'm going to create a class which will have all three cuisines specified as an enum. So see, these are my available cuisines. And now here you can just use Python's type hint and say AvailableCuisines. So you're saying that cuisine has to be from these available cuisines. Now, this is a type hint. Python is not a statically typed language, so if you run the code just like that, it's not going to do anything. But FastAPI understands now that the user or the backend engineer is expecting cuisine to be one of these three, and if you don't supply the cuisine which is, you know, part of this list, let's see what happens.
So here, once again, if I supply indian, things are going to just work as fine. But when I say mexican, it will give me an error that it is not valid. The valid values are these three. So see, you don't have to write that validation code here, and this is benefit number one, that FastAPI offers inbuilt data validation. It is a huge benefit. It can make your code really compact because you don't have to do all this validation yourself. It can also reduce bugs. So you see a very nice error here.
I quickly wrote a second function. Let's say on your Grubhub website you have some coupon codes, you know, and 1, 2, 3 are coupon code IDs, and these are the relevant amounts in percentages for those coupon codes. And you can have another endpoint called get_coupon and code. Now code you expect it to be only an integer, so using a type hint again, you are saying it has to be an integer. Okay, and let's see if it is not an integer. So I go back here, I will say get_coupon and when I say 1, you know, I get 10 percent. When I say 2, I get 20 percent. But if I do abc, it will again tell me that value is not a valid integer. It has to be an integer. So again, the data validation in FastAPI is super awesome.
Benefit 2: Automatic API Documentation
The second big benefit of FastAPI is the enabled documentation. So you can do /docs and it will generate the documentation for you. See, I didn't have to write anything. This could be very useful for a front-end engineer who is using your backend, because that way they will know what you are expecting in your API. For example, in get_cuisine you are expecting only Indian, American, Chinese. So if you click on this 'Try it out' button, see, it is showing you that these are the three valid cuisines. And you can also send a test request. So if I say indian and if I execute, you know, see, I'm getting very delicious samosa and dosa back, which I can eat and increase my programming productivity. You know, american, execute, hot dog, apple pie. So this is giving you a nice test pad to test out your APIs.
You can also use a different kind of documentation. So FastAPI, again, if you do /docs you get this documentation. If you do redoc, you know, redoc, that's another way of generating documentation. So see, here it generates like response and response samples as well. So you can just explore it. It's pretty useful.
This is the official website of FastAPI, and if you click on tutorials, they have amazing quality tutorials. I have not seen tutorials of such a great quality, very simple, easy to understand, on any other technology frameworks. Okay, so I highly recommend you go through all these tutorials because I just covered the basics of FastAPI. I compared it with Flask, but there are so many things, you know, so many options available. For example, form data. Form data is a usual thing when you're doing UI coding in your JavaScript, and you can directly import that Form class here in the FastAPI backend and you can do various things with it. You know, you get some ready-made functionality, so explore these options and you're going to absolutely love the documentation of this portal.
Summary of FastAPI's Key Benefits
While coding, we covered the two big benefits of FastAPI which were inbuilt data validation and the second was inbuilt documentation support. There are a few other benefits as well. For example, the benefit number three is that the FastAPI, as the name suggests, is actually very fast. The way it is written, it gives you the best performance. So your server will run almost at the speed of, you know, a Node.js server. So the performance, runtime performance, is beautiful. So that's benefit number three.
Benefit number four is the code that you're writing is very compact and as a developer, it will take you very less time to write FastAPI code. So it's a compact code, the code development is very fast, and there are very few bugs. So just to quickly summarize four benefits: inbuilt data validation, inbuilt documentation support, the runtime performance is pretty good, it is very fast, and the development time is also very less and there are fewer bugs.
I hope you like this video. If you did, please give it a thumbs up and if you have any questions, post in the comment box below.