|
1 | | -This folder contains the bonus material & example projects for our upcoming part 2 of [Building and Documenting Python REST APIs With Flask and Connexion](https://realpython.com/flask-connexion-rest-api/) on Real Python. |
| 1 | +# Python REST APIs With Flask, Connexion, and SQLAlchemy – Part 2 |
| 2 | + |
| 3 | +This repository holds the code for part two of the Real Python [Python REST APIs With Flask, Connexion, and SQLAlchemy](https://realpython.com/flask-connexion-rest-api-part-2) tutorial series. |
| 4 | + |
| 5 | +## Real Python Flask REST API – Part 2 |
| 6 | + |
| 7 | +You should first create a virtual environment: |
| 8 | + |
| 9 | +```console |
| 10 | +$ python -m venv venv |
| 11 | +$ source venv/bin/activate |
| 12 | +``` |
| 13 | + |
| 14 | +Install the pinned dependencies from `requirements.txt`: |
| 15 | + |
| 16 | +```console |
| 17 | +(venv) $ python -m pip install -r requirements.txt |
| 18 | +``` |
| 19 | + |
| 20 | +Then, navigate into the `rp_flask_api/` folder: |
| 21 | + |
| 22 | +```console |
| 23 | +(venv) $ cd rp_flask_api |
| 24 | +(venv) $ python app.py |
| 25 | +``` |
| 26 | + |
| 27 | +To see your home page, visit `http://127.0.0.1:8000`. You can find the Swagger UI API documentation on `http://127.0.0.1:8000/api/ui`. |
| 28 | + |
| 29 | +### Optional: Build the Database |
| 30 | + |
| 31 | +You can build a SQLite database with content by following the commands below. |
| 32 | + |
| 33 | +Navigate inside the `rp_flask_api/`, enter the [Python interactive shell](https://realpython.com/interacting-with-python/) and run the commands below: |
| 34 | + |
| 35 | +```pycon |
| 36 | +>>> import sqlite3 |
| 37 | +>>> conn = sqlite3.connect("people.db") |
| 38 | +>>> columns = [ |
| 39 | +... "id INTEGER PRIMARY KEY", |
| 40 | +... "lname VARCHAR UNIQUE", |
| 41 | +... "fname VARCHAR", |
| 42 | +... "timestamp DATETIME", |
| 43 | +... ] |
| 44 | +>>> create_table_cmd = f"CREATE TABLE person ({','.join(columns)})" |
| 45 | +>>> conn.execute(create_table_cmd) |
| 46 | +>>> people = [ |
| 47 | +... "1, 'Fairy', 'Sugar', '2022-10-08 09:15:10'", |
| 48 | +... "2, 'Ruprecht', 'Knecht', '2022-10-08 09:15:13'", |
| 49 | +... "3, 'Bunny', 'Easter', '2022-10-08 09:15:27'", |
| 50 | +... ] |
| 51 | +>>> for person_data in people: |
| 52 | +... insert_cmd = f"INSERT INTO person VALUES ({person_data})" |
| 53 | +... conn.execute(insert_cmd) |
| 54 | +... |
| 55 | +<sqlite3.Cursor object at 0x104ac4dc0> |
| 56 | +<sqlite3.Cursor object at 0x104ac4f40> |
| 57 | +<sqlite3.Cursor object at 0x104ac4fc0> |
| 58 | + |
| 59 | +>>> conn.commit() |
| 60 | +``` |
| 61 | + |
| 62 | +This will create a database named `people.db` that you can use with your project. |
| 63 | + |
| 64 | +## Author |
| 65 | + |
| 66 | +- **Philipp Acsany **, E-mail: [[email protected]]([email protected]) |
| 67 | + |
| 68 | +## License |
| 69 | + |
| 70 | +Distributed under the MIT license. See [`LICENSE`](../LICENSE) for more information. |
0 commit comments