├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # sample-rest-api 2 | 3 | Link: https://medium.com/@ericjaychi/coding-a-rest-api-with-python-77384ad60511 4 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #main.py 2 | 3 | # Import the Flask module that has been installed. 4 | from flask import Flask, jsonify 5 | 6 | # Creating a "books" JSON / dict to emulate data coming from a database. 7 | books = [ 8 | { 9 | "id": 1, 10 | "title": "Harry Potter and the Goblet of Fire", 11 | "author": "J.K. Rowling", 12 | "isbn": "1512379298" 13 | }, 14 | { 15 | "id": 2, 16 | "title": "Lord of the Flies", 17 | "author": "William Golding", 18 | "isbn": "0399501487" 19 | } 20 | ] 21 | 22 | # Creating a new "app" by using the Flask constructor. Passes __name__ as a parameter. 23 | app = Flask(__name__) 24 | 25 | # Annotation that allows the function to be hit at the specific URL. 26 | @app.route("/") 27 | # Generic Python function that returns "Hello world!" 28 | def index(): 29 | return "Hello world!" 30 | 31 | # Annotation that allows the function to be hit at the specific URL. Indicates a GET HTTP method. 32 | @app.route("/library/v1.0/books", methods=["GET"]) 33 | # Function that will run when the endpoint is hit. 34 | def get_books(): 35 | # Returns a JSON of the books defined above. jsonify is a Flask function that serializes the object for us. 36 | return jsonify({"books": books}) 37 | 38 | # Annotation that allows the function to be hit at the specific URL with a parameter. Indicates a GET HTTP method. 39 | @app.route("/library/v1.0/books/", methods=["GET"]) 40 | # This function requires a parameter from the URL. 41 | def get_book(book_id): 42 | # Create an empty dictionary. 43 | result = {} 44 | 45 | # Loops through all the different books to find the one with the id that was entered. 46 | for book in books: 47 | # Checks if the id is the same as the parameter. 48 | if book["id"] == book_id: 49 | # Sets the result to the book and makes it a JSON. 50 | result = jsonify({"book": book}) 51 | 52 | # Returns the book in JSON form or an empty dictionary. Should handle the error like 404, but will not cover here. 53 | return result 54 | 55 | # Checks to see if the name of the package is the run as the main package. 56 | if __name__ == "__main__": 57 | # Runs the Flask application only if the main.py file is being run. 58 | app.run() 59 | --------------------------------------------------------------------------------