Chapter 8
Chpater 8
- WebSockets
- The WebSocket protocol has introduced ws:// and wss:// as the new URI schemes. In other words, instead of http:// (or https://), the WebSocket URL is prefixed by ws:// (or wss://)
- To establish a WebSocket connection, the client browser sends a WebSocket handshake request to a server to upgrade the connection, along with a Sec-WebSocket-Key header. The server ackonlwedges the handshake and inserts a hash of the key in a Sec-WebSocket-Auth header.
- Once the connection is established, it doesn't need to follow the HTTP protocol. A server application commmunicates with each client individually. Since WebSocket is a persistent connection, the server and the client can continue to exchange messages for any length of time until one of them chooses to close the session. In the WebSocket communication, event-driven web programming is possible.
-
To install websocket
-
WebSocket Server:
- to start up a WebSocket server, call the
serve()coroutine defined in thewebsocketsmodule and provide ws_handler, host, and port as arguments.
The handler coroutine (
hello()) basically waits for the client to request connection, consumes the data it receives, and then sends back its response. - to start up a WebSocket server, call the
-
FastAPI has an integrated support of the WebSocket protocol. Just as the HTTP path operations are handled by the path operation decorators, th FastAPI app object defines the
@app.websocket()decorator. It starts a WebSocket server that listens for incoming requests at the URL path given as a string parameter. -
Test WebSocket with Insomnia
- Insomnia is a cross-platform desktop application to test REST, WebSocket, and graphQL APIs.
- PostMan can also test REST, WebSocket, and GraphQL
-
The fact that WebSocket is a bidrectional communication protocol makes it ideal for building real-time applications. We can implenment a chat with multiple clients interacting simultaneously.
- The functionality of maintaining the list of currently live connections and sending and broadcasting the message is handled by the
Connection_handlerclass (see chap/app.py for example)
- The functionality of maintaining the list of currently live connections and sending and broadcasting the message is handled by the
-
GraphQL
- A major drawback of REST is that a client downloads more information than is actually required for its consumption.
- With its declarative data fetching, the GraphQL client is able to ask for exactly what data it needs from an API. Another feature of GraphQL is that a GraphQL server only exposes a single endpoint as against REST where multiple endpoints are defined.
- Contrary to a common misconception, GraphQL is not a database technology. It is a query language for APIs and has nothing to do with SQL which is used by databases.
-
Schema definition language (SDL): GraphQL uses the Scehma Definition Language to write the API schema
- As mentiond earlier, a GraphQL API exposes only a single endpoint. Clients can determine exactly what its requirements are.
-
Query: users specify payloads of the query
-
Mutations:
- to create or add new data
- to update or modify data
- to delete data
-
Subscriptions:
- there is a concept of subscriptions: a real-time connection to the server is available, and the client immediately gets information about important events. If a client subscribes to an event, the server pushes the corresponding data to it, whenever that particualr event then actually happens.
- Schema:
- A GraphQL schema is a collection of GraphQL root types. The special root types are included in the definition of the schema of an API.
- Strawberry GraphQL
- there are quite a few Python libraries available for implementing the GraphQL protocol
- Ariadne
- Strawberry
- Tartiflette
- Graphene
- The latest releases of FastAPI recommend the Strawberry library for working with GraphQL
-
FastAPI events:
- FastAPI has two decorators --
@app.on_event("startup")and@app.on_even("shutdown"). The decorated functions will fire as and when these events occur. Obviously, both events occur once during each run. This feature can be effectively utilized to perform a mandatory activity as the application starts and just before the server stops. A typical use case can be starting and closing the database connection. -
newer version recommends
lifespan -
Mounting WSGI application
- You can use an existing Flask/Django application as a subapplication along with FastAPI. Flask and Django frameworks implement WSGI. To mount a Flask application, it should be wrapped with WSGIMiddleware.
# flask_app.py
from flask import Flask
flask_app = Flask(__name__)
@flasl_app.route("/")
def index_flask():
return "Hello World"
# fastapi.py
from fastapi import FastAPI
from fastapi.middleware.wsgi import WSGIMiddleware
from flask_app import flask_app
app = FastAPI()
app.mount("/flask", WSGIMiddleware(flask_app))