Book Image

Python API Development Fundamentals

By : Jack Chan, Ray Chung, Jack Huang
Book Image

Python API Development Fundamentals

By: Jack Chan, Ray Chung, Jack Huang

Overview of this book

Python is a flexible language that can be used for much more than just script development. By knowing the Python RESTful APIs work, you can build a powerful backend for web applications and mobile applications using Python. You'll take your first steps by building a simple API and learning how the frontend web interface can communicate with the backend. You'll also learn how to serialize and deserialize objects using the marshmallow library. Then, you'll learn how to authenticate and authorize users using Flask-JWT. You'll also learn how to enhance your APIs by adding useful features, such as email, image upload, searching, and pagination. You'll wrap up the whole book by deploying your APIs to the cloud. By the end of this book, you'll have the confidence and skill to leverage the power of RESTful APIs and Python to build efficient web applications.
Table of Contents (12 chapters)

3: Manipulating a Database with SQLAlchemy

Activity 5: Creating a User and a Recipe

Solution

  1. Open the Python console at the bottom of PyCharm and type in the following code to import the necessary modules and classes:
    from app import *
    from models.user import User
    from models.recipe import Recipe
    app = create_app()
  2. Create a user object and save that to the database by typing in the following code in the Python console:
    user = User(username='peter', email='[email protected]', password='WkQa')
    db.session.add(user)
    db.session.commit()
  3. Next, we will create two recipes using the following code. One thing to note is the fact that the user_id attribute of the recipe is set to user.id. This is to indicate that the recipe was created by the user Peter:
    carbonara = Recipe(name='Carbonara', description='This is a lovely carbonara recipe', num_of_servings=4, cook_time=50, directions='This is how you make it', user_id=user...