Fast API
FastAPI targets development of web APIs. FastAPI was mainly designed to build APIs, and its default input is JSON
. FastAPI itself does not include a web server but recommends Uvicorn
.
You can start Uvicorn
and the FastAPI web application in two ways:
- externally (or)
- internally
1. To start Uvicorn externally, via the command line
# Start Uvicorn with the command line
$ uvicorn hello:app --reload
# The hello refers to the hello.py file, and app is the FastAPI variable name within it.
2. To start Uvicorn internally in the application itself
# Start Uvicorn internally
from fastapi import FastAPI
app = FastAPI()
@app.get("/hi")
def greet():
return "Hello? World?"
if __name__ == "__main__":
import uvicorn
uvicorn.run("hello:app", reload=True)
In either case, that reload tells Uvicorn to restart the web server if hello.py changes.
Test FastAPI after Installing
To make sure the installation worked, we can open a Python interactive shell and try to import the FastAPI
package:
Installing the HTTPie command-line utility
FastAPI
automatic documentation (we'll talk about this later in the book)Postman
, a GUI tool to perform HTTP requestscURL
, the well-known and widely used command-line tool to perform network requestsHTTPie
, a command-line tool aimed at making HTTP requests with an intuitive syntax, JSON support, and syntax highlighting.
# GET
$ http GET https://603cca51f4333a0017b68509.mockapi.io/todos
#POST
$ http -v POST https://603cca51f4333a0017b68509.mockapi.io/todos text="My new task"
#
$ http -v GET https://603cca51f4333a0017b68509.mockapi.io/todos "My-Header: My-Header-Value"
Web Tools
The main Python web tools (FastAPI):
FastAPI
: The web framework itselfUvicorn
: An asynchronous web serverHTTPie
: A text web client, similar to curlRequests
: A synchronous web client packageHTTPX
: A synchronous/asynchronous web client package
SQLAlchemy
SQLAlchemy is the most popular ORM library and can establish communication between any Python-based application and database platform.
This ORM is a boilerplated interface that aims to create a database-agnostic data layer that can connect to any database engine. But compared to other ORMs, SQLAlchemy is DBA-friendly because it can generate optimized native SQL statements.
Installing the database driver
SQLAlchemy will not work without the required database driver. It is mandatory to install the psycopg2
dialect since the database of choice is PostgreSQL: