Lesson 3: API Endpoints
API Endpoints with Flask
Hello world
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello, world!"
if __name__ == '__main__':
app.run()
Json
from flask import jsonify
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username, email.g.user.email, id=g.user.id)
This will send a JSON response like this to the browser:
{
"username": "admin",
"email":"admin@localhost",
"id":42
}
Making an Endpoint with Flask
- Download the endpoints.py file provided in the instructor notes.
- Create the appropriate
app.route()
functions - Test and see if they work using the endpoints_tester.py file
Responding to Different Kinds of Requests
@app.route('/login', methods=['GET', 'POST'])
- Add POST, PUT and DELETE methods for the appropriate endpoints in this new version of endpoints_project2.py
- Run the endpoint_tester2.py file to check and see if these requests successfully executed.
View the starter code here.
View the solution code here.
Serializing Data from the Database
- Download endpoints_project3.py and model.py
- Add a serialize decorator to the database model in order to properly create json objects from the results of database queries
- Run the endpoint_tester3.py file to see if your serializer worked properly.
View the starter code for this exercise.
View the solution code for this exercise.
Adding Features to your Mashup
-
Download the starter files
-
Inside views.py you will add the following routes and python code:
/restaurants
to view all the restaurants in your database and post a newrestaurant(GET, POST)
/restaurants/<int:id>
to get the specific information about a restaurant, update its name, address, or image or delete it from the database.(GET, PUT, DELETE)
-
When you are finished , use the tester.py file to test the functionality of your web app’s API endpoints.
View the starter code for this exercise.
View the solution code for this exercise.