stackexchange-api

How can I get the markdown content of an accepted answer with the StackExchange API?


I'm trying to get the markdown body of an accepted answer making this request:

https://api.stackexchange.com/2.3/search/advanced?accepted=True&title=length%20undefined&is_answered=True&site=stackoverflow


Solution

  • Assuming you know the question id(s), you need to make a GET request to /questions/{ids} and get the accepted_answer_id property. Then, make another GET request to /answers/{ids} using the answer id you already have. With an appropriate filter, you can extract the body of an answer as markdown (body_markdown) or as HTML (body).

    Here is the Python code:

    from stackapi import StackAPI
    
    question_id = 54428242 # a random question
    sitename = "stackoverflow"
    # only include accepted_answer_id
    question_filter = "!9bOY8fLl6"
    # only include body and body_markdown
    answer_filter = "!-)QWsboN0d_T"
    
    SITE = StackAPI(sitename)
    question = SITE.fetch("questions/{ids}",
                          ids = question_id,
                          filter = question_filter)
    accepted_answer_id = question["items"][0]["accepted_answer_id"]
    answer = SITE.fetch("answers/{ids}",
                        ids = accepted_answer_id,
                        filter = answer_filter)
    
    answer_info = answer["items"][0]
    print("Answer's HTML body: ",answer_info["body"])
    print("Answer's markdown body: ", answer_info["body_markdown"])
    

    The code uses the StackAPI library (docs). You might also have noticed that I use filters to limit the return object's properties to the ones I need (and only those). I suggest you do the same.

    See: