Python Web APIs with Uvicorn and FastAPI

in #technology3 months ago

Have you ever needed to knock up a REST API really quick, but didn't want to leave your Python comfort zone?

Or had to make your Python interoperate with another tech stacK?

There is an amazing solution ...

Install uvicorn with dependencies

sudo pip3 install 'uvicorn[standard]'

This will install uvicorn with a good set of dependencies and "extras".

  • Uvloop - a fast, drop-in replacement of the built-in asyncio event loop.
  • The built-in asyncio event loop.
  • HTTP protocol handled by httptools.
  • Websockets
  • --reload flag in development mode will use watchfiles.
  • Colorama installed for Windows colored logs.
  • python-dotenv will be installed (use the --env-file option).
  • PyYAML will be installed (provide a .yaml file to --log-config).

'Hello World' First Uvicorn App

Create an application called main.py

async def app(scope, receive, send):
    assert scope['type'] == 'http'

    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [
            [b'content-type', b'text/plain'],
        ],
    })
    await send({
        'type': 'http.response.body',
        'body': b'Hello, world!',
    })

Run the server:

uvicorn main:app

If, like me, you have a development server that you interact with over SSH, instead of that command you should specify the IP address, like so:

uvicorn main:app --host 192.168.0.93 (substituting for your dev server IP address)

Fast API

sudo pip3 install fastapi

Then create or edit main.py:

from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}

Run with:

fastapi dev main.py

Again you can use the default or specify your dev IP by adding:

--host 192.168.0.93

As well as the root of the API, we added an API endpoint that takes two parameters:

  • /items/{item_id}
  • ?q=

The first is a "path" based parameter, for example it could be a product in a store, or an article like in your Hive blog.

We can also pass in "query" parameters, identified with the question mark, where we pass in a string on the URL, for example it could be a search or a filter.

FastAPI Docs

Where FastAPI is unusually helpful is it autogenerates a docs KB for you!

Simply go to the URL as before but add /docs to the path and you will see the documentation for your API.

Screenshot by Dropbox Capture.png

Magic!

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.