talkpython / modern-apis-with-fastapi Goto Github PK
View Code? Open in Web Editor NEWCourse demos and handouts for our Modern APIs with FastAPI course.
Home Page: https://talkpython.fm/fastapi
Course demos and handouts for our Modern APIs with FastAPI course.
Home Page: https://talkpython.fm/fastapi
Just starting out with your course and I noticed that the "UI" in the browser isn't working. I say "UI" as not sure how to describe it but screenshots should hopefully work:
What I get (no menu/interface):
Versus what I see in your videos (options to show raw data or formatted):
I've tried searching for the problem, but I'm not using the right terminology as all that comes up is about the docs UI. This works fine, if I go to http://127.0.0.1:8000/docs. Other results suggest it's something to do with Swagger-UI but that doesn't get installed so not sure about that one.
Installed from requirements.txt:
fastapi
uvicorn
Any pointers in the right direction would be appreciated. It doesn't really affect the course but just stood out and I was curious.
My code:
from typing import Optional
import fastapi
import uvicorn
api = fastapi.FastAPI()
@api.get('/')
def index():
body = "<html>" \
"<body style='padding: 10px;'>" \
"<h1>Welcome to the API</h1>" \
"<div>" \
"Try it: <a href='/api/calculate?x=7&y=11'>/api/calculate?x=7&y=11</a>" \
"</div>" \
"</body>" \
"</html>"
return fastapi.responses.HTMLResponse(content=body)
@api.get('/api/calculate')
def calculate(x: int, y: int, z: Optional[int] = None):
if z == 0:
return fastapi.responses.JSONResponse(content={"error": "ERROR: Z cannot be zero."}, status_code=400)
value = (x + y)
if z is not None:
value /= z
return {
'x': x,
'y': y,
'z': z,
'value': value
}
uvicorn.run(api, port=8000, host="127.0.0.1")
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300303
- 4:38 we're gonna come down here and say "uviacorn, run this application". And we could
+ 4:38 we're gonna come down here and say "uvicorn, run this application". And we could
- 5:09 FastAPI and uviacorn, create a simple method and call uviacorn
+ 5:09 FastAPI and uvicorn, create a simple method and call uvicorn
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300304
- 0:14 so we're gonna use uviacorn,
+ 0:14 so we're gonna use uvicorn,
- 0:35 And then we just say "uviacorn.run"
+ 0:35 And then we just say "uvicorn.run"
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300408
- 1:48 Uviacorn is one of them.
+ 1:48 Uvicorn is one of them.
- 3:04 Uviacorn. And That's a pretty awesome logo.
+ 3:04 Uvicorn. And That's a pretty awesome logo.
- 3:34 is based upon. So here's Uviacorn, we're gonna be using that. This is one
+ 3:34 is based upon. So here's Uvicorn, we're gonna be using that. This is one
- 4:12 so we have uviacorn,
+ 4:12 so we have uvicorn,
- 4:58 might as well run it on uviacorn,
+ 4:58 might as well run it on uvicorn,
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300502
- 1:05 we'll have FastAPI, uviacorn.
+ 1:05 we'll have FastAPI, uvicorn.
- 1:28 thing going. So we'll import FastAPI and we'll import uviacorn,
+ 1:28 thing going. So we'll import FastAPI and we'll import uvicorn,
- 1:56 come down here and we'll do a uviacorn, run, API, port,
+ 1:56 come down here and we'll do a uvicorn, run, API, port,
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300506
- 5:46 Come down here. We would say "uviacorn",
+ 5:46 Come down here. We would say "uvicorn",
- 5:53 like this. There we go. uviacorn.
+ 5:53 like this. There we go. uvicorn.
- 6:25 Now I go down to the terminal and I uviacorn it. It's back to working, okay.
+ 6:25 Now I go down to the terminal and I uvicorn it. It's back to working, okay.
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300805
- 1:02 You saw that we use you uviacorn,
+ 1:02 You saw that we use you uvicorn,
- 1:41 application over in uviacorn,
+ 1:41 application over in uvicorn,
- 1:53 It's gonna be this uviacorn process. And in fact,
+ 1:53 It's gonna be this uvicorn process. And in fact,
- 2:59 We're gonna install uviacorn and our Python Web app,
+ 2:59 We're gonna install uvicorn and our Python Web app,
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300807
- 3:15 We don't have the libraries needed to run, set up like uviacorn, or
+ 3:15 We don't have the libraries needed to run, set up like uvicorn, or
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300808
- 3:10 So uviacorn is running on our server as we hoped.
+ 3:10 So uvicorn is running on our server as we hoped.
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300810
- 0:33 We're going to run four copies of uviacorn as workers.
+ 0:33 We're going to run four copies of uvicorn as workers.
- 0:51 but a ASGI, uviacorn ones.
+ 0:51 but a ASGI, uvicorn ones.
- 1:36 and uviacorn on the server require these two libraries as well.
+ 1:36 and uvicorn on the server require these two libraries as well.
- 3:56 still. So perfect. We've now set up Gunicorn And uviacorn to always
+ 3:56 still. So perfect. We've now set up Gunicorn And uvicorn to always
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300811
- 1:12 which will fan it out to the uviacorn workers,
+ 1:12 which will fan it out to the uvicorn workers,
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300902
- 0:10 so we're using uviacorn as the server.
+ 0:10 so we're using uvicorn as the server.
- 0:38 we just have to call uviacorn dot run and pass it
+ 0:38 we just have to call uvicorn dot run and pass it
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300909
- 0:19 Gunicorn is going to run a bunch of uviacorn worker processes
+ 0:19 Gunicorn is going to run a bunch of uvicorn worker processes
- 0:25 like this and over in uviacorn,
+ 0:25 like this and over in uvicorn,
Hello Mike,
It seems that the stylesheet link is no longer valid that you included in layout.html:
<link href="//oss.maxcdn.com/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
I had to change it to:
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
Refer to https://bootstrapdocs.com/v3.0.3/docs/getting-started/
and check "Bootstrap CDN"
I went ahead and used bootstrap beta 5, which looks way nicer btw, check it out if you want to (also supports integrity checks which is a plus):
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
ch04-language-foundations/async/async_scrape
program.py
await mising in get_title_range function
for n, t in tasks:
html = await t
title = await get_title(html, n)
print(Fore.WHITE + f"Title found: {title}", flush=True)
Hi, In modern-apis-with-fastapi, inappropriate dependency versioning constraints can cause risks.
Below are the dependencies and version constraints that the project is using
fastapi
uvicorn
httpx
jinja2
aiofiles
requests
The version constraint == will introduce the risk of dependency conflicts because the scope of dependencies is too strict.
The version constraint No Upper Bound and * will introduce the risk of the missing API Error because the latest version of the dependencies may remove some APIs.
After further analysis, in this project,
The version constraint of dependency fastapi can be changed to >=0.51.0,<=0.78.0.
The version constraint of dependency httpx can be changed to >=0.6.7,<=0.7.8.
The version constraint of dependency httpx can be changed to >=0.10.0,<=0.11.1.
The version constraint of dependency requests can be changed to >=0.2.1,<=0.2.3.
The version constraint of dependency requests can be changed to >=0.7.0,<=2.24.0.
The version constraint of dependency requests can be changed to ==2.26.0.
The above modification suggestions can reduce the dependency conflicts as much as possible,
and introduce the latest version as much as possible without calling Error in the projects.
The invocation of the current project includes all the following methods.
fastapi.FastAPI fastapi.FastAPI.get fastapi.APIRouter.get fastapi.Response fastapi.APIRouter fastapi.FastAPI.include_router fastapi.APIRouter.post fastapi.Depends
httpx.AsyncClient
requests.get requests.post
__create_key choice.lower.strip configure_routing state.strip pathlib.Path.absolute.exists configure_fake_data super fastapi.FastAPI bs4.BeautifulSoup.select_one __reports.append repr fastapi.responses.HTMLResponse fastapi.APIRouter.post models.location.Location requests.get.raise_for_status get_html asyncio.new_event_loop.run_until_complete city.strip open country.strip get_title_range services.report_service.add_report report_event Order asyncio.create_task tasks.append str collections.namedtuple header.text.strip configure_api_keys start_response configure __cache.get r.get bs4.BeautifulSoup pathlib.Path.absolute services.openweather_service.get_report_async requests.get Exception requests.get.json r.get.get uuid.uuid4 fastapi.APIRouter.get state.strip.lower client.get.json fastapi.FastAPI.get models.reports.Report range fastapi.responses.RedirectResponse services.report_service.get_reports client.get input.lower Item datetime.timedelta receive starlette.staticfiles.StaticFiles httpx.AsyncClient json.load.get get_title fastapi.APIRouter datetime.datetime.now.total_seconds list fastapi.responses.JSONResponse main city.strip.lower starlette.templating.Jinja2Templates asyncio.new_event_loop fastapi.Response json.load __clean_out_of_date fastapi.FastAPI.mount fastapi.FastAPI.include_router uvicorn.run client.get.raise_for_status asyncio.run country.strip.lower units.strip units.strip.lower print datetime.datetime.now.get __cache.items resp.json.get starlette.templating.Jinja2Templates.TemplateResponse pathlib.Path counter float __reports.sort send super.__init__ see_events requests.post fastapi.Depends dateutil.parser.parse isinstance datetime.datetime.now int input
@developer
Could please help me check this issue?
May I pull a request to fix it?
Thank you very much.
It would be nice to see tests for APIs.
I'm afraid that I don't understand asyncio well enough to fix this myself so was wondering if I could get some help with this one?
In the code for Chapter 7 - inbound data, there is some fake data supposed to be added. When I try to run main.api it bombs out with a runtime error. As always there's lots of it but the pertinent bit seems to be:
File "./main.py", line 53, in <module>
configure()
File "./main.py", line 20, in configure
configure_fake_data()
File "./main.py", line 45, in configure_fake_data
asyncio.run(report_service.add_report("Misty sunrise today, beautiful!", loc))
File "/Users/mike/.pyenv/versions/3.8.6/lib/python3.8/asyncio/runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'add_report' was never awaited
If I change the code not to call asyncio.run() and just call the functions it starts, but the fake data is not added at all.
I'm running Python v3.8.6 if that has any bearing.
Thanks for any ideas/hints and big thanks for a most excellent course!
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300501
- 0:22 like whether? So we're gonna build this web application here.
+ 0:22 like weather? So we're gonna build this web application here.
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300506
- 1:07 let's just put whether for now, and then we're gonna have this,
+ 1:07 let's just put weather for now, and then we're gonna have this,
- 1:10 let's call it "whether" and let's just say it's gonna return some report for the moment.
+ 1:10 let's call it "weather" and let's just say it's gonna return some report for the moment.
- 2:30 import whether_api and from a views import home".
+ 2:30 import weather_api and from a views import home".
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300705
- 0:20 Let's get something back, like "whether slash portland" and run it.
+ 0:20 Let's get something back, like "weather slash portland" and run it.
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300709
- 1:58 We're gonna put just put "e dot corruption".
+ 1:58 We're gonna put just put "e dot description".
- 3:43 Once we add one again reports and whether it's raining,
+ 3:43 Once we add one again reports some weather it's raining,
https://training.talkpython.fm/courses/transcript/getting-started-with-fastapi/lecture/300908
- 0:04 Give us the whether in a location,
+ 0:04 Give us the weather in a location,
The code starting with async with
block in the openweathermap service in the repo looks like this:
async with httpx.AsyncClient() as client:
resp = await client.get(url)
resp.raise_for_status()
data = resp.json()
forecast = data['main']
return forecast
Notice the final three lines which are not indented.
See https://github.com/talkpython/modern-apis-with-fastapi/blob/main/ch05-a-realistic-api/services/openweather_service.py
But the slide shown at 00:35 in the video tells that those lines should be indented and thus included in the async with
block.
So which is the right way to do this?
When calling uvicorn.run(api)
I get this error in Python 3.9.6
Expected type 'Union[Type[ASGI2Protocol], (Union[HTTPScope, WebSocketScope, LifespanScope], () -> Awaitable[Union[HTTPRequestEvent, HTTPDisconnectEvent, WebSocketConnectEvent, WebSocketReceiveEvent, WebSocketDisconnectEvent, LifespanStartupEvent, LifespanShutdownEvent]], (Union[HTTPResponseStartEvent, HTTPResponseBodyEvent, HTTPServerPushEvent, HTTPDisconnectEvent, WebSocketAcceptEvent, WebSocketSendEvent, WebSocketResponseStartEvent, WebSocketResponseBodyEvent, WebSocketCloseEvent, LifespanStartupCompleteEvent, LifespanStartupFailedEvent, LifespanShutdownCompleteEvent, LifespanShutdownFailedEvent]) -> Awaitable[None]) -> Awaitable[None], str]', got 'FastAPI' instead
You have awesome examples on working with external API's asynchronously using httpx.
It would be great if there was a small video on how to work with SQL/noSQL databases in this manner.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.