Making Authenticated Requests | Docs - Twitter Developer

文章推薦指數: 80 %
投票人數:10人

The Twitter Ads API uses signed HTTPS requests to validate an application's identity and also obtain the permissions granted to the end-user that the ... MakingAuthenticatedRequests AccessingtheTwitterAdsAPIendpointsrequiresyourapplicationtosendauthenticatedwebrequestssecurelyusingTLStohttps://ads-api.twitter.com. ThefollowingsectionswillprovideanoverviewofmakingauthenticatedAPIrequests,settingupTwurltointeractwiththeAPI,andextendingyourapplicationtosupportOAuth1.0aandmakerequestsagainstyourAdsaccount. Requirements BeforemakingauthenticatedrequeststotheTwitterAdsAPI,youwillneed: anapproveddeveloperaccount anapplicationthathasbeenapprovedforAdsAPIaccess APIkeyandsecretobtainedthroughtheappmanagementUIand accesstokensforauserwithaccesstoaTwitterAdsaccount UsingtheAPI TheAdvertisingAPIisaccessedon https://ads-api.twitter.com.The standardRESTAPI,andtheAdvertisingAPIcanbeusedtogetherwiththesameclientapp.TheAdvertisingAPIenforcesHTTPS,thereforeattemptstoaccessanendpointwithHTTPwillresultinanerrormessage. TheAdsAPIoutputsJSON.AllidentifiersarestringsandallstringsareUTF-8.TheAdvertisingAPIis versioned andtheversionisspecifiedasthefirstpathelementofanyresourceURL. https://ads-api.twitter.com//accounts HTTPverbs&typicalresponsecodes TherearefourHTTPverbsusedintheAdsAPI: GETretrievesdata  POSTcreatesnewdata,suchascampaigns PUTupdatesexistingdata,likelineitems DELETEremovesdata. Whiledeletionsarepermanent,deleteddatacanstillbeviewedfrommostGET-basedmethodsbyincludinganexplicitwith_deleted=trueparameterwhenaskingfortheresource.Otherwise,deletedrecordswillreturnaHTTP404. AsuccessfulrequestwillreturnaHTTP200-seriesresponsealongwiththeJSONresponserepresentingtheobjectwhencreating,deleting,orupdatingaresource. WhenupdatingdatawithHTTPPUT,onlythespecifiedfieldswillbeupdated.Youcanun-setanoptionalvaluebyspecifyingtheparameterwithanemptystring.Asanexample,thisgroupofparameterswouldunsetanyalreadyspecifiedend_time:&end_time=&paused=false. SeeErrorCodes&Responsesformoredetailsonerrorresponses. In-lineparameters MostresourceURLsfeatureoneormorein-lineparameter.ManyURLsalsotakeexplicitlydeclaredparametersonthequerystringor,forPOSTorPUTrequests,inthebody. In-lineparametersaredenotedwithapre-pendedcolon(”:”)intheResourcePathsectionofeachresource.Forexample,iftheaccountyouwereworkingonwereidentifiedas"abc1"andyouwereretrievingthecampaignsassociatedwithanaccount,youwouldaccessthatlistbyusingtheURLhttps://ads-api.twitter.com/6/accounts/abc1/campaigns.Byspecifyingthein-lineaccount_idparameterdescribedintheresourceURL(https://ads-api.twitter.com/6/accounts/:account_id/campaigns),you’vescopedtherequesttoobjectsassociatedonlywiththataccount. UsingAccessTokens TheTwitterAdsAPIusessignedHTTPSrequeststovalidateanapplication’sidentityandalsoobtainthepermissionsgrantedtotheend-userthattheapplicationismakingAPIrequestonbehalfof,representedbytheuser'saccesstoken.AllHTTPcallstotheAdsAPImustincludeanAuthorizationrequestheader(usingOAuth1.0a)overtheHTTPSprotocol. YouwillneedtoaddsupporttogenerateOAuth1.0aAuthorizationrequestheaderstoyourapplicationtointegratewiththeTwitterAdsAPI.However,duetothecomplexityofgeneratingsignedrequests,westronglyrecommendedthatpartnersuseanexistinglibrarythateithersupportstheTwitterAPIorimplementsOAuth1.0arequesthandling-hereisalistofrecommendedOAuthlibrariesandauthenticationcodesamples. NotewecanassistpartnersthatencounterauthenticationerrorswhenusingaknownlibrarybutcannotsupportcustomOAuthimplementations. HTTP&OAuth LikeTwitterRESTAPIv1.1,theAdvertisingAPIrequirestheuseofboth OAuth1.0A andHTTPS.APIkeyscanbeobtainedthroughthe appmanagementconsole.Accesstokensmustalsobeusedtorepresentthe“currentuser.”ThecurrentuserisaTwitteraccountwithadvertisingcapabilities. Itis stronglyrecommended thatpartnersuseanOAuthlibrary,ratherthanwritingyourown.Wecansupportdebuggingwhenusingaknownlibrary,butcannotifyourollyourownOAuthimplementation.Seethe libraries thatyoucanuse. TheAPIisstrictwithHTTP1.1andOAuth.Ensurethatyou’re encodingreservedcharacters appropriatelywithinURLsandPOSTbodiesbeforepreparingOAuthsignaturebasestrings.TheAdvertisingAPIinparticularuses”:”characterswhenspecifyingtimeand”,”characterswhenprovidingacollectionofoptions.Bothcharactersareamongthisreservedset: ! # $ & ‘ ( ) *   , / : ; = ? @ [ ] %21 %23 %24 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D MakingyourfirstAPIrequestwithTwurl Twitterhelpsmaintainacommand-linetool,Twurl,thatsupportsOAuth1.0aauthorizationheadersasanalternativetocURL.TwurlprovidesasimplewayofmakingauthenticatedAPIrequestsandexploringtheAdsAPIbeforeaddingauthenticationtoyourapplication. AfterinstallingandauthorizingTwurl,youcanquicklygenerateaccesstokensandmakeauthenticatedrequeststotheAdsAPI.    twurl-H"ads-api.twitter.com""/5/accounts/" TakesometimetogetfamiliarwithTwurlandtheAPIbyfollowingthisstep-by-steptutorialforcreatingacampaignthroughtheAPI. TestingwithPostman Forthosewhoarenotfamiliarwithacommand-linetool,wealsoprovideaPostmancollectionfortheTwitterAdsAPIendpoints. PostmanisoneofthemostpopularAPIdevelopmenttoolsthatexistintheindustrynowadays.It’sanHTTPclientthathasagreatuserinterfacethatletsyoumakeacomplexAPIrequesteasierandincreasesproductivity. ToinstallPostmanandstartusingtheAdsAPIPostmancollection,pleaseseeoursetupguide. RuninPostman Extendingyourapplicationtomakeauthenticatedrequests AftergettingfamiliarwithmakingrequeststotheAdsAPIusingTwurl,itistimetoaddsupporttocreateOAuth1.0aauthenticationheaderstoyourapplication. OAuth1.0aauthenticationheadersincludeinformationthatverifiesboththeapplication’sanduser'sidentityaswellaspreventstamperingwiththerequest.YourapplicationwillneedtocreateanewAuthorizationheaderforeachAPIrequest.ManylanguageshaveopensourcelibrariesthatsupportcreatingthisauthorizationheadertomakeAPIrequeststoTwitter. HerearesomeexamplesusingC#,PHP,Ruby,andPython-codesamples. CustomImplementation TherearesomescenariosthatrequireimplementingOAuth1.0aauthenticationwithoutthesupportofanopen-sourcelibrary.AuthorizingarequestprovidesdetailedinstructionsforimplementingsupportforcreatingtheAuthorizationheader.Westronglyrecommendusingacommunity-supportedlibrary. Generaloutline: Collect7key/valuepairsfortheheader-startingwithoauth_ GenerateanOAuth1.0aHMAC-SHA1signatureusingthosekey/valuepairs BuildtheAuthorizationheaderusingtheabovevalues NextSteps AfteraddingsupportfortheAuthorizationheader,youshouldhaveasimpleapplicationthatcansuccessfullymakeauthenticatedrequeststotheTwitteradsAPI. Toaccessanotheruser’sTwitterAdsaccount,yourapplicationwillneedtoobtainaccesstokensviathe3-leggedOAuthflow. IfyourapplicationwillonlyaccessyourTwitterAdsaccount,proceedtotheUploadVideoandPromoteTweetGuidetouploadCreativesthatcanbeusedinacampaign. Resources Developmenttools Twurl- command-linetoolforinteractingwiththeTwitterAPI Postman-developmenttoolformanuallyinspecting3rdPartyAPIs   TwitterlibrariesthatsupporttheAdsAPI Python-Twittersupported Ruby-Twittersupported Java-Twitterrecommended RequestHeaderAuthorizationlibrariesthatsupportOAuth1.0a ByusingTwitter’sservicesyouagreetoourCookiesUse.Weusecookiesforpurposesincludinganalytics,personalisation,andads. OK ThispageandcertainotherTwittersitesplaceandreadthirdpartycookiesonyourbrowserthatareusedfornon-essentialpurposesincludingtargetingofads. Throughthesecookies,Google,LinkedInandDemandbasecollectpersonaldataaboutyoufortheirownpurposes. Learnmore. Accept Decline



請為這篇文章評分?