FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python-type hints. The key features are fast to code, fewer bugs, easy to use, easy to learn, and automatic interactive API documentation.
Key Features:
- Fast: FastAPI is one of the fastest frameworks for building APIs with Python, only slower than NodeJS and Starlette (which is used as the base of FastAPI).
- Pythonic: The main goal of FastAPI is to be easy to use while also enabling new, high-level features not available before.
- Easy: It’s designed to be easy to use and learn.
- Data validation: Validate data using Pydantic.
- Interactive API documentation: With the use of Python type hints and Pydantic models, FastAPI automatically generates beautiful interactive API documentation (using Swagger UI and ReDoc) that lets you call and test your API directly from the browser.
Quick Start:
- Installation
Install FastAPI and an ASGI server, such as Uvicorn:
pip install fastapi[all] uvicorn
- Basic Example
A simple FastAPI application might look like this:
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, query_param: str = None):
return {"item_id": item_id, "query_param": query_param}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
To run the app, use the command:
uvicorn your_module_name:app --reload
The --reload
flag allows the server to reload upon code changes, making it ideal for development.
- Define Data Models
Use Pydantic to create data models:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
- POST Request Example
A route handling POST requests and receiving a body might look like this:
@app.post("/items/")
def create_item(item: Item):
return item
- API Documentation
You can view the automatic interactive API documentation of your API by visiting:
- Swagger UI:
http://127.0.0.1:8000/docs
- ReDoc:
http://127.0.0.1:8000/redoc
- Dependency Injection
FastAPI includes a very simple to use, but extremely powerful dependency injection system. It’s designed to be easy for a newcomer while giving the maximum power to an expert developer. - Asynchronous and Synchronous Code
FastAPI supports both asynchronous and traditional synchronous code, allowing for high performance while also making it simpler to write certain types of logic.
Advantages of Using FastAPI:
- FastAPI allows you to build APIs for data validation, data conversion, authentication, and asynchronous communication, among other things, very quickly.
- Automatic interactive API docs.
- Built-in OAuth2 and JWT.
- Data validation and serialization/deserialization with Pydantic.
- Asynchronous and synchronous code.
FastAPI has been designed to be easy to use, while also enabling new, high-level features not available before. It’s a robust framework for different use cases but is particularly good for building high-performance, asynchronous APIs.
For more in-depth knowledge and usage of different capabilities of FastAPI, refer to the official documentation.
Creating a URL shortener using FastAPI can be quite straightforward due to its simplicity and performance.
Below is a simple example of a URL shortener implemented in FastAPI. Note that this example stores the original and short URLs in memory, meaning all data will be lost when the application is restarted. For a production application, you’d want to use a persistent database.
First, install FastAPI and an ASGI server, such as uvicorn:
pip install fastapi uvicorn
Here’s a basic example of a FastAPI application that implements a simple URL shortener:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
import hashlib
app = FastAPI()
url_mapping = {} # {short_url: original_url}
class Url(BaseModel):
original_url: HttpUrl
@app.post("/shorten-url")
def shorten_url(url: Url):
# Generate a unique hash for the URL
url_hash = hashlib.md5(url.original_url.encode()).hexdigest()[:6]
# Store it in the mapping
url_mapping[url_hash] = url.original_url
return {"short_url": f"/{url_hash}"}
@app.get("/{short_url}")
def redirect_to_original(short_url: str):
# Retrieve the original URL
original_url = url_mapping.get(short_url)
# Return an error if the short_url is not found in our mapping
if original_url is None:
raise HTTPException(status_code=404, detail="Short URL not found")
return {"original_url": original_url}
Explanation:
- Url model: Defines the data structure for original URLs. The URL must be valid due to the
HttpUrl
type. shorten_url
endpoint: Takes a URL, hashes it to create a unique ID, stores the original URL in a dictionary with the hash as the key, and returns the shortened URL.redirect_to_original
endpoint: Retrieves the original URL using the short hash. If the hash is not found, a 404 error is returned.
Running the Application:
To run the application, use Uvicorn:
uvicorn your_file_name:app --reload
Make sure to replace your_file_name
with the actual name of your Python file. This basic URL shortener example doesn’t perform actual redirection but instead returns the original URL to demonstrate a simple mapping process. In a full application, you’d want to implement HTTP redirection and likely use a database to persist the URL mappings.
For production deployments, consider using a more robust ASGI server configuration and ensure that you’re handling all necessary aspects of URL validation and security.