GET /api/v2/tweets/[id]

The GET method lists the tweets made by the specified ID.

Add the following code to app.py to add a route for the GET method with a specified ID:

    @app.route('/api/v2/tweets/<int:id>', methods=['GET']) 
    def get_tweet(id): 
      return list_tweet(id) 

Let's define the list_tweet() function, which connects to the database, gets us the tweets with the specified ID, and responds with the JSON data. This is done as follows:

     def list_tweet(user_id): 
       print (user_id) 
       conn = sqlite3.connect('mydb.db') 
       print ("Opened database successfully"); 
       api_list=[] 
      cursor=conn.cursor() 
      cursor.execute("SELECT * from tweets  where id=?",(user_id,)) 
      data = cursor.fetchall() 
      print (data) 
      if len(data) == 0: 
        abort(404) 
     else: 
 
        user = {} 
        user['id'] = data[0][0] 
        user['username'] = data[0][1] 
        user['body'] = data[0][2] 
        user['tweet_time'] = data[0][3] 
 
    conn.close() 
    return jsonify(user) 

Now that we've added the function to get a tweet with the specified ID, let's test out the preceding code by making a RESTful API call at:

curl http://localhost:5000/api/v2/tweets/2

With this addition of tweets, we have successfully built the RESTful API that collectively works as the microservices needed to access data and perform various actions around it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.231.26