FastAPI backend for Repost

Overview

Repost FastAPI

This is the FastAPI implementation of the Repost API.

Installation

Python 3 must be installed and accessible through the use of a terminal and the keyword python or python3. Below are the steps for a proper setup using VENV (Python Virtual Environment).

  1. Clone the repository
git clone https://github.com/pckv/repost-fastapi.git
  1. Navigate to the repost-fastapi directory and create a new VENV
cd repost-fastapi
python -m venv venv

3 (Linux). Activate the venv (alternatively: run all commands after this step prefixed with venv/bin/)

source venv/bin/activate

3 (Windows). Activate the venv (alternatively: run all commands after this step prefixed with venv\Scripts\)

venv\Scripts\activate
  1. Install the required packages
pip install -r requirements.txt

Configurations

Configurations are set by environment variables. Follow the instructions below to run the server once and a file config.env will be created in the root directory. Otherwise, the following settings can also be set using exported environment variables.

  • REPOST_CLIENT_ID - The OAuth2 client_id. Default is repost
  • REPOST_JWT_SECRET - The secret key used for JSON Web Tokens
  • REPOST_JWT_ALGORIGHTM - The algorithm used for the key above
  • REPOST_DATABASE_URL - An SQLAlchemy database url. See Engine Configuration
  • REPOST_ORIGINS - A list of CORS URLs separated by ;

Running the API with uvicorn

Uvicorn is a single-threaded ASGI server designed around uvloop to run fast. It is included in the requirements and should be used to run the API.

uvicorn repost:app

The default host and port is localhost and 8000. They can be changed with the --host and --port arguments. To run the server publically, set the host to 0.0.0.0 like so.

uvicorn repost:app --host 0.0.0.0

Running the API with gunicorn

Gunicorn is a WSGI server that can manage multiple workers. Uvicorn has a worker for Gunicorn that can be used to run multiple Uvicorn workers. Since Repost is a stateless API, this works perfectly and will allow utilizing more processing power.

gunicorn repost:app -w 17 -k uvicorn.workers.UvicornWorker

The example above uses 17 workers for a system with 8 CPUs (16 threads + 1 workers). This value can be tweaked to your setup. You can also set the host and port in gunicorn with the -b argument, which includes both host and port in the same argument.

gunicorn repost:app -b 0.0.0.0:8000 -w 17 -k uvicorn.workers.UvicornWorker

Documentation

Documentation for the API is available after deployment at the /api/swagger and /api/docs endpoints.

Comments
  • Change routes to only use the required resource

    Change routes to only use the required resource

    The previous routing system got unnecessarily complex, with actions on comments requiring references for 3 items: /resubs/{resub}/posts/{post}/comments/{comment}/vote/{vote}. The comment id is unique, and as such the references to resub and post are useless here.

    This PR removes the unused references, and by doing so, the specific route files only need resolvers for their respective resource. E.g /resubs/{resub}/posts was moved from routes/posts.py to routes/resubs.py.

    enhancement 
    opened by pckv 1
  • Create CRUD functions and implement endpoints for users

    Create CRUD functions and implement endpoints for users

    This includes authorization, so the JWT functions are now used to authorize and authenticate users.

    Still missing resub, comment and post endpoints. Refer to #26.

    Resolves #20 Also resolves #18 in that resolve_current_user uses resolve_user, which will inherently raise 404 Not Found for any tokens with a username for a user that doesn't exist.

    Some discussion

    Currently the CRUD function for update_user uses **columns in order to easily modify only the requested columns. This ties in nicely with the API schema, which can simply be written as:

    **edited_user.dict(exclude_unset=True)
    

    The drawback of this solution is that the modifiable columns are not documented in the update_user functions. But at the same time, it makes it very easy to implement in both the API and the CRUD aspect.

    enhancement database 
    opened by pckv 1
  • Implement OAuth2 client_id and scope validation

    Implement OAuth2 client_id and scope validation

    This PR ensures OAuth2 consistency with pckv/repost-aspnet and EspenK/repost-spring by validating client_id and checking OAuth2 scopes.

    There is only one scope user, and providing no scope will by default choose all scopes. Therefore, a token issued by the server should always have only the user scope in Swagger UI.

    enhancement 
    opened by pckv 0
  • Update authentication response status messages to fit Spring Boot implementation

    Update authentication response status messages to fit Spring Boot implementation

    In Spring OAuth2 Boot, invalid credentials is a 400 Bad Request, whereas it's a 401 Unauthorized in our FastAPI implementaion. 400 makes more sense for this.

    In Spring OAuth2 Boot, invalid tokens are always a 401 Unauthorized, even for unparsable tokens. This kinda makes sense, so we can implement that here too.

    bug 
    opened by pckv 0
  • Update vote path and cascade delete votes

    Update vote path and cascade delete votes

    Votes were previously left behind when deleting a post/comment. This meant that new posts with the same ID would be assigned those votes.

    The same considerations need to be applied to deletion of any other object. A note for this discussion is created in https://github.com/pckv/repost-fastapi/projects/1

    bug 
    opened by pckv 0
  • Avoid using external dependencies

    Avoid using external dependencies

    Currently, we are using starlette's status fields. This means that starlette is a dependency and should be in requirements.txt (if FastAPI stops using starlette at some point, it would be incompatible). FastAPI has its own status, so we should be using that.

    Same for any others that we may be using. PyCharm will show where these are.

    (this is not actually required for our project, but it would be a good consideration for a project with a longer lifespan)

    opened by pckv 0
  • Invalid token due to deleted user should respond with 401 Unauthorized

    Invalid token due to deleted user should respond with 401 Unauthorized

    If a user is deleted, the token should be invalid and therefore yield a 401 Unauthorized response. Currently, we would have to document a 404 on every authorized endpoint as well, which makes little sense.

    opened by pckv 0
  • Create a custom endpoint for replies that stays consistent with the API

    Create a custom endpoint for replies that stays consistent with the API

    The current solution uses a query parameter for parent_comment_id which is not consistent with the style of the rest of the API. This implementation adds the parent_id to a comment when it is submitted under another specific comment_id.

    POST /resubs/{resub}/posts/{post_id}/comments creates a top level comment
    POST /resubs/{resub}/posts/{post_id}/comments/{comment_id} creates a reply

    Another solution would be to add a parent_comment_id: Optional[int] parameter to the CreateComment schema (although personally I think this solution fits the API pattern more).

    bug enhancement 
    opened by pckv 0
  • Bump fastapi from 0.53.0 to 0.65.2

    Bump fastapi from 0.53.0 to 0.65.2

    Bumps fastapi from 0.53.0 to 0.65.2.

    Release notes

    Sourced from fastapi's releases.

    0.65.2

    Security fixes

    This change fixes a CSRF security vulnerability when using cookies for authentication in path operations with JSON payloads sent by browsers.

    In versions lower than 0.65.2, FastAPI would try to read the request payload as JSON even if the content-type header sent was not set to application/json or a compatible JSON media type (e.g. application/geo+json).

    So, a request with a content type of text/plain containing JSON data would be accepted and the JSON data would be extracted.

    But requests with content type text/plain are exempt from CORS preflights, for being considered Simple requests. So, the browser would execute them right away including cookies, and the text content could be a JSON string that would be parsed and accepted by the FastAPI application.

    See CVE-2021-32677 for more details.

    Thanks to Dima Boger for the security report! 🙇🔒

    Internal

    0.65.1

    Security fixes

    0.65.0

    Breaking Changes - Upgrade

    • ⬆️ Upgrade Starlette to 0.14.2, including internal UJSONResponse migrated from Starlette. This includes several bug fixes and features from Starlette. PR #2335 by @​hanneskuettner.

    Translations

    Internal

    0.64.0

    Features

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Bump uvicorn from 0.11.3 to 0.11.7

    Bump uvicorn from 0.11.3 to 0.11.7

    Bumps uvicorn from 0.11.3 to 0.11.7.

    Release notes

    Sourced from uvicorn's releases.

    Version 0.11.7

    0.11.7

    • SECURITY FIX: Prevent sending invalid HTTP header names and values.
    • SECURITY FIX: Ensure path value is escaped before logging to the console.

    Version 0.11.6

    • Fix overriding the root logger.

    Version 0.11.5

    • Revert "Watch all files, not just .py" due to unexpected side effects.
    • Revert "Pass through gunicorn timeout config." due to unexpected side effects.

    Version 0.11.4

    • Use watchgod, if installed, for watching code changes.
    • Reload application when any files in watched directories change, not just .py files.
    Changelog

    Sourced from uvicorn's changelog.

    0.11.7

    • SECURITY FIX: Prevent sending invalid HTTP header names and values.
    • SECURITY FIX: Ensure path value is escaped before logging to the console.

    0.11.6

    • Fix overriding the root logger.

    0.11.5

    • Revert "Watch all files, not just .py" due to unexpected side effects.
    • Revert "Pass through gunicorn timeout config." due to unexpected side effects.

    0.11.4

    • Use watchgod, if installed, for watching code changes.
    • Watch all files, not just .py.
    • Pass through gunicorn timeout config.
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Owner
PC
Computer engineer @Safepath-AS
PC
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

FastAPI Ariadne Example Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI - GitHub ###Запуск на локальном окру

ZeBrains Team 9 Nov 10, 2022
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 1, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 2022
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

Glib 14 Dec 5, 2022
Code Specialist 27 Oct 16, 2022
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 2022
Qwerkey is a social media platform for connecting and learning more about mechanical keyboards built on React and Redux in the frontend and Flask in the backend on top of a PostgreSQL database.

Flask React Project This is the backend for the Flask React project. Getting started Clone this repository (only this branch) git clone https://github

Peter Mai 22 Dec 20, 2022
A simple Blogging Backend app created with Fast API

This is a simple blogging app backend built with FastAPI. This project is created to simulate a real CRUD blogging system. It is built to be used by s

Owusu Kelvin Clark 13 Mar 24, 2022
A dynamic FastAPI router that automatically creates CRUD routes for your models

⚡ Create CRUD routes with lighting speed ⚡ A dynamic FastAPI router that automatically creates CRUD routes for your models

Adam Watkins 950 Jan 8, 2023
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 7, 2023
Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

identix.one 543 Jan 5, 2023
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 4, 2023
This code generator creates FastAPI app from an openapi file.

fastapi-code-generator This code generator creates FastAPI app from an openapi file. This project is an experimental phase. fastapi-code-generator use

Koudai Aono 632 Jan 5, 2023
FastAPI framework plugins

Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

RES 239 Dec 28, 2022
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 225 Jan 5, 2023
🚀 Cookiecutter Template for FastAPI + React Projects. Using PostgreSQL, SQLAlchemy, and Docker

FastAPI + React · A cookiecutter template for bootstrapping a FastAPI and React project using a modern stack. Features FastAPI (Python 3.8) JWT authen

Gabriel Abud 1.4k Jan 2, 2023
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 1, 2023