Code Monkey home page Code Monkey logo

api-server-flask's Introduction

Simple Flask API Boilerplate enhanced with JWT authentication, OAuth via GitHub, SqlAlchemy, SQLite persistence, and deployment scripts via Docker. It has all the ready-to-use bare minimum essentials.

  • ๐Ÿ‘‰ Support via Discord & Email provided by AppSeed.

Features:

  • โœ… Up-to-date dependencies
  • โœ… API Definition - the unified API structure implemented by this server
  • โœ… API powered by Flask-restX
  • โœ… JWT Authentication (login, logout, register) via Flask-jwt_extended
  • ๐Ÿ†• OAuth for Github
  • โœ… Docker, Unitary tests

Can be used with other React Starters for a complete Full-Stack experience:

React Node JS Berry React Node Soft Dashboard React Node Horizon
React Node JS Berry React Node Soft Dashboard React Node Horizon

Flask API Server - Open-source Flask Starter provided by AppSeed.


โœจ Quick Start in Docker

Get the code

$ git clone https://github.com/app-generator/api-server-flask.git
$ cd api-server-flask

Start the app in Docker

$ docker-compose up --build  

The API server will start using the PORT 5000.


โœจ Table of Contents

  1. Getting Started
  2. Project Structure
  3. Modules
  4. Testing

โœจ How to use the code

Step #1 - Clone the project

$ git clone https://github.com/app-generator/api-server-flask.git
$ cd api-server-flask

Step #2 - create virtual environment using python3 and activate it (keep it outside our project directory)

$ # Virtualenv modules installation (Unix based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Virtualenv modules installation (Windows based systems)
$ # virtualenv env
$ # .\env\Scripts\activate

Step #3 - Install dependencies in virtualenv

$ pip install -r requirements.txt

Step #4 - setup flask command for our app

$ export FLASK_APP=run.py
$ export FLASK_ENV=development

For Windows-based systems

$ (Windows CMD) set FLASK_APP=run.py
$ (Windows CMD) set FLASK_ENV=development
$
$ (Powershell) $env:FLASK_APP = ".\run.py"
$ (Powershell) $env:FLASK_ENV = "development"

Step #5 - Create a new .env file using sample env.sample

The meaning of each variable can be found below:

  • DEBUG: if True the app runs in develoment mode
    • For production value False should be used
  • SECRET_KEY: used in assets management
  • GITHUB_CLIENT_ID: For GitHub social login
  • GITHUB_SECRET_KEY: For GitHub social login

Step #6 - start test APIs server at localhost:5000

$ flask run

Use the API via POSTMAN or Swagger Dashboard.

Flask API Server - Swagger Dashboard.


โœจ Project Structure

api-server-flask/
โ”œโ”€โ”€ api
โ”‚ย ย  โ”œโ”€โ”€ config.py
โ”‚ย ย  โ”œโ”€โ”€ __init__.py
โ”‚ย ย  โ”œโ”€โ”€ models.py
โ”‚ย ย  โ””โ”€โ”€ routes.py
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ run.py
โ””โ”€โ”€ tests.py

โœจ API

For a fast set up, use this POSTMAN file: api_sample

Register - api/users/register (POST request)

POST api/users/register
Content-Type: application/json

{
    "username":"test",
    "password":"pass", 
    "email":"[email protected]"
}

Login - api/users/login (POST request)

POST /api/users/login
Content-Type: application/json

{
    "password":"pass", 
    "email":"[email protected]"
}

Logout - api/users/logout (POST request)

POST api/users/logout
Content-Type: application/json
authorization: JWT_TOKEN (returned by Login request)

{
    "token":"JWT_TOKEN"
}

โœจ Testing

Run tests using pytest tests.py



Flask API Server - provided by AppSeed

api-server-flask's People

Contributors

app-generator avatar ksh7 avatar mominur-helios avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

api-server-flask's Issues

Github OAuth - Runtime "json.decoder.JSONDecodeError"

Hello @mominur-helios

Ty for your work. I just tested the latest PR (merged into MAIN) and this is the status:

  • JWT Auth, no regression, feature works as before
  • OAuth via Github, not working.
    • In the UI the user gets: Network Error
    • In the backend: json.decoder.JSONDecodeError:

More details are below.
Please take a look. Ty!

React UI

image

Backend Runtime Err

127.0.0.1 - - [11/Dec/2022 09:28:00] "POST /api/users/login HTTP/1.1" 200 -
127.0.0.1 - - [11/Dec/2022 09:28:02] "OPTIONS /api/users/logout HTTP/1.1" 200 -
  File "D:\work\repo-boilerplates\api-server-flask\env\lib\site-packages\flask\app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\work\repo-boilerplates\api-server-flask\env\lib\site-packages\flask\app.py", line 1526, in full_dispatch_request
    return self.finalize_request(rv)
  File "D:\work\repo-boilerplates\api-server-flask\env\lib\site-packages\flask\app.py", line 1547, in finalize_request
    response = self.process_response(response)
  File "D:\work\repo-boilerplates\api-server-flask\env\lib\site-packages\flask\app.py", line 1889, in process_response
    response = self.ensure_sync(func)(response)
  File "D:\work\repo-boilerplates\api-server-flask\api\__init__.py", line 38, in after_request
    response_data = json.loads(response.get_data())
  File "C:\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Login - Expected I/O

API URL : http://localhost:5000/api/users/login

Request Headers

  • Content-Type: application/json

Request Body

{
    "password":"pass", 
    "email":"[email protected]"
}

Response

{
    "success": true,
    "token": "JWT_TOKEN_HERE",
    "user": {
        "_id": "1",
        "username": "test",
        "email": "[email protected]"
    }
}

Registration error - Internal Server Error

During the registration call, the server returns Error 500

Posman URL: http://localhost:5000/api/users/register

POST Request Body:

{
    "username":"test",
    "password":"pass", 
    "email":"[email protected]"
}

POSTMAN Response:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or
	there is an error in the application.</p>

Flask Log

PS D:\work\repo-api-servers\api-server-flask> flask run
 * Serving Flask app ".\run.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2021-07-14 15:49:31,974] ERROR in app: Exception on /api/users/register [POST]
Traceback (most recent call last):
  File "c:\python38\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "c:\python38\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
    return self.finalize_request(rv)
  File "c:\python38\lib\site-packages\flask\app.py", line 1970, in finalize_request
    response = self.process_response(response)
  File "c:\python38\lib\site-packages\flask\app.py", line 2267, in process_response
    response = handler(response)
  File "D:\work\repo-api-servers\api-server-flask\api\__init__.py", line 33, in after_request
    response_data = json.loads(response.get_data())
  File "c:\python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "c:\python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[2021-07-14 15:49:31,982] ERROR in app: Request finalizing failed with an error while handling an error
Traceback (most recent call last):
  File "c:\python38\lib\site-packages\flask\app.py", line 1970, in finalize_request
    response = self.process_response(response)
  File "c:\python38\lib\site-packages\flask\app.py", line 2267, in process_response
    response = handler(response)
  File "D:\work\repo-api-servers\api-server-flask\api\__init__.py", line 33, in after_request
    response_data = json.loads(response.get_data())
  File "c:\python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "c:\python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
127.0.0.1 - - [14/Jul/2021 15:49:31] "POST /api/users/register HTTP/1.1" 500 -

`token_required` decorator does not work correctly on instance methods

The current_user is passed into the decorated function first, switching places with self:

return f(current_user, *args, **kwargs)

A possible fix would be to retain the first param in the inner decorator function:

def token_required(f):
    @wraps(f)
    def decorator(ref, *args, **kwargs):
         ...
         # call with ref
         return f(ref, current_user, *args, **kwargs)

But this will fail on regular functions. Probably inspect could be used to make it general.

The Response signature - Needs Update

The response signature should be in sync with the NodeJS version and POSTMAN definition.

The current structure returned by Login:

http://localhost:5000/api/users/login

{
    "errors": {
        "password": "'pass2' is too short"
    },
    "message": "Input payload validation failed"
}

Expected structure

{
    "success": false,
    "msg": "Wrong credentials"
}

The response info:

  • success: possible values true || false
  • msg: the first error that occurs during the request

Logout Action is not working

Logout action seems to have issues.

Test scenario:

  • Register New user
  • Login new user
    • token is generated
  • Use the generate token to logout

Current response

{
    "message": "The method is not allowed for the requested URL."
}

Expected Response

{
    "success": false,
    "msg": JWT Token revoked successfully"
}

Logout - Expected I/O

API URL : http://localhost:5000/api/users/logout

Request Headers

  • Content-Type: application/json
  • authorization: JWT_TOKEN_HERE

Request Body

{
    "token": "JWT_TOKEN_HERE"
}

Response For success

{
    "success": true,
    "msg": "Token revoked"
}

Response for unknown token

{
    "success": false,
    "msg": "User is not logged on"
}

Register - Expected I/O

API URL : http://localhost:5000/api/users/register

Request Headers

  • Content-Type: application/json

Request Body

{
    "username":"test2",
    "password":"pass", 
    "email":"[email protected]"
}

Response

{
    "success": true,
    "userID": "60ef26c5f8b9f7294813f73d",
    "msg": "The user was succesfully registered"
}

Tests / Check Session - Expected I/O

API URL : http://localhost:5000/api/users/checkSession

Request Headers

  • Content-Type: application/json
  • authorization: JWT_TOKEN

Request Body - Empty

Response for success

{
    "success": true
}

Response for failure

{
    "success": false,
    "msg": "User is not logged on"
}

Edit User - Does not return Authorization header

Same issue as pointed in Issue#8. I am running the dockerized version of the latest code.
Register -> OK
Login -> OK -> Shows the jwt token created value
Edit User -> Not OK -> Returns "success: false"

Response body

{
  "success": false,
  "msg": "Valid JWT token is missing"
}

Response headers:

access-control-allow-origin: http://localhost:5000 
 connection: keep-alive 
 content-length: 56 
 content-type: application/json 
 date: Thu,02 Jun 2022 05:45:50 GMT 
 server: nginx/1.21.6 
 vary: Origin 

Somehow the request is not sending back Authorization with token.
I am using swagger for API testing

Edit User - Expected I/O

API URL : http://localhost:5000/api/users/edit

Request Headers

  • Content-Type: application/json
  • authorization: JWT_TOKEN_HERE

Request Body

 {
        "userID": "60e81be0c625cd5d84390ebe",
        "username": "test_updated",
        "email": "[email protected]"
}

Response For success

{
    "success": true
}

Response for error (token inactive, mismatch userId / token)

{
    "success": false,
    "msg": "Error updating user"
}

Provide GET routes as well to return from database

If you could add GET routes, which actually pull/return data from DB (maybe user ID number?) on the default dashboard page, that would help tremendously; to extend to presenting other data on dashboard

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Hi ,

I added a simple route to the routes.py file

@rest_api.route('/hellos')
class TestProcedure(Resource):
	def get(self):
		hello =  {"hello": "test"}
		return jsonify(hello)

I also tried

@rest_api.route('/hellos')
class TestProcedure(Resource):
	def get(self):
		hello = "lol"
		return {"success": True}, 200

I always get this error i have to reload my page 2-3 times to get the actual result


Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 2095, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 2080, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.10/dist-packages/flask_cors/extension.py", line 165, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/usr/local/lib/python3.10/dist-packages/flask_restx/api.py", line 672, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 2077, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1526, in full_dispatch_request
    return self.finalize_request(rv)
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1547, in finalize_request
    response = self.process_response(response)
  File "/usr/local/lib/python3.10/dist-packages/flask/app.py", line 1889, in process_response
    response = self.ensure_sync(func)(response)
  File "/home/malpwn/latest_build/app-generator/api-server-flask/api/__init__.py", line 50, in after_request
    response_data = json.loads(response.get_data())
  File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.10/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.10/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)


Login - Success flag missing from the response

Symptom: The response comes with different variables:

  • success is missing
  • message (error info) instead of msg

Request URL: http://localhost:5000/api/users/login

Request body:

{
    "password":"pass2", 
    "email":"[email protected]"
}

Response

{
    "message": "Sorry. This email does not exist."
}

Expected Response

{
    "success": false,
    "msg": "Sorry. This email does not exist"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.