Giter Club home page Giter Club logo

modern-apis-with-fastapi's Introduction

Modern APIs with FastAPI course

A course from Talk Python Training. Sign up at talkpython.fm/fastapi.

Course Summary

FastAPI is one of the most exciting new web frameworks out today. It's exciting because it leverages more of the modern Python language features than any other framework: type hints, async and await, dataclasses, and much more. If you are building an API in Python, you have many choices. But, to us, FastAPI is the clear choice going forward. And this course will teach you everything you need to know to get started. We'll build a realistic API working with live data and deploy that API to a cloud server Linux VM. In fact, you'll even see how to create proper HTML web pages to augment your API all within FastAPI.

What's this course about and how is it different?

This course is designed to get you creating new APIs running in the cloud with FastAPIs quickly. We start off with just a little foundational concepts, then jump right into build our first API with FastAPI.

Then we explore the foundational modern Python features to make sure you're ready to take full advantage of this framework. We'll look at how async and await works in Python, how to build self-validating and describing classes with Pydantic, Python 3's type hints, and other core language concepts.

We round out the course by building a realistic API working with live data. Then we deploy that API using nginx + gunicorn + uvicorn running on Ubuntu in a cloud VM at Digital Ocean.

What topics are covered

In this course, you will:

  • See how simple working with basic APIs in FastAPI can be.
  • Create API methods that handle common HTTP verbs (GET, POST, DELETE, etc)
  • Return JSON data to API clients
  • Use async and await to create truly scalable applications
  • Leverage Pydantic to create required and optional data exchange
  • Have FastAPI automatically validate and convert data types (e.g. "2021-01-05" to a datetime)
  • Organize your app using APIRoutes to properly factor your application across Python files.
  • Return the most appropriate error response (e.g. 400 Bad Request) to API clients
  • To deploy Python web applications in production-ready configurations on Linux
  • Understand why gunicorn and uvicorn should be used together in production
  • And lots more

View the full course outline.

Who is this course for?

This course is for anyone who wants to build an API with Python as the backend language. If you want your API to rival the speed and features of any major web API framework, this is the course to take.

The student requirements are quite light for this course. You'll need Basic Python language knowledge:

  • Functions
  • Strings
  • Variables
  • API clients (making a call with requests)

Note: All software used during this course, including editors, Python language, etc., are 100% free and open source. You won't have to buy anything to take the course.

Sound good?

If this sounds like a great course for you, take it over at talkpython.fm/fastapi.

modern-apis-with-fastapi's People

Contributors

mikeckennedy avatar prezu avatar serixscorpio avatar sgrimes-irc avatar shireenrao avatar tompropst avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modern-apis-with-fastapi's Issues

Runtime error when the fake data is supposed to be added

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!

Course video ch.5 vid 14/14 "Concept: Async API methods" - slides vs. repo descrepancy

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?

AWAIT ERROR

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)

Feature request: asyncronous database queries

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.

Because UV acorns looks cool but can't serve Python code... :)

TRANSCRIPT CORRECTIONS SUGGESTIONS

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, 

Expected type 'Union[Type[ASGI2Protocol]

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

Because I'm not sure what a whether app would look like... :)

TRANSCRIPT CORRECTIONS SUGGESTIONS

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, 

Project dependencies may have API risk issues

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.

The calling methods from the fastapi
fastapi.FastAPI
fastapi.FastAPI.get
fastapi.APIRouter.get
fastapi.Response
fastapi.APIRouter
fastapi.FastAPI.include_router
fastapi.APIRouter.post
fastapi.Depends
The calling methods from the httpx
httpx.AsyncClient
The calling methods from the requests
requests.get
requests.post
The calling methods from the all methods
__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.

FastAPI UI not appearing

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):
image

Versus what I see in your videos (options to show raw data or formatted):
image

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.

Here's my venv:
image

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")

bootstrap not loading from layout.html

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">

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.