Full Web Apps with FastAPI Transcripts
Chapter: Course conclusion and review
Lecture: Our first site, a minimal FastAPI website
0:00 The first major thing that we covered was, how do we get started with FastAPI?
0:03 Let's build the absolute most minimalistic web application,
0:07 not just API endpoint,
0:08 but web application with FastAPI. And the fact that it fits in that square
0:12 grey box that we're about to light up, that tells you, it's not too complicated,
0:16 is it? So we're gonna need two things to get started.
0:19 We've gotta import fastapi so we can use it.
0:21 And then, in order to run the application created with FastAPI,
0:24 we need a web server.
0:26 So we're gonna use uvicorn,
0:27 which is a fantastic, production grade, ASGI, Asynchronous Web Service
0:32 Gateway Interface Server. We start by creating an app instance from the FastAPI,
0:39 our FastAPI instance. I'm calling it app here,
0:42 sometimes it's called api, sometimes it's called app. Doesn't really matter as long as
0:45 you're consistent. Then we define a function that's gonna be called for a given URL
0:49 when we request it with a web browser.
0:51 So we say app.get("/").
0:54 That means if we do a basic normal HTTP request against the, just the server.
0:59 This is what's going to run, not a POST or other HTTP verbs, just a GET
1:04 standard web request. And then, in here,
1:06 we're going to generate a message very,
1:08 very simple in this case,
1:09 we just have a header that says "Hello
1:11 web!". Now remember,
1:14 if we return just the string by itself, return "<h1>..." and so on, FastAPI
1:18 is an API framework first, with this ability to do HTML second.
1:24 So if we did it that way,
1:25 we would get a JSONResponse,
1:27 which has a string "Hello,
1:29 web!". That's not at all what we want.
1:31 We wanna have a web page,
1:33 not an API response,
1:35 right? So we're gonna use one of the specialized responses, it really comes from Starlette,
1:40 but we'll find that under fastapi.responses.HTMLResponse.
1:44 Doing it this way, we tell the web browser what you're getting back is a web
1:49 page, not some JSON data exchange.
1:53 This is gonna be our home page here.
1:55 Not very impressive as you saw it when we got started,
1:57 but we built on it throughout the course,
1:59 and then finally, in order to run our application,
2:02 unlike Flask, you can't say app.run().
2:04 Instead, you say uvicorn.run(),
2:07 and then, if you'd like, you can specify the host and the port.
2:11 The port defaults to 8000. The host,
2:13 I believe, defaults to 0.0.0.0 or listen on the Internet.
2:18 Not a big fan of that,
2:19 so I'll just listen on localhost here.