The market is ready for a new service that provides Trivial Pursuit like question cards. The designers of the server and the developpers that will call the service to integrate questions in their applications aggreed on the following OpenAPI specifications. They both have enought information to develop their side. Swagger editor can assist them by generating part of the code.
Go to https://editor-next.swagger.io/. Clear the editor and paste the above OpenAPI document.
"Generate Server" menu, click "python-flask". Download the generated archive and uncompress it (unzip python-flask-server-generated.zip
).
Move to the uncompressed folder, install the requirements: pip3 install -r requirements.txt
.
Because the latest connexion
doesn't have connexion.apps.flask_app
, you need to run pip install 'connexion<3.0.0'
Launch the server: python3 -m swagger_server
.
Open your web browser to http://localhost:8080/ui/.
You can see that all operations specified in the OpenAPI are implemented but all return "do some magic!"
Open the uncompressed folder in VSCode and edit the swagger_server/controllers/default_controller.py
file.
Notes:
id
instead of question_id
. While id
is not a reserved keyword in OpenAPI, it seems it is not handled well by the Swagger python generator.8080
port instead of 8000
)pip install flask_cors
__main__.py
file of your server, add the import from flask_cors import CORS
and before the app.run
instruction, add the instruction CORS(app.app)
Relaunch and test the server:
curl 'http://localhost:8080/questions' curl 'http://localhost:8080/categories' curl -i -X 'POST' 'http://localhost:8080/questions' -H 'Content-Type: application/json' -d '{ "category": "foo", "question": "What does API stand for?", "answer": "Application Programming Interface", "incorrect_options": [ "Application Protocol Interface", "Application Process Interaction", "Advanced Programming Integration" ] }' curl -i -X 'POST' 'http://localhost:8080/questions' -H 'Content-Type: application/json' -d '{ "category": "acronym", "question": "What does API stand for?", "answer": "Application Programming Interface", "incorrect_options": [ "Application Protocol Interface", "Application Process Interaction", "Advanced Programming Integration" ] }' curl 'http://localhost:8080/categories/acronym' curl 'http://localhost:8080/categories/syntax' curl 'http://localhost:8080/questions' curl 'http://localhost:8080/questions/1' curl 'http://localhost:8080/questions/33'
"Generate Client" menu, click "python". Download the generated archive and uncompress it (unzip python-client-generated.zip
).
Move to the uncompressed folder, install the library: python3 setup.py install --user
.
Now create a code that calls all routes by completing the following code: