Python FastAPI Tutorial: Build a REST API in 15 Minutes
Key Takeaways
This video teaches how to install and build a REST API with FastAPI in Python
Full Transcript
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 backend 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'll 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 up 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 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 gonna 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 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 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 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 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'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 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 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 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 3 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 the string luckily fast API also supports pedantic 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 pedantic 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 pedantic with fast API is that you can really easily 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 because all you need to do is just use the same base model from pedantic 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 nexjs 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 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 [Music] 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 slash 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 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 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 fast API is quite popular and easy to use right now how does it compare go to an industry standard framework like flask which has been around for much longer and has much wider adoption while 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 and as you've seen it's really easy to use the way you define routes to find 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 fast API 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 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 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
Original Description
Learn how to install and build your first app with FastAPI (a high-performance web framework for Python).
In this tutorial, you'll learn how to instal FastAPI, and use it to create a new app. Learn how to define routes, handle errors, use request and path parameters, validating data with Pydantic models, modelling responses, and how to use the interactive documentation.
🔗 Code: https://github.com/pixegami/simple-fastapi-example
🔗 FastAPI: https://fastapi.tiangolo.com/
📚 Chapters
00:00 Why Use FastAPI?
00:49 Install and Get Started with FastAPI
02:22 GET and POST Routes
05:27 Handling HTTP Errors
06:48 JSON Request and Path Parameters
10:38 Response Models
11:42 Interactive Documentation
13:31 FastAPI vs Flask
#pixegami #fastapi
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from pixegami · pixegami · 50 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
▶
51
52
53
54
55
56
57
58
59
60
How to Build an AWS Lambda Function in Python in Just 7 Minutes!
pixegami
AWS CDK Tutorial: Deploy a Python Lambda Function using AWS
pixegami
I used GPT-3 to Write Poetry • Is AI the Future of Creative Writing?
pixegami
Create NFT Generative Art with Python! (Full Tutorial)
pixegami
Build an AI-driven SaaS Application: FULLSTACK Tutorial with Python, React, and AWS
pixegami
NextJS and TailwindCSS: How to Build a Portfolio Site from Scratch
pixegami
Python Web Scraping Tutorial • Step by Step Beginner's Guide
pixegami
Build Wordle in Python • Word Game Python Project for Beginners
pixegami
How to create 1000+ unique NFT-style images (like Cryptopunk) | Python Tutorial
pixegami
Top 10 Python Modules 2022
pixegami
How to Send SMS Text Messages with Python & Twilio - Quick and Simple!
pixegami
How To Write Unit Tests in Python • Pytest Tutorial
pixegami
How to Style Your React Landing Page with Tailwind CSS
pixegami
FastAPI Python Tutorial - Learn How to Build a REST API
pixegami
How to Deploy FastAPI on AWS EC2: Quick and Easy Steps!
pixegami
PyScript • How to run Python in a browser
pixegami
My Custom Ubuntu Linux Terminal with Themes and Plug-ins 💻
pixegami
Deploy FastAPI on AWS Lambda ⚡ Serverless hosting!
pixegami
NextJS Firebase Auth Tutorial • How to Authenticate Users for Your App
pixegami
AWS Lambda Python functions with a database (DynamoDB)
pixegami
How To Build a CRUD (TO-DO) App on AWS using FastAPI and Python
pixegami
How to Make a Discord Bot with Python
pixegami
How To Use GitHub Copilot (with Python Examples)
pixegami
PyTest • REST API Integration Testing with Python
pixegami
Python Beginner Project: Build a Caesar Cipher Encryption App
pixegami
Decorators in Python: How to Write Your Own Custom Decorators
pixegami
NextJS 13 Tutorial: Create a Static Blog from Markdown Files
pixegami
Exploring ChatGPT for Coding and Business ✨ 8 Real Examples!
pixegami
How I Would Learn Python (if I had to start over) • A Roadmap for 2023
pixegami
Build an AI Pokemon Generator with Python and Midjourney
pixegami
Why You Should Learn Python in 2023 (as your first programming language)
pixegami
ChatGPI API in Python ✨ How to Build a Custom AI Chat App
pixegami
Learn Python • #1 Installation and Setup • Get Started With Python!
pixegami
Learn Python • #2 Variables and Data Types • Python's Building Blocks
pixegami
Learn Python • #3 Operators • Add, Subtract and More...
pixegami
Learn Python • #4 Conditions • If / Else Statements
pixegami
Learn Python • #5 Lists • Storing Collections of Data
pixegami
Learn Python • #6 Loops • How to Repeat Code Execution
pixegami
Learn Python • #7 Dictionaries • The Most Useful Data Structure?
pixegami
Learn Python • #8 Tuples and Sets • More Ways To Store Data!
pixegami
Learn Python • #9 Functions • Python's Most Important Concept?
pixegami
Learn Python • #10 User Input • 4 Ways To Get Input From Your User
pixegami
Learn Python • #11 Classes • Create and Use Classes in Python
pixegami
Learn Python • #12 Final Project • Build an Expense Tracking App!
pixegami
Stripe & Firebase Tutorial • Add Payments To Your NextJS App
pixegami
How To Use GitHub Actions • Automate Your AWS Deployments
pixegami
How to Run a Python Docker Image on AWS Lambda
pixegami
My MacOS Terminal Setup for HIGH Productivity
pixegami
Host a Python Discord Bot on AWS Lambda (Free and Easy)
pixegami
Python FastAPI Tutorial: Build a REST API in 15 Minutes
pixegami
Pydantic Tutorial • Solving Python's Biggest Problem
pixegami
How to Get Started with AWS • Crash Course
pixegami
Python Requests Tutorial: HTTP Requests and Web Scraping
pixegami
Amazon Bedrock Tutorial: Generative AI on AWS
pixegami
How to Publish a Python Package to PyPI (pip)
pixegami
Langchain: The BEST Library For Building AI Apps In Python?
pixegami
RAG + Langchain Python Project: Easy AI/Chat For Your Docs
pixegami
Python Dataclasses: Here's 7 Ways It Will Improve Your Code
pixegami
Build a Custom AI RPG Game with OpenAI GPTs
pixegami
Create a Custom AI Assistant + API in 10 Mins
pixegami
More on: API Design
View skill →Related Reads
📰
📰
📰
📰
How to Undo git reset — hard and Recover Lost Commits
Medium · Programming
Bypassing Shadow DOMs & Same-Origin Iframes: How I Solved LinkedIn's Massive SDUI Update
Dev.to · Maaz Khan
Why Check Then Act Is the Silent Killer in Banking Backends, and How NestJS Prevents It
Dev.to · Peace Melodi
PDF Tamper Detection API for Laravel and PHP: Integration Guide
Dev.to · Iurii Rogulia
Chapters (8)
Why Use FastAPI?
0:49
Install and Get Started with FastAPI
2:22
GET and POST Routes
5:27
Handling HTTP Errors
6:48
JSON Request and Path Parameters
10:38
Response Models
11:42
Interactive Documentation
13:31
FastAPI vs Flask
🎓
Tutor Explanation
DeepCamp AI