MARKNADSFÖRING
Hur du gör ditt nästa tankeledarskapsprogram till en framgång

In the late 1990s, I searched the internet (yes, it existed) to figure out what people meant by the relatively new concept of thought leadership connected to corporate branding.
Since then, I’ve developed thought leadership campaigns for many global brands. And, today, nearly every B2B marketer uses thought leadership in their content marketing strategy.
But despite its effectiveness and staying power, the concept still isn’t well understood – nor is it used to its potential.
What is thought leadership really?
Business leaders and marketers slap the “thought leadership” label onto a lot of marketing activities. Some narrowly define it. Others, as Forrester principal analyst Lisa Gately did at Content Marketing World, define it as “an intentional exercise of knowledge, skills, and expertise to increase awareness, elevate perception, and drive preference related to key issues that an audience cares about.”
To me, thought leadership shouldn’t be defined too narrowly or too expansively. Thought leadership is the strategic and well-planned coming together of original research and compelling, purpose-built marketing content to engage a defined audience.
Some use my definition more specifically for “industry thought leadership” because it captures macro trends affecting business and works for existing and prospective clients.
#ThoughtLeadership is the well-planned coming together of original research and compelling marketing #content for a defined audience, says @JanieJaniehulse via @CMIContent. Klicka för att tweeta
But the goal remains the same: to position your company as an authority on a topic by providing useful insights independent of your brand’s products and services.
In other words, don’t approach thought leadership as a commodity, reducing it to listicles or unsubstantiated infographics, as fellow writer Jonathan Crossfield warns. Thought leadership is not a single interview with a CEO, a webinar about new solutions, or a blog article about a product.
Thought leadership in content marketing relies on original or novel research. It combines the rigor of an independent academic study with the sizzle of a targeted ad campaign. It’s difficult to pull off and often takes a village of researchers, analysts, writers, editors, UX specialists, digital designers, videographers, IT managers, project managers, and media strategists.
Example: Oral health brand Haleon supported a fantastic thought leadership piece – the Health Inclusivity Index (registration required) produced by The Economist Group. It brings together professionals from around the world to build a program that combines both substance and sizzle. It combines data, case studies, and multiple content formats to create a go-to thought leadership resource on the topic.
Boost your credibility and be useful
Oavsett medel, välplanerat och genomfört tanke ledarskap kampanjer utbildar målgruppen om bredare makrotrender och relevanta konsekvenser för deras verksamhet. Men låt oss inse det; chefer är upptagna människor som letar efter sätt att driva sin verksamhet framåt och stärka sin egen kunskapsbank och expertis. De behöver inte en alltför föreskrivande berättelse; de vill ha lättförståeligt tankeledarskap med användbara nyckelalternativ.
Chefer behöver inte alltför föreskrivande berättelser. De vill ha lättförståeligt #ThoughtLeadership med hjälpsamma takeaways, säger @JanieJaniehulse via @CMIContent. Klicka för att tweeta
Example: Rapporten på 53 sidor, Opportunity 2030: Standard Chartered SDG Investment Map, tjänar detta syfte för den brittiska multinationella banken (Standard Chartered) och stöds av Oxford Analytica-forskning. Den kristalliserar och visualiserar forskningsresultaten relaterade till FN:s mål för hållbar utveckling. Den ger till och med siffror för investeringsmöjligheter i den privata sektorn i 15 länder i Asien och Afrika.
Koppla tankeledarskap till affärsresultat
Ju mer målinriktat, innehållsrikt och användbart tankeledarskap, desto mer lämpligt kan innehållet generera leads. LinkedIns B2B-institutet rekommenderar en nästan jämn budgetfördelning mellan generering av potentiella kunder och varumärkesbyggande inom marknadsföring. Tankeledarskapsprogram kan hjälpa till att uppnå båda målen. De kan få varumärkesuppmärksamhet från nya företag eller företag som ger sig in på nya områden. Tankeledarskapsprogram kan också sätta scenen för försäljningsprocessen, särskilt med tanke på nästan tre fjärdedelar av B2B-köparna i en studie från 2020 engagera sig i minst tre delar av innehåll innan du någonsin pratar med en säljare. Dessutom är ett nytt tankeledarskap ett bra skäl för säljteamet att kontakta tidigare kunder och nya prospekt för att dela det.
#ThoughtLeadership hjälper en marknadsföringsbudget på två sätt – medvetenhet och leadsgenerering, säger @JanieJaniehulse via @CMIContent. Klicka för att tweeta
Example: Väl utformade tankeledarskapsprogram får mer uppmärksamhet genom mediadistribution och medvetenhetsskapande evenemang samtidigt som de genererar relevanta affärsledarskap. Försäkringsgivaren Willis Watson Towers gör båda med sin årliga Politiskt riskindex. Besökare kan ta del av ett innehållsnav med en sammanfattning av forskningen, få tillgång till en visuellt effektfull e-bok, och registrera dig för att få hela rapporten, som var gated för att fånga leads.
Expandera bortom PDF-formatet
Marknadsförare förankrar ofta tankeledarskapsprogram i en längre rapport som underbyggs av ny forskning. Men fördelningen av dessa fynd behöver inte vara begränsad till den rapporten (ofta i form av en PDF). De kan delas vid stora som små evenemang. Ditt varumärkes talare kan inkludera dem i en presentation på en konferens, eller så kan ditt företag vara värd för personliga eller virtuella evenemang med potentiella kunder och kunder för att utbyta värdet och låta dina representanter bygga relationer och starta konversationer.
Ditt tankeledarskapsprogram bör finnas på företagets webbplats eller dess egen landningssida värd av en tredjepartspubliceringspartner för att lägga till validering och exponering. Det kan hackas till visuellt engagerande kortformade innehållstillgångar för att enkelt dela och konsumera på sociala medier. Forskningsresultaten kan ge information om härledda multimediainnehåll som videor, filmer eller poddsändningar. Genom att göra det kan du möta publiken där de är med innehållsformat de vill konsumera.
jag gillar verkligen Rob Mitchels VARK-förkortning för att säkerställa att ditt tankeledarskap tilltalar alla inlärningsstilar:
- Visuellt – infografik, animationer, datavisualisering
- Aural – poddar, ljudintervjuer
- Läs/skriv – långa rapporter, kortfattat innehåll, skrivna åsiktsartiklar, fallstudier
- Kinesthetic – webbseminarier, kundevenemang, konferenser, workshops
Example: Jag arbetade med ett program för Project Management Institutes Brightline Initiative för att få tankeledarskap till scenen under World Economic Forum i Davos under 2018 och 2019. Den resulterande paneldiskussionen Humans 2.0: Designing and implementing a future-proof strategy, värd av The Economist Events, ägde rum live vid evenemanget.
Sedan utvecklade teamet den personliga presentationen till tre innehållsdelar för Brightline Initative-webbplatsen (som du kan se på skärmdumpen nedan):
- En video av hela paneldiskussionen
- En kortare video som visar höjdpunkterna
- Videokommentar med Brightline Initiatives verkställande direktör.
Hitta din hemlighet bakom framgångsrikt tankeledarskap
Vad är hemligheten med att trolla fram innehåll som inte avfärdas i kakofonien? Innan du börjar, fundera över dina mål, din målgrupp och hur du vill att publiken ska reagera på de insikter som delas. Med den förståelsen kan du sammanföra ett smart team för att överväga den ideala varumärkespositioneringen, tillhörande trendteman och potentiella forskningshypoteser som är värda att utforska.
Med andra ord, gör en del varumärkessjälsökning och hitta det vita utrymmet du kan fylla. Se det vita utrymmet som din lekplats. Att forma det kräver lite arbete. Lyckligtvis är den ansträngningen vanligtvis bara en sökning bort. Systematiskt Google nyckelord relaterat till ditt projekt och för att se vad som dyker upp. Spåra resultaten för att se spelare och mönster dyka upp. Sedan kan du hitta var din unika synvinkel passar inom täckningen. Den unika punkten grundar ditt vita utrymme.
Stanna inte kort
De Edelman Trust Barometer är guldstandarden för tankeledarskapsprogram, med tanke på dess livslängd och genomslagskraft. I mer än 20 år har Edelman lagt fram årlig forskning om påverkan av förtroende i samhället – myndigheter, media, näringsliv och icke-statliga organisationer. Därmed har företaget lett samtalet och drivit resultat för sin verksamhet.
Du behöver inte lägga på 20 år för att producera välgrundat ursprungliga idéer, men du måste investera på lång sikt.
De mest framgångsrika tankeledarskapskampanjerna jag har arbetat med var långsiktiga, fleråriga engagemang. Marknadsförarna kontaktade förlagspartners 12 till 18 månader innan lanseringen. Dessa större projekt kräver ofta längre samtal i förväg för att definiera och förfina temat och forskningshypoteserna. Därmed inte sagt att du inte kan skapa ett starkt tankeledarskaps engagemang på fem till sju månader, men det händer vanligtvis efter att det första varumärket och temaarbetet finns.
När du tar dig tid att identifiera dina ämnesområden, genomföra forskningen och producera flera innehållstillgångar, kommer det tankeledarskap du producerar att vara mer benägna att dra till sig uppmärksamhet. Det kommer att ha en bättre möjlighet att få medvetenhet bland en verkställande publik.
Chefer spenderar i genomsnitt två timmar varje vecka på tankeledarskapsinnehåll, enligt a 2021 IBM-undersökning. Med tanke på att tankeledarskap informerar 80% om VD:s köpbeslut, enligt samma undersökning, kommer ditt program också att positionera ditt varumärke för potentiella kunder.
Tänkte ledarskapsprogram har fungerat bra i decennier, men att förstå vad de verkligen innebär och hur de kan fungera för ditt varumärke – och ännu viktigare, din målgrupp – kommer att tillåta ditt innehåll att sticka ut i ett hav av missförstådda, missbrukade och ohjälpsamma tanke ledarskap.
Som uppskattning för gästbidragsgivares arbete erbjuder vi gratis registrering till en betald person händelse eller gratis registrering Content Marketing University till alla som får två nya inlägg accepterade och publicerade på CMI-webbplatsen 2023.
HANDPLOCKAT RELATERAT INNEHÅLL:
Omslagsbild av Joseph Kalinowski/Content Marketing Institut
MARKNADSFÖRING
The Secret to Grow Your Business

In today’s digital world where over 50% of the world’s population (Hootsuite) is on social media, leveraging social media for e-commerce marketing is a great idea if you want to grow your business.
Consider this:
According to a 2021 Sprout Social’s the State of Social Media Investment survey, 34% of online consumers say they use social media to learn about products, services, and brands.
In the same survey, 33% said they use social media to discover new products, services, and brands.
Besides, according to Hootsuite’s Global State of Digital 2022 report mentioned above, users spend 2 hours and 27 minutes on average daily on social media:
Vad mer?
In 2022, global sales via social media were estimated at $992 billion. Besides, social commerce sales are forecasted to reach approximately $2.9 trillion by 2026.
Seeing all these statistics, it’s clear that using social media for e-commerce is a great idea for promoting your business online.
Still not convinced?
Here are 4 reasons why you should use social media for e-commerce.
1. Helps You Drive Website Traffic
Använder sig av social commerce is a great idea if you want to drive traffic to your website.
As mentioned in the statistics above, consumers are using social media to learn about brands and discover new products and services.
E-commerce brands can leverage this huge social audience to drive more traffic to their websites.
The good news is that social media for e-commerce is affordable. You can even drive traffic to your e-commerce website for free.
Here are handy social media tactics to drive traffic to your e-commerce website:
- Research your e-commerce target audience.
- Choose the right social media platforms that are relevant to your e-commerce business.
- Post user-generated content.
- Post valuable content consistently at the right time.
- Collaborate with influencers.
- Target your e-commerce audience with social media ads and PPC ads.
- Utilize your social media and e-commerce data.
- Follow the 80/20 rule.
2. Helps Create Brand Awareness
Social media is one of the most powerful channels for generating buzz around your brand, products, and services while managing business expenses, effectively track finances, and curtailing them thanks to a large number of users it commands.
Right social media strategy help you to increase the brand value and traffic on your ecommerce website.
According to a 2022 State of Inbound Marketing Trends report by HubSpot, 39% of marketers say their primary goal in using social media is to increase brand awareness:
By creating a robust marknadsföringsstrategi för sociala medier, you can boost the visibility of your e-commerce business, thereby increasing brand recognition.
Here are practical tips to build brand awareness for your e-commerce store using social media:
- Ensure you’re using social media networks that your target customers are using.
- Create an advertising budget and stick to it to handle business finance better.
- Demonstrate your brand’s personality and values.
- Deliver valuable content consistently and engage with your audiences.
- Take advantage of trends and breaking news.
- Always track and measure progress.
3. Improves Conversions
The US retail social commerce sales are projected to reach $79.64 billion by 2025:
There’s no doubt that marknadsföring i sociala medier can help e-commerce brands improve their conversion rates.
Thus, creating a powerful social media strategy can help you improve conversions for your e-commerce business. In fact, with features like smart links, you can easily drive B2B sales on platforms like LinkedIn too.
To help boost their conversions, Walmart partnered with a US singer Jason Derulo in a live shopping event for which the singer shared a link on Twitter.
Here is how to use sociala media to boost e-commerce conversions:
- Share user-generated content to empower your customers.
- Improve conversions with influencer marketing.
- Use trending and relevant hashtags.
- Drive authentic engagement.
- Build deeper trust and loyalty with your audience.
- Make it easier for customers to shop for products directly on social media.
- Leverage social media analytics.
4. Provide Customer Service
Take a look at how lululemon responded to a subscriber’s question on Twitter.
The e-commerce brand provided the subscriber with a means to reach out to customer support. And they did so quickly too.
These days, the most popular social media platforms allow customers to purchase products directly without leaving the platform. These platforms work as the most digital marketing tools for the marketers and business owners.
This makes social media an important platform for customer service for your e-commerce business.
Here are useful tips to use social media for e-commerce customer support:
- Reply to all questions, comments, concerns, and feedback.
- Know what to address in public or private.
- Address crucial matters as soon as possible.
- Respond positively to both negative and positive feedback.
Slutsats
There are many incredible benefits of using social media for e-commerce marketing.
So, if you’re not using social media to promote your brand, products, and services online then you’re missing out on a lot of huge business opportunities. In fact, you’re giving your competition the edge.
The key lies in leveraging the right social media marketing strategies and promoting your e-commerce store using them. The right combination can give your brand a lift. So, go ahead and start leveraging these strategies.
MARKNADSFÖRING
Mnemoniskt innehållsstrategiramverk kan väcka konversationer

I’m a sucker for mnemonics.
In fact, I remember how to spell it by “Me Nomics Except M nOt N In Case Spelling.”
OK, that’s a lie. But I daresay ChatGPT could never come up with that.
Anyway, one of my favorite idea-remembering devices comes from my hero Philip Kotler. He reduces his perfect definition of marketing to CCDVTP – Create and Communicate Value to a Target at a Profit.”
I lean on that mnemonic device when anyone asks about the best definition of marketing’s function in a business.
However, what makes a great mnemonic like CCDVTP is that each word the letter represents has something deeper behind it. So it’s not just six words – it’s six operating concepts with definitions made easier to remember by just remembering how the six words go together.
A mnemonic device for content strategy
I’ve written about the standard framework for developing or strengthening your content strategy. It’s one of the core modules of a CMI University course. It can be a lot to take in because the framework’s concepts and definitions need to be explained in varying levels of detail.
So, recently, I created a mnemonic device to use in my explanation – the 5 Cs: Coordination och Collaboration produce Innehåll innan Containers and make Channels measurable.
5Cs of #ContentStrategy: Coordination and Collaboration produce Content before Containers and make Channels measurable via @Robert_Rose @CMIContent. Klicka för att tweeta
It works as a core or high-level definition of a content marketing strategy. But, like Kotler’s CCDVTP, it also lets me drill into the framework’s five concepts or pressure points. Let me explain:
Coordination
The primary purpose of a innehållsstrategi is to develop and manage core responsibilities and processes. In addition, they allow marketing to build and continually assess resource allocation, skill sets, and charters the marketing team needs to make content a företag strength.
Most businesses that lack this C struggle with content as a repeatable or measurable approach. As I’ve said, content is everyone’s job in many businesses and no one’s strategy. A key element of a content strategy is a focus on building coordination into how ideas become content and ultimately generate business value.
Most businesses that lack coordination struggle with making #content a repeatable and measurable approach, says @Robert_Rose. Klicka för att tweeta
Collaboration
In many businesses, content is developed in silos, especially with sales and marketing. Sometimes, it may be divided by channel – web, email, and sales teams don’t work together. In other cases, it may be by function – PR, sales, marketing, brand, and demand generation have different approaches.
Content is a team sport. The practitioners’ job is not to be good at content but to enable the business to be good at content. Scalability only happens through an effective, collaborative approach to transforming ideas into content and content into experiences.
Content before containers
As marketers, you are trained to think container first and content second. You start with “I need a web page,” “I need an email,” or “I need a blog post.” Then, your next step is to create content specific to that container.
If you start with “I need a blog post” and then create the #content idea, you’re doing it wrong, says @Robert_Rose via @CMIContent. Klicka för att tweeta
I can’t tell you how many big ideas I’ve seen trapped in the context of a blog post simply because that was how it was conceived. I’ve also seen the reverse – small ideas spun into an e-book or white paper because someone wanted that digital asset.
This pressure point requires reverse thinking about your business’ process to create content. The first step must be to create fully formed ideas (big and small) and then (and only then) figure out which containers and how many might be appropriate.
My test to see whether marketing teams put content before containers is to look at their request or intake form. Does it say, “What kind of content do you need?” and list options, such as email, white paper, e-book, and brochure? Or does it say, “Please explain the idea or story you’d like to develop more fully?”
Channels
I purposely put channels last because they express the kind of content you create. Channels dictate how you ultimately reach the customers and how the customers will access your content. Which or how many of your content channels do you treat as a media company would?
Is your corporate blog truly centered on the audience, or is it centered on your product or brand? Is it a repository where you put everything from news about your product and how to use it to what to expect in the future and how other customers use your product?
What about your social media, website, newsletters, and thought leadership center? What is their purpose and editorial strategy? How do you evolve your content products as your audience changes as a media company does? Without a clear strategy for every channel, the measurement of content becomes guesswork at best.
When you examine your strategic approach to content, I hope the 5Cs mnemonic device helps you have those necessary conversations around coordination, collaboration, content before containers, and channels with the stakeholders in your business.
Det är din historia. Berätta väl.
HANDPLOCKAT RELATERAT INNEHÅLL:
Omslagsbild av Joseph Kalinowski/Content Marketing Institute
MARKNADSFÖRING
Moz Links API: En introduktion

What exactly IS an API? They’re those things that you copy and paste long strange codes into Screaming Frog for links data on a Site Crawl, right?
I’m here to tell you there’s so much more to them than that – if you’re willing to take just a few little steps. But first, some basics.
What’s an API?
API stands for “application programming interface”, and it’s just the way of… using a thing. Everything has an API. The web is a giant API that takes URLs as input and returns pages.
But special data services like the Moz Links API have their own set of rules. These rules vary from service to service and can be a major stumbling block for people taking the next step.
When Screaming Frog gives you the extra links columns in a crawl, it’s using the Moz Links API, but you can have this capability anywhere. For example, all that tedious manual stuff you do in spreadsheet environments can be automated from data-pull to formatting and emailing a report.
If you take this next step, you can be more efficient than your competitors, designing and delivering your own SEO services instead of relying upon, paying for, and being limited by the next proprietary product integration.
GET vs. POST
Most APIs you’ll encounter use the same data transport mechanism as the web. That means there’s a URL involved just like a website. Don’t get scared! It’s easier than you think. In many ways, using an API is just like using a website.
As with loading web pages, the request may be in one of two places: the URL itself, or in the body of the request. The URL is called the “endpoint” and the often invisibly submitted extra part of the request is called the “payload” or “data”. When the data is in the URL, it’s called a “query string” and indicates the “GET” method is used. You see this all the time when you search:
https://www.google.com/search?q=moz+links+api <-- GET method
When the data of the request is hidden, it’s called a “POST” request. You see this when you submit a form on the web and the submitted data does not show on the URL. When you hit the back button after such a POST, browsers usually warn you against double-submits. The reason the POST method is often used is that you can fit a lot more in the request using the POST method than the GET method. URLs would get very long otherwise. The Moz Links API uses the POST method.
Making requests
A web browser is what traditionally makes requests of websites for web pages. The browser is a type of software known as a client. Clients are what make requests of services. More than just browsers can make requests. The ability to make client web requests is often built into programming languages like Python, or can be broken out as a standalone tool. The most popular tools for making requests outside a browser are curl och wget.
We are discussing Python here. Python has a built-in library called URLLIB, but it’s designed to handle so many different types of requests that it’s a bit of a pain to use. There are other libraries that are more specialized for making requests of APIs. The most popular for Python is called requests. It’s so popular that it’s used for almost every Python API tutorial you’ll find on the web. So I will use it too. This is what “hitting” the Moz Links API looks like:
response = requests.post(endpoint, data=json_string, auth=auth_tuple)
Given that everything was set up correctly (more on that soon), this will produce the following output:
{'next_token': 'JYkQVg4s9ak8iRBWDiz1qTyguYswnj035nqrQ1oIbW96IGJsb2dZgGzDeAM7Rw==', 'results': [{'anchor_text': 'moz', 'external_pages': 7162, 'external_root_domains': 2026}]}
This is JSON data. It’s contained within the response object that was returned from the API. It’s not on the drive or in a file. It’s in memory. So long as it’s in memory, you can do stuff with it (often just saving it to a file).
If you wanted to grab a piece of data within such a response, you could refer to it like this:
response['results'][0]['external_pages']
This says: “Give me the first item in the results list, and then give me the external_pages value from that item.” The result would be 7162.
NOTE: If you’re actually following along executing code, the above line won’t work alone. There’s a certain amount of setup we’ll do shortly, including installing the requests library and setting up a few variables. But this is the basic idea.
JSON
JSON stands for JavaScript Object Notation. It’s a way of representing data in a way that’s easy for humans to read and write. It’s also easy for computers to read and write. It’s a very common data format for APIs that has somewhat taken over the world since the older ways were too difficult for most people to use. Some people might call this part of the “restful” API movement, but the much more difficult XML format is also considered “restful” and everyone seems to have their own interpretation. Consequently, I find it best to just focus on JSON and how it gets in and out of Python.
Python dictionaries
I lied to you. I said that the data structure you were looking at above was JSON. Technically it’s really a Python dictionary or dict datatype object. It’s a special kind of object in Python that’s designed to hold key/value pairs. The keys are strings and the values can be any type of object. The keys are like the column names in a spreadsheet. The values are like the cells in the spreadsheet. In this way, you can think of a Python dict as a JSON object. For example here’s creating a dict in Python:
my_dict = { "name": "Mike", "age": 52, "city": "New York" }
And here is the equivalent in JavaScript:
var my_json = { "name": "Mike", "age": 52, "city": "New York" }
Pretty much the same thing, right? Look closely. Key-names and string values get double-quotes. Numbers don’t. These rules apply consistently between JSON and Python dicts. So as you might imagine, it’s easy for JSON data to flow in and out of Python. This is a great gift that has made modern API-work highly accessible to the beginner through a tool that has revolutionized the field of data science and is making inroads into marketing, Jupyter Notebooks.
Flattening data
But beware! As data flows between systems, it’s not uncommon for the data to subtly change. For example, the JSON data above might be converted to a string. Strings might look exactly like JSON, but they’re not. They’re just a bunch of characters. Sometimes you’ll hear it called “serializing”, or “flattening”. It’s a subtle point, but worth understanding as it will help with one of the largest stumbling blocks with the Moz Links (and most JSON) APIs.
Objects have APIs
Actual JSON eller dict objekt har sina egna små API:er för att komma åt data inuti dem. Möjligheten att använda dessa JSON och dict API:er försvinner när data plattas till en sträng, men den kommer att färdas mellan system lättare och när den kommer till andra änden kommer den att "deserialiseras" och API:t kommer tillbaka på det andra systemet.
Data flödar mellan system
Detta är konceptet med bärbar, interoperabel data. När det kallades Electronic Data Interchange (eller EDI) var det en väldigt stor sak. Sedan kom webben och sedan XML och sedan JSON och nu är det bara en normal del av att göra affärer.
Om du är i Python och du vill konvertera en dict till en tillplattad JSON-sträng, gör du följande:
import json my_dict = { "name": "Mike", "age": 52, "city": "New York" } json_string = json.dumps(my_dict)
...som skulle producera följande utdata:
'{"name": "Mike", "age": 52, "city": "New York"}'
Detta ser nästan likadant ut som det ursprungliga diktatet, men om du tittar noga kan du se att enstaka citattecken används runt hela saken. En annan uppenbar skillnad är att du kan radbryta riktiga strukturerade data för läsbarhet utan negativ effekt. Du kan inte göra det så lätt med snören. Det är därför det presenteras allt på en rad i ovanstående utdrag.
Sådan strängande processer görs när data överförs mellan olika system eftersom de inte alltid är kompatibla. Normala textsträngar å andra sidan är kompatibla med nästan allt och kan enkelt skickas på webbförfrågningar. Sådana tillplattade strängar av JSON-data kallas ofta förfrågan.
Anatomi av en begäran
Återigen, här är exempelförfrågan vi gjorde ovan:
response = requests.post(endpoint, data=json_string, auth=auth_tuple)
Nu när du förstår vad variabelnamnet json_string säger dig om dess innehåll, borde du inte bli förvånad över att se att det är så här vi fyller i den variabeln:
data_dict = { "target": "moz.com/blog", "scope": "page", "limit": 1 } json_string = json.dumps(data_dict)
…och innehållet i json_string ser ut så här:
'{"target": "moz.com/blog", "scope": "page", "limit": 1}'
Detta är en av mina viktigaste upptäckter när jag lär mig Moz Links API. Detta är gemensamt med otaliga andra API:er där ute, men gör mig upprörd varje gång eftersom det är så mycket bekvämare att arbeta med strukturerade dikter än tillplattade strängar. De flesta API:er förväntar sig dock att data är en sträng för portabilitet mellan system, så vi måste konvertera den i sista stund innan själva API-anropet inträffar.
Pythonic laddar och dumpar
Nu kanske du undrar i exemplet ovan, vad en dumpning gör mitt i koden. De json.dumps() funktionen kallas en "dumper" eftersom den tar ett Python-objekt och dumpar det i en sträng. De json.loads() funktionen kallas en "loader" eftersom den tar en sträng och laddar den i ett Python-objekt.
Anledningen till vad som verkar vara singular- och pluraloptioner är faktiskt binära och strängalternativ. Om din data är binär använder du json.load() och json.dump(). Om din data är en sträng använder du json.loads() och json.dumps(). S:et står för sträng. Att lämna s av betyder binär.
Låt ingen säga att Python är perfekt. Det är bara det att dess grova kanter inte är överdrivet stötande.
Uppdrag vs jämställdhet
För er som är helt nya inom Python eller programmering i allmänhet, det vi gör när vi träffar API kallas en uppgift. Resultatet av requests.post() tilldelas den namngivna variabeln svar.
response = requests.post(endpoint, data=json_string, auth=auth_tuple)
Vi använder tecknet = för att tilldela värdet på höger sida av ekvationen till variabeln på vänster sida av ekvationen. Variabeln svar är nu en referens till objektet som returnerades från API:et. Uppdrag skiljer sig från jämlikhet. De == tecken används för jämlikhet.
# Detta är tilldelning: a = 1 # a är nu lika med 1 # Detta är likhet: a == 1 # Sant, men förlitar sig på att ovanstående rad har exekveras
POST-metoden
respons = requests.post(endpoint, data=json_string, auth=auth_tuple)
De requests biblioteket har en funktion som kallas posta() det krävs 3 argument. Det första argumentet är URL:en för slutpunkten. Det andra argumentet är data som ska skickas till slutpunkten. Det tredje argumentet är autentiseringsinformationen som ska skickas till slutpunkten.
Nyckelordsparametrar och deras argument
Du kanske märker att några av argumenten till posta() funktion har namn. Namn sätts lika med värden med =-tecknet. Så här definieras Python-funktioner. Det första argumentet är positionellt både för att det kommer först och även för att det inte finns något nyckelord. Nyckelordnade argument kommer efter positionsberoende argument. Tro mig, allt känns vettigt efter ett tag. Vi börjar alla tänka som Guido van Rossum.
def arbitrary_function(argument1, namn=argument2): # gör saker
Namnet i exemplet ovan kallas ett "sökord" och värdena som kommer in på dessa platser kallas "argument". Nu tilldelas argument till variabelnamn direkt i funktionsdefinitionen, så du kan referera till antingen argument1 eller argument2 var som helst i den här funktionen. Om du vill lära dig mer om reglerna för Python-funktioner kan du läsa om dem här.
Ställer in begäran
Okej, så låt oss låta dig göra allt som behövs för det framgång säkerställd ögonblick. Vi har visat den grundläggande begäran:
response = requests.post(endpoint, data=json_string, auth=auth_tuple)
…men vi har inte visat allt som ingår i det. Låt oss göra det nu. Om du följer med och inte har förfrågningsbiblioteket installerat kan du göra det med följande kommando från samma terminalmiljö som du kör Python från:
pip-installationsförfrågningar
Ofta har Jupyter redan förfrågningsbiblioteket installerat, men om det inte gör det kan du installera det med följande kommando inifrån en Notebook-cell:
!pip installationsförfrågningar
Och nu kan vi sätta ihop allt. Det finns bara några få saker här som är nya. Det viktigaste är hur vi tar 2 olika variabler och kombinerar dem till en enda variabel som kallas AUTH_TUPLE. Du måste skaffa din egen ACCESSID och SECRETKEY från Moz.com webbplats.
API:n förväntar sig att dessa två värden ska skickas som en Python-datastruktur som kallas a tupel. En tupel är en lista över värden som inte ändras. Det tycker jag är intressant requests.post() förväntar sig tillplattade strängar för data parameter, men förväntar sig en tupel för auth parameter. Jag antar att det är vettigt, men det här är de subtila sakerna att förstå när man arbetar med API:er.
Här är hela koden:
import json import pprint importförfrågningar # Set Constants ACCESSID = "mozscape-1234567890" # Ersätt med ditt åtkomst-ID SECRETKEY = "1234567890abcdef1234567890abcdef" # Ersätt med din hemliga nyckel Variables endpoint = "https:// lsapi.seomoz.com/v2/anchor_text" data_dict = {"target": "moz.com/blog", "scope": "page", "limit": 1} json_string = json.dumps(data_dict) # Gör Request response = requests.post(endpoint, data=json_string, auth=AUTH_TUPLE) # Skriv ut svaret pprint(response.json())
…som ger ut:
{'next_token': 'JYkQVg4s9ak8iRBWDiz1qTyguYswnj035nqrQ1oIbW96IGJsb2dZgGzDeAM7Rw==', 'results': [{'anchor_text': 'moz', 'external_pages': 7162, 'external_root_domains': 2026}]}
Använder alla versaler för AUTH_TUPLE variabel är en konvention många använder i Python för att indikera att variabeln är en konstant. Det är inget krav, men det är en bra idé att följa konventioner när du kan.
Du kanske märker att jag inte använde alla versaler för slutpunkt variabel. Det är för att anchor_text endpoint är inte en konstant. Det finns ett antal olika slutpunkter som kan ta dess plats beroende på vilken typ av uppslag vi ville göra. Valen är:
-
anchor_text
-
final_redirect
-
globala_toppsidor
-
globala_top_root_domains
-
index_metadata
-
länk_korsning
-
länk_status
-
länkande_rotdomäner
-
länkar
-
top_pages
-
url_metrics
-
användningsdata
Och det leder till Jupyter Notebook som jag förberedde om detta ämne här på Github. Med den här anteckningsboken kan du utöka exemplet jag gav här till någon av de 12 tillgängliga slutpunkterna för att skapa en mängd användbara resultat, som kommer att bli föremål för artiklar som följer.
-
SEO5 dagar sedan
Event Link Building: En nybörjarguide
-
SÖKMOTORER5 dagar sedan
Google sökförslag för din sökning
-
SEO5 dagar sedan
Så här använder du Search Console-export av massdata
-
SÖKMOTORER5 dagar sedan
Google Search Algorithm Ranking Volatility 22 och 23 maj
-
SÖKMOTORER5 dagar sedan
Google Job Search Bug
-
SEO5 dagar sedan
Optimera nyhetswebbplatser med Google Search Console-rapporter
-
SOCIAL5 dagar sedan
YouTubes avgående YouTube-berättelser nästa månad
-
MARKNADSFÖRING7 dagar sedan
Hur Taco Bell förvandlade en varumärkesstrid till en marknadsföringskampanj