• Stars
    star
    162
  • Rank 232,284 (Top 5 %)
  • Language
    Python
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Example CRUD API in Python using FastAPI, Pydantic and pyMongo

FastAPI + Pydantic + MongoDB REST API Example

Sample API using FastAPI, Pydantic models and settings, and MongoDB as database - non-async.

The API works with a single entity, "Person" (or "People" in plural) that gets stored on a single Mongo database and collection.

The code is intended to create the whole OpenAPI documentation with the maximum detail, including full, detailed models for requests, responses and errors.

Endpoints

Endpoints define the whole CRUD operations that can be performed on Person entities:

  • GET /docs - OpenAPI documentation (generated by FastAPI)
  • GET /people - list all available persons
  • GET /people/{person_id} - get a single person by its unique ID
  • POST /people - create a new person
  • PATCH /people/{person_id} - update an existing person
  • DELETE /people/{person_id} - delete an existing person

Project structure (modules)

  • app.py: initialization of FastAPI and all the routes used by the API. On APIs with more endpoints and different entities, would be better to split the routes in different modules by their context or entity.
  • models: definition of all model classes. As we are using MongoDB, we can use the same JSON schema for API request/response and storage. However, different classes for the same entity are required, depending on the context:
    • person_update.py: model used as PATCH request body. Includes all the fields that can be updated, set as optional.
    • person_create.py: model used as POST request body. Includes all the fields from the Update model, but all those fields that are required on Create, must be re-declared (in type and Field value).
    • person_read.py: model used as GET and POST response body. Includes all the fields from the Create model, plus the person_id (which comes from the _id field in Mongo document) and the age (calculated from the date of birth, if any).
    • person_address.py: part of the Person model, address attribute.
    • common.py: definition of the common BaseModel, from which all the model classes inherit, directly or indirectly.
    • fields.py: definition of Fields, which are the values of the models attributes. Their main purpose is to complete the OpenAPI documentation by providing a description and examples. Fields are declared outside the classes because of the re-declaration required between Update and Create models.
    • errors.py: error models. They are referenced on Exception classes defined in exceptions.py.
  • database.py: initialization of MongoDB client. Actually is very short as Mongo/pymongo do not require to pre-connecting to Mongo or setup the database/collection, but with other databases (like SQL-like using SQLAlchemy) this can get more complex.
  • exceptions.py: custom exceptions, that can be translated to JSON responses the API can return to clients (mainly if a Person does not exist or already exists).
  • middlewares.py: the Request Handler middleware catches the exceptions raised while processing requests, and tries to translate them into responses given to the clients.
  • repositories.py: methods that interact with the Mongo database to read or write Person data. These methods are directly called from the route handlers.
  • exceptions.py: custom exceptions raised during request processing. They have an error model associated, so OpenAPI documentation can show the error models. Also define the error message and status code returned.
  • settings.py: load of application settings through environment variables or dotenv file, using Pydantic's BaseSettings classes.
  • utils.py: misc helper functions.
  • tests: acceptance+integration tests, that run directly against the API endpoints and real Mongo database.

Requirements

make tools

# Install requirements
make install-requirements

# Run the app (available at http://localhost:5000/...)
make run

# Install test requirements
make install-test-requirements

# Start MongoDB for tests (requires Docker)
make start-test-mongo

# Run the tests
make test

More Repositories

1

ThisPersonDoesNotExistAPI

Unofficial "API" for the ThisPersonDoesNotExist webpage, that returns a random fictional person picture generated by AI
Python
124
star
2

dalle-mini-telegram-bot

A Telegram bot interface for DALL·E mini
Python
51
star
3

python-qqddm

Python wrapper for QQ "Different Dimension Me" AI (convert pictures into anime avatars)
Python
20
star
4

MQTT2MongoDB

Store all incoming 🦟MQTT messages on 🍃MongoDB
Python
18
star
5

VigoBusAPI

Updated REST API that provide Stops and Buses information for the public transport system of the city of Vigo (Galicia/Spain) 🚌🚏
Python
17
star
6

Dockerized-Python-SSH

Docker image with Python + SSH server 🐍🔐🐳
Dockerfile
13
star
7

MQTT2NotifySend

🌉Bridge between MQTT and 🖥️Freedesktop.org Notify-Send desktop notifications (Ubuntu & other distros)🐧 - Send notifications from MQTT directly to your desktop!
Shell
13
star
8

VigoBus-TelegramBot

Bot de Telegram para ver los horarios de los autobuses de Vigo por paradas 🤖🚌🚏
Python
11
star
9

TDTSpain2VLC

Script Python para descargar el listado de canales TDT por streaming de TV-Online-TDT-Spain y convertirlo a una playlist XSPF para VLC
Python
10
star
10

MQTT2MySQL

Store all incoming 🦟MQTT messages on 🐬MySQL/MariaDB
Python
9
star
11

Docker-PortForward

Docker image for setting up one or multiple TCP ports forwarding, using socat
Go
9
star
12

pnytter

Python library for scraping (Twiiter) Nitter
Python
8
star
13

Telegram-BusBot-DataManager

Persistent data managing API to be used by a Telegram bot serving a public transportation service 🤖🚌💾
Python
8
star
14

Docker-Python-Git-App

🐳Docker image to deploy a 🐍Python app hosted on a Git repository
Python
8
star
15

GTAV-SimpleGangWar

Grand Theft Auto V script to create a basic battle between two teams
C#
8
star
16

Docker-SSH-Port-Forward-Server

Dockerized SSH server that allows TCP local and remote port forwarding
Python
6
star
17

Docker-SSH-Port-Forward-Client

Dockerized SSH client to forward a remote port to local host 🐳🔐🔌
Python
6
star
18

Arango-Foxx-Inventory-API

CRUD REST API to store generic items hierarchically or container-based on ArangoDB, as a Foxx microservice 🥑🦊📦
JavaScript
5
star
19

RDR2-SimpleGangWar

Red Dead Redemption 2 script to create a basic battle between two teams
C#
5
star
20

Arduino-PowerOutageDetector

Simple Arduino project to detect power outages
C++
4
star
21

twitterscraper

Twitter profiles scraper, based on microservices and AMQP queues
Python
4
star
22

ArduinoInternetMonitor

An Arduino sketch that will ping external servers and reboot your router when Internet is down
Arduino
4
star
23

HurdyGurdy-Rock-Metal-Spotify-Playlist

Spotify collaborative playlist featuring Rock/Metal songs that include Hurdy Gurdy
Python
4
star
24

GTAIV-SimpleGangWar

Grand Theft Auto IV script to create a basic battle between two teams
C#
4
star
25

Python-DotEnv-Settings-Handler

⚙️Settings handler to load settings from a DotEnv file or system env variables, on a Python class, using pydantic
Python
4
star
26

Skyrim-SE-Personal-Mod-List

Personal mod list for Skyrim SE, focusing on realism and inmersion
3
star
27

AccuracyFix

A GTA V script for globally controlling the accuracy for all AI peds
C#
3
star
28

python-wait4it

Python module to wait for a TCP port to be available
Python
3
star
29

mountagne

A disk automounting service
Python
2
star
30

Docker-Nextcloud-Webcron

Run a Docker container to keep the Nextcloud background jobs running using WebCron
Dockerfile
2
star
31

Python_UPnP_Manager

A better understanding Python tool for creating, removing and managing UPnP port mappings using miniupnpc
Python
2
star
32

MQTT2ETCD

Send configuration from 🦟MQTT to ⚙️ETCD and vice versa
Python
2
star
33

OpenWRT-MQTT-Scripts

Useful MQTT-related shell scripts I use within OpenWRT routers
Shell
2
star
34

MQTT2InfluxDB

Log 🦟MQTT messages on 🕓InfluxDB
Python
2
star
35

ping2mqtt

Service that periodically ICMP-pings hosts and publishes the results in MQTT topics
Python
2
star
36

pvpc

Repositorio con los precios de la luz PVPC, actualizados diariamente mediante Github Actions
Python
2
star
37

Assassins-Creed-II-OpenTexMod-Launcher

Pair of Batch scripts that launch Assassin's Creed II on PC using OpenTexMod
Batchfile
2
star
38

Docker-Python-Autoclonable-App

🐍 🐳 A Docker that downloads a Git repository with a Python app you want to deploy when a container runs for the first time
Shell
2
star
39

Presentacion-Raspberry-GPIO-Python-gpiozero

Presentación de uso de los GPIO de Raspberry Pi en Python usando la librería gpiozero
Python
2
star
40

Python-Enhanced-MQTT-Client

Improved paho.mqtt-based client with initial reconnection and decorators
Python
2
star
41

Spotify-Collaborative-Public-Playlists-Template

Manage Spotify Public playlists from Github!
Python
2
star
42

Basic_Python_TelegramBot

A very simple Python tool to send messages via a Telegram bot
Python
2
star
43

Docker-DuckDNS

Docker image to auto-update DuckDNS domains
Shell
2
star
44

FastAPI-Pydantic-SQLAlchemy-PetShelter-API

Example of a full REST API created with Python, FastAPI, Pydantic & SQLAlchemy to persist data for a fictional Pet Shelter
Python
2
star
45

ZeroHealthCheck

Simple ZeroMQ-based host/service healthcheck monitor written in Python
Python
2
star
46

David-Lor

2
star
47

ScreamingInjuredPeds

Screaming Injured Peds script for Grand Theft Auto V
C#
1
star
48

Pydantic-BaseSettings-lightning-talk

Lightning talk slideshow & examples about Pydantic's BaseSettings usage
1
star
49

SelectiveFire

SelectiveFire is a GTA V mod, featuring alternative fire modes on weapons, such as semi-auto and burst fire
C#
1
star
50

pyTelegramBotApi-Presentaciones

Python
1
star
51

archive.org-telegrambot

Telegram bot that saves links on Archive.org. Written in Go, using AMQP
1
star
52

Docker-Signal-Desktop-GUI

Docker image for the Signal messaging desktop app, accessible through a web browser or VNC
Dockerfile
1
star
53

PhoneBills

PhoneBills script for Grand Theft Auto V
C#
1
star
54

GTAV-GangWarReloaded

GTA V GangWar scripts
C#
1
star
55

action-tag-on-pr-merge

Github Action for creating a new Tag on a Pull Request merge
1
star
56

RPi-NetMonitor

A Raspberry Pi project: Network Monitor
Python
1
star
57

TirasLedMicropythonMQTT

Proyecto de domotización de tiras LED con Micropython, ESP8266, MQTT y PIR
1
star
58

LocationalDamage

A GTA V script featuring a realistic health-armor-damage system
C#
1
star
59

TelegramBot-Webhook-Updates-Receiver-Service

Proof of Concept of a Service to receive Telegram Bot updates through Webhook and publish/enqueue them on a message broker
Python
1
star
60

Python-PubProxy-API

A Python wrapper for the pubproxy.com public proxy API
Python
1
star
61

MQTT2Docker

Shell scripts to interact with Docker containers through MQTT
Shell
1
star
62

ESP8266_MicroPython_PCMonitor

A Micropython script to monitorize a computer Power Status and turn it ON/OFF by hardware
Python
1
star
63

RPi-TelegramBot-Psutil

Python
1
star
64

Logging-Requests-POC

POC of an API with per-request contextualized logs
Python
1
star
65

PyBuses

A Python framework to help working with bus stops and incoming buses data 🚍
Python
1
star
66

FastAPI_LightningTalk-Notebook

FastAPI first steps with examples, within a Jupyter Notebook
Jupyter Notebook
1
star
67

dgtscraper

Utilidad para descargar y parsear datasets de matriculaciones de la DGT
Python
1
star
68

Node-RED_TorrentSearch

Node-RED flow to search and download torrents from RARBG
1
star
69

InjuredRagdollEnhanced

Injured Ragdoll Enhanced script for Grand Theft Auto V (PC)
C#
1
star
70

TMUX-Python-Interface

Python script para controlar TMUX sin introducir comandos para crear pantallas o acceder a pantallas abiertas.
Python
1
star
71

Docker-BOINC-Manager-GUI

Docker image to deploy BOINC Manager with GUI, accesible through web browser & VNC
Makefile
1
star
72

Conda-Menu

A console menu to manage your Conda virtual envs: create new envs, view created envs, activate an env, delete an env
Python
1
star
73

IsMyHomeOnline

A set of client-server scripts to notify you via Telegram when your home internet connection is down and up again
PHP
1
star