ML
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    FastAPI

    IT Discussion
    python rest
    1
    1
    357
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • stacksofplatesS
      stacksofplates
      last edited by

      Django and Flask have been the long running Python web frameworks that everyone chooses. FastAPI is a newish micro framework that allows for quick REST API development. We've been using FastAPI to write most of our microservices and it's working out pretty well. One catch is everything being asynchronous, but since FastAPI exposes a decorator for startup events, you can add them there vs manually creating tasks on the loop.

      To get started it's pretty simple. Create a file named main.py

      from fastapi import FastAPI
      
      app = FastAPI()
      
      
      @app.get("/testing/{id}")
      async def get_test(id: int):
          data = {"id": id}
          return data
      

      Then just run your app with Uvicorn: uvicorn "main:app" --reload

      --reload adds live reloading for when you make changes.

      The handler methods are defined through the decorators @app.get, @app.post, etc. This method makes a nice quick way to define endpoints. Decorators also control startup and shutdown events and even middleware. So adding middleware to your requests is pretty trivial:

      @app.middleware("http")
      async def timer(request: Request, call_next):
          start = time.time()
          resp = await call_next(request)
          total_time = time.time() - start
          print(f'request took {total_time} seconds')
      
          return resp
      

      So to put that all together it looks like this:

      from fastapi import FastAPI, Request
      import time
      
      
      app = FastAPI()
      
      
      @app.middleware("http")
      async def timer(request: Request, call_next):
          start = time.time()
          resp = await call_next(request)
          total_time = time.time() - start
          print(f'request took {total_time} seconds')
      
          return resp
      
      
      @app.get("/testing/{id}")
      async def get_test(id: int):
          data = {"id": id}
          return data
      
      1 Reply Last reply Reply Quote 2
      • 1 / 1
      • First post
        Last post