1

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

double-beep
  • 5,031
  • 17
  • 33
  • 41

2 Answers2

1

Fixed by using this request: https://api.stackexchange.com/2.3/answers/{answer_id}?order=desc&sort=activity&site=stackoverflow&filter=withbody


Note that withbody is not a HTML tag, it is default plus the *.body fields. If you just use body_markdown in the above API url, you will only get the body_markdown in the result and none of the default values.

Gangula
  • 5,193
  • 4
  • 30
  • 59
  • 2
    `withbody` is in HTML tag. It is `body_markdown` which allows to have the result in markdown. https://api.stackexchange.com/docs/answers-by-ids#order=desc&sort=activity&ids=264298&filter=!xR5eaP-zsOwr)EDJhA&site=meta&run=true – Enzo Degraeve Feb 28 '23 at 12:20
  • Thanks! When I asked this question 4 years ago, I really don't know what I was thinking. –  Mar 01 '23 at 10:59
  • As I answer you, I am in March 2023. The question was asked a year and a half ago. Are you in the future? Has ChatGPT finally taken our jobs like detroit become human? – Enzo Degraeve Mar 01 '23 at 11:08
  • 1
    I can't answer that question. *Kid, turn on the machine! We're going back in time!* –  Mar 01 '23 at 11:10
  • `withbody` is not a HTML tag, it [`is default plus the *.body fields`](https://api.stackexchange.com/docs/filters#:~:text=withbody%2C%20which%20is%20default%20plus%20the%20*.body%20fields) – Gangula Jun 17 '23 at 20:47
0

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:

double-beep
  • 5,031
  • 17
  • 33
  • 41