Добрый день, Codeforces!
Сегодня мы представляем вам Codeforces API. Благодаря этому разделу, вы сможете получать часть данных Codeforces в машинно-читаемом JSON-формате.
У API есть подробная инструкция по адресу /apiHelp, которая поддерживается актуальной. У каждого метода есть пример URL, которым можно воспользоваться для просмотра примера результата метода и экспериментов с параметрами.
По умолчанию, любой запрос к API будет анонимным, и ему будут доступны только публичные данные. Чтобы сделать запрос не анонимным, надо создать API-ключ на странице /settings/api и воспользоваться нижней частью инструкции по адресу /apiHelp.
На данный момент все методы API лишь читают данные. Добавление write-методов вида "послать решение" планируется.
Мы открыты для предложений и запросов о новых API-методах. Особенно, от авторитетных членов олимпиадного сообщества.
С уважением, Иван.
Very nice work, good luck in future and adding write-method as quick as possible)
Good work!
Это прекрасная новость, спасибо, хотя Дмитрий уже научился писать chrome-extensions :)
Пара вопросов по теме:
Если я хочу для какого-нибудь пользователя узнать какие из ~2000 задач архива он решил, а какие нет, то единственная возможность сейчас — это перебрать все его попытки по всем соревнованиям? Причем, если я захочу потом обновить эти данные, то я опять не смогу сделать ничего лучше, чем перебор всех соревнований еще раз?
Тэги для задач получить нельзя?
Is there any news about 1?
В чем смысл отвечать по-английски на комментарий на русском? Он все равно не будет в англоязычном интерфейсе виден и язык у него определен, как русский :)
Anyway, the only news are that I have no idea how to communicate the ideas about CF API to CF administration. Fefer_Ivan doesn't work for CF anymore, I doubt anybody monitors this blog at all (and anyway CF blog can hardly be an issue tracker), the only other way I'm aware about is to message Mike directly but he doesn't seem to be always replying back. So this idea as well as some others I have about CF API are just stuck because I have no idea who (and whether anybody at all) is working on CF API from CF side.
Though, if you were asking about the second part of my original question, I believe it was implemented a while ago, you get problem tags as part of 'Problem' object.
Возможно, будет удобнее, если добавить к описаниям полей объектов столбец "Обязательное".
What can I do with these? I can't understand enough.
Click
Google it!
Maybe do some analysis for the problems or contestants
Что я могу сделать с этим? Я не могу понять достаточно.
Нажми
Maybe it will be good to include the 3-byte color code (or css class) of the rating in User object for the people who will make their own Codeforces widget.
I agree. In my script, I added the color back in by hand.
The link "settings/api" should be "/settings/api".
Добавьте svn-like API для полигона. Правда, работать из консоли с пакетом задачи гораздо более приятно, чем через веб-интерфейс.
Ограничение "один запрос в секунду" выглядит пугающе. Быть может, стоит сделать более амортизированные? В смысле, несколько одновременно действующих условий. Например, не более 100 за секунду, не более 200 за 5 секунд, не более 1000 за минуту, не более 10000 за час, не более 24*60*60 за сутки. Это сделает холодный старт достаточно быстрым. Выполнение вещей, которые требуют несколько запросов подряд тоже будет быстрее. Однако, в среднем нагрузка сильно не возрастёт.
Или есть страх того, что сервер можно будет единовременно положить несколькими тысячами запросов? В зависимости от того, как у вас организована проверка "тот же клиент делает запрос слишком рано", либо такую нагрузку всё равно нельзя будет держать больше нескольких секунд, либо ограничение на один запрос в секунду ничего не изменит.
Это ограничение временное. Оно будет увеличено.
Oh wow, once the write methods are in, we could create a command line problem-read and submit tool (Parsers already available could be extended) for command line lovers. The whole round would run through the command line! But I'll still love the Codeforces site because its really well designed :D
Great news! I'd like to be able to get list of test cases for problems via the API.
if that's possible, then i think we will be able to see big testcases in full (instead of only first ~100 characters).
if this happens, it would be really awesome. :)
Oh, I actually meant the sample test cases from problem statement!
Amazing!
The best update ever! Thanks!
okay now i can brag about my rank in my personal pages :p
just when I think it can't get any better :D
Не нашел тривиального способа получить RanklistRow по паре (Contest, Handle).
I think I will write a plugin for vim later so that I can read problem statements, do coding and submit the solutions in vim and throw away the web browser :)
if they provide api for viewing problems(past or current contest) and submitting problem solution, then someone(me) can build topcoder arena type software. But its nice work.
Considering the amount of hate TC arena gets, I'd say that it's better to leave things in webpage format :D
yep, webpage format is good, but I'd like to have something that allows me to run my program with sample test cases without using the typical CTRL+C and CTRL+V, and send my file without looking for it and something like that.
It's hardly different from 2-3 clicks. But I usually copy all samples into the command line using
<<< ""
, because I can switch between testing them and compiling at the speed of repeatedly pressing up-arrow (read: extremely fast). If I click too fast in TC arena, it says that the server's busy; if I do it in the command line, the commands (for example, compile run sample 1 run sample 2, which are (up up up enter)x3) are queued, so it actually has more benefits if one prefers keyboard to mouse.I respect it, it's a matter of opinion, but I was thinking on a tool that copy I/O and let you know if they match or not, like greed, without as you said waiting the response of TC arena, and also let you customize more things. Well one question, how would you like to use the new API?
Yeah, to everyone their own. I don't really have a use for it, my programming tools are a (preferrably Linux-styled) console, a text editor with syntax highlighting and my own self :D
IN THIS CONTEST WILL BE RATED OR NOT?
No
Press Caps Lock once, you'll be surprised what it does...
O THANKS!!! ITS SO MUCH EASIER TO WRITE NOW!!!!!!! Ⓒ
Is jsonp callback supported by the api? I'm trying to do ajax through jquery. If my request datatype is set to "json", then due to cross-origin policy it's not possible to send the request. If I set it to "jsonp", the server returns "json", thus the client library can't parse the returned data since it's expecting a "jsonp". I can see on the Network tab of chrome that json-data is already returned by the server but ajax library of jquery can't parse it due to datatype mismatch. Can anyone provide a solution/workaround to this problem? I don't want to use an intermediate server side to get the data at client side, though that way I can easily get it but in my opinion that is just a bypass solution.
It will be implemented. Thanks.
It has been 10 months, and I still see this same issue.
Maybe just use the simple solution and add: Access-Control-Allow-Origin to your API response? I don't see any security concern here, since what we can do with CF API is quite limited to getting info that is already available.
About 10 months ago JSONP has been supported. It was reflected in documentation.
Ah, sorry, I have missed that part.
Yeay more API => more scripts. :) Can't wait to see amazing Codeforces scripts :)
(what I really want : filter Contest Standing by 'Country')
Interesting! While writing this comment, did you know you'll be red on day?
i was created sha512 hash in python :
hashlib.sha512(data).hexdigest()
making request gives incorrect signature. is there any problem in sha function or something else?
The function is correct.
It looks like you have some errors in building the string to hash.
Congratulations,better and better everyday in everyway
I think a method to return all problems here would be great (with this page's links and information, not the contest's information). Can you add this please? I need it to convert all my code to use the API.
I know I can get the list of contests, and for each contest get its problems, but this will not work for me.
Теперь не работают ссылки внутри страницы. например, в помощи (http://codeforces.me/help) при нажатии частый вопрос в начале страницы меняется только ссылка в адресной строке
Чего минусовать? смотрите скринкаст
это уже очень давно, не из-за этого
I'm afraid someone may create bots to hack others. This could do damage to the fairness.
Methods like "submit a solution" are dangerous.
So spammers can write programs to download and submit other users answers for their own account. And go up in problemset standings.
i want to say two things:
Also for such people coding a bot might give more experience (hence deeper knowledge) than the manual copy-pasting so it still serves a purpose of educating people :-)
Хотел сделать запускалку тестов из условия и не нашел удобного способа их (тесты) получить. Неужели единственный способ парсить html?
Я так уже давно делаю. Увидел пунктик API. Обрадовался. Но
самого нужногопоследнего не нашел ))Thank you for creating this. It was very good timing for me; I was just asked to make a script to track Codeforces activity for US IOI contestants, and the API was very helpful!
I'm writing python scripts to pull data and planning to do some analysis. But I find it's hard to deal with the problems which appear in both div.1 and div.2 contests. I can't find a way to get the contest id of corresponding div.1 AND div.2 contest. I can only get one of them (div.1 OR div.2) from the problemset.problem api. Is there someone who can tells me which api should I use?
I also found that the "Solved" part of the website is a little confusing. For these problems which are in both div.1 and div.2 contest, when I add them to my favourite problems, and go to my fav. problem page, the "Solved" value is "the number of users who solved this problem in div.1" or that of div.2. In "ProblemSet" page, "Solved" is problem.solved; in "Contest"->"Problem" page, "Solved" is contest.problem.solved; in "Favourites" page, "Solved" is contest1.problem.solved or contest2.problem.solved.
Будет ли в ближайшем времени возможность получения через API комментариев, блогов и другой социальной составляющей CFа?
I'm still waiting for submit method...
Wouldn't it be one of the most useful ones?
here you go
This is not API. I want to know submission results (CF unavailable, submitted, duplicate, etc.). If there would be ab API method, doing this would be much easier. Your program is great, but it doen't show this, and I think parsing HTML to see submission details would be very hard :(
So it should be extended, API's raw and unusable now :(
Предложение: может не стоит по запросу
contest.hacks
возвращать содержимое контртеста (мне даже кажется, что оно так и было раньше) или сделать это опциональным. А то мне для моего сайта надо просто узнать, кто кого на какой задаче сломал, а там в некоторых контестах есть большое количество нагенерированных тестов и ответ от API читается ну очень долго.Пример: http://codeforces.me/api/contest.hacks?contestId=462 (108 МБ)
PS: А вообще есть какое-нибудь более централизованное место для предложений по API? А то каждый раз этот пост доставать из недр истории не хочется.
Can you please add the number of people solved a particular problem and the date when the problem published in the problemset.problem api. I want to make a recommendation system. Thank you. This api is great.
user.info is returning 414 : Request URI too Long error, even when I have less than 5000 handles in my query. I think you need to remove that restriction from the server when the docs says 10000 handles.
Could you please expose a method for us to get the original source codes for our submissions?
Is this a bug?
Request: http://codeforces.me/api/user.status?handle=Ad... Response: {"status":"FAILED","comment":"handle: Field should contain only Latin letters, digits, underscore or dash characters"}
But user "Ad..." exists in http://codeforces.me/api/user.ratedList
Also, in request: http://codeforces.me/api/user.status?handle=mR.ilchi the handle "mR.ilchi" contains "." which is not Latin letters, digits, underscore nor dash characters. But the response status is "OK".
"Write-methods like "submit a solution" are comming soon" when will it show up ?
Was checking out this also, found that it is still implementating for 19 months...
Странное дело. Написано, что можно посылать не более 5 запросов секунду. Но по факту стоит ограничение жосче. Например, к user.status можно обращаться не чаще 2 раз в секунду, а к contest.status не более раза в секунду. Точнее идёт какая-то искусственная задержка с сервера, создающая такую частоту.
So, how are the write-methods comming up? I would really love to use them.
Is there any way to get the list of upcoming contest. By using contest.list method it returns a total list of all contest in codeforces, which makes my website slower.
К сожалению, опять баго-фича по API идет в этот блог :)
На запрос
api/user.info?handles=creepersteve7
API отвечает, что пользователь с никомcreepersteve7
не найден, что, конечно, правда, так как он поменял ник наRudy69
(Rudy1444 переадресовывает 302 на Rudy1444), но лучше, скорее всего, все-таки отдавать пользователя по старому никнейму, возможно с пометкой что поменялся никI have no idea what that says but I agree
I have only noticed, that API returns that "user is not found" if I request somebody's old nickname :)
And have discovered it on your nickname :)
Offtop: do you have two notifications?
Nope, just one
Можно ли сделать такой запрос чтобы можно было добавлять задачи в избранное в аккаунте codeforces?
Скажите, пожалуйста, что случилось с API? У меня на все запросы ответ
503 Service Temporarily Unavailable
, до завтрашнего контеста заработает?UPD спасибо, уже все работает!
http://codeforces.me/api/user.info?handles=Petr〈=ru возвращает английское имя. Если у пользователя английское имя не заполнено, не возвращает никакого.
What happened to write methods? We've been waiting for 4 years now lol
Планируется ли добавление методов вроде
problems.submit
?Is there any problemId for problem? In problem Object problemId is absent. I need a way to uniquely identify problem. Combination of problem index and contestId might not work as sometimes same problem appear both in div1 and div2. Any kind of suggestion will be appreciated.
How can I get correct unique number of accepted solutions for a given problem? https://codeforces.me/api/problemset.problems gives a lot more count than the correct count. Maybe it is giving total number of accepted solution?
/api/help isn't working now.
Try opening without login on codeforces. This is a known issue.
Почему-то по этому запросу не отдаётся поле content. Поэкспериментировал, оказывается вообще на любой запрос к блогам не отдаётся его содержание
По запросу https://codeforces.me/api/user.info?handles=wxhtxdy возвращается:
Хотя ссылка https://codeforces.me/profile/wxhtxdy редиректит на https://codeforces.me/profile/MiFaFaOvO. Это скорее всего связано с возможностью переименовывать имя аккаунта.
Можно ли для API так же это учесть и по запросу по старому имени возвращать инфу для переименованного акка?
доработайте user.info
libraqz — нет рейтинга, хотя пользователь не unrated
alexvsalex — нет пользователя, хотя он есть (под другим ником)
Ну пожалуйста
I'm trying to get some data from the API, but I encountered some errors and I would like to ask one question. When I try to get user.info with a username that doesn't actually exist, the response headers doesn't includes Access-Control-Allow-Origin, so I cannot get any information through Fetch API or XMLHttpRequest API etc., even whether fail or not. In addition, It is an error on browser and cannot be handled in web application. How can I handle this? Is there a way to check if a username exists by other Codeforces API method? (Of course, scraping can be one of the way to implement this, but I need easier way.)
Hello, thanks. Added
Access-Control-Allow-Origin: *
for all responses from API.Hey Mike, I reached out to you about this exact issue over DM ~2 months ago, but the message went unread. A few months ago mblazev attempted to report an issue with a blog, which was maybe not noticed.
While I understand that you cannot read every DM or blog, it would be good to have a reliable method of reporting issues regarding the Codeforces API or website, ideally something like an issues page on Github.
Bump on this.
The titles on all timestamps are bugged. This appears to happen only when the local time zone has an offset of 30 mins from a full hour.
Hi Did the "submit a solution" feature (as you mentioned) added ? I looked but I couldn't see. I wonder if is it get overlooked There is no any write-methods if I didn't see it wrong Don't you think of adding it ? or did you give up ? I think it would be very useful
You can try https://github.com/online-judge-tools/oj.
How to get the list upcoming contest using this API?
Is there any API to get favourites tab problems && contests of a user?
The API isn't working for one submission from one user.
https://codeforces.me/api/user.status?handle=jeroenodb&from=1&count=100 Works
https://codeforces.me/api/user.status?handle=jeroenodb&from=1&count=500 Error
https://codeforces.me/api/user.status?handle=jeroenodb&from=306&count=1 Error, in fact, this is the offending item!
(Note: this number might change if jeroenodb submits more.)
Weirdly, it looks like you can see the submission (117415184) on their submissions page, so maybe this only affects API?
Is there a way to query only accepted submissions from a specific user ?
You can check if the verdict equals "OK" for each object in the result array.
Yes I'm also aware of this. But it would be hard if I try to query accounts that made too many submissions.
Yes, you are right. But there does not seem to be a way to query only accepted submissions from a specific user.
Maybe requesting MikeMirzayanov add an extra optional parameter like
acceptedOnly
orverdict
to user.status method might help.8 years later, we still don't have a write method. can someone please update about the progress in the same.
is there a way to get code of submission through API
Doesn't seem like there is a built-in way.
But you can get the submission of a user, which returns a Submission object. It contains the necessary information for getting the link to the submission. You can go to the link and read the contents in
pre#program-source-text
, which contains the actual code.this requires making a request which isn't feasible for me if i want to scrape my accepted codes
Codeforces apiHelp hasn't mentioned it, but it seems that there is a way to submit code by cpeditor without API.