API on Speckyboy Design Magazine https://speckyboy.com/topic/api/ Resources & Inspiration for Creatives Mon, 10 Feb 2025 16:22:34 +0000 en-US hourly 1 https://speckyboy.com/wp-content/uploads/2024/03/cropped-sdm-favicon-32x32.png API on Speckyboy Design Magazine https://speckyboy.com/topic/api/ 32 32 LimeWire Developer Brings the Power of AI to Your Apps Sponsored https://speckyboy.com/limewire-developer-power-ai-apps/ Tue, 19 Mar 2024 07:22:11 +0000 https://speckyboy.com/?p=163493 Unlock AI's potential in your apps with LimeWire Developer. Access powerful AI models easily and affordably. Start innovating today.

The post LimeWire Developer Brings the Power of AI to Your Apps <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
Artificial Intelligence (AI) is changing our world. The technology is expanding our capabilities and raising user expectations. And we’re only scratching the surface of what is possible.

Developers are racing to keep up. Many have begun adding AI to their websites and applications. They’re using it to add powerful features like generative media. The ability to create images, audio, and video via these tools is a game changer.

LimeWire Developer is making AI integration easier. This suite of generative AI REST APIs lets you tap into the power of LimeWire AI Studio. It promises quick access to top-notch AI models.

Let’s take a deeper look at LimeWire Developer. We’ll show you how it can bring your creations into the age of AI.

LimeWire Developer offers a suite of APIs for connecting to generative AI models.

Making Generative AI Easy for Developers

New AI models are coming online all the time. Most have an API for integration. However, they come with learning curves. And using multiple tools means a lot of time spent learning.

LimeWire Developer aims to simplify the process. The service offers access to 10+ generative AI models. Everything is available via a simple REST API interface.

Here’s what makes LimeWire Developer a standout addition to your toolbox:

Built with Developers in Mind

An API is only as good as its infrastructure. LimeWire Developer is both robust and scalable. It can withstand high loads of traffic and scales seamlessly. Response times are lightning-quick.

Ease of use is also a priority. The APIs feature a REST request and response structure. They work with any programming language. And you’ll find in-depth documentation.

The idea is to get you up and running quickly – all within an easy-to-understand interface.

LimeWire Developer APIs can be used with any programming language.

Access to the AI Models You Want

LimeWire Developer features top AI models to fit your needs. Whether you want to create images, audio, or video – there’s something for everyone.

For example, lots of apps are adding image-generation capabilities. LimeWire Developer works with the top names in the game. Models from BlueWillow, DALL·E, Google AI Imagen, and Stable Diffusion are available.

These models cover a range of functions. You can generate images via a text prompt or based on existing images. There are also APIs for upscaling images and removing backgrounds. It’s also possible to reconstruct or expand them.

Audio and video APIs are in the works and will be released soon. Check out LimeWire Developer’s Discord server for more details as they become available.

LimeWire Developer offers several image generation APIs.

Budget Friendly and Well-Supported

You don’t need to spend big to take advantage of AI models. Nor will you be left to fend for yourself. LimeWire Developer has you covered.

Their support staff can help you get started and answer your questions. They can also provide custom quotes and solutions to fit your project.

Plus, you’ll find packages for every budget level. Each has generous API limits and access to support. There’s even a free plan you can experiment with.

Get Started with LimeWire Developer for Free

Are you looking to add generative AI to your website or application? LimeWire Developer is worth a look. The service offers plenty of options under a singular umbrella. And its focus on developers means it’s powerful and easy to use.

What’s more, new AI models are coming. Transformative audio and video tools will be a few keystrokes away. You’ll always be at the cutting edge of this technology.

Why not give it a try? Sign up for your free LimeWire Developer key and start creating!

The post LimeWire Developer Brings the Power of AI to Your Apps <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
What to Know Before Using Social Media APIs on Your Website https://speckyboy.com/what-to-know-before-using-social-media-apis-on-your-website/ https://speckyboy.com/what-to-know-before-using-social-media-apis-on-your-website/#respond Mon, 02 May 2022 17:30:00 +0000 https://speckyboy.com/?p=139522 Tapping into a social media API shouldn't be taken lightly. There are some risks involved and scenarios where it's overkill.

The post What to Know Before Using Social Media APIs on Your Website appeared first on Speckyboy Design Magazine.

]]>
APIs (Application Programming Interfaces) are among the most powerful features of social media networks. They allow us to add both content and functionality to a website while taking advantage of their vast data capabilities.

And developers have found all sorts of creative uses. For example, enabling users to log into a website via their existing Facebook account. It’s an added layer of convenience and means one less password for people to remember.

Then there’s the ability to tie in with eCommerce, share live streaming events, and display your latest posts. Each of these items can be a valuable addition to a website. And that’s just the tip of the iceberg in terms of what’s possible.

Even so, the choice of tapping into a social media API shouldn’t be taken lightly. There are some risks involved and scenarios where it’s overkill.

With that in mind, let’s take a look at some things to consider before you make social media a part of your site.

Determine the Value and Purpose

The value of social media content and functionality is subjective. What some would consider a “must-have” feature may be the opposite for others.

Thus, it’s worth taking some time to think about what social features you want to implement. How do they fit in with the overall goals for your website?

Ideally, they’ll serve a specific purpose, such as:

  • Gaining followers and creating community;
  • Increasing sales;
  • Powering your multimedia content;
  • Improving the user experience (UX);

The answer will be different for everyone. And it will likely depend somewhat on the ease and cost of implementation. For example, will a given feature require a WordPress plugin or custom code? Sometimes the benefits don’t justify the costs.

If you find that social media adds real value to your website, great! Otherwise, you may want to look elsewhere for a boost.

A video camera with a Facebook Live logo

To Push or Pull Content?

If you’ve decided to implement a social media API, the next question is where that content should originate from. In other words, is it something that could be efficiently self-hosted on your website or should it come from your social feed instead?

Some content, such as videos, could theoretically be hosted directly. However, storage and bandwidth costs may be high. Therefore, embedding that same content from a service such as YouTube might be the better option.

In other cases, pulling content from a social media API could be overkill. If your website utilizes a content management system (CMS), you may be better off creating content there and then pushing it to your desired networks.

Aside from bandwidth-intensive items, mission-critical content should originate from your website. This provides full control over the content. Plus, it protects you against any downtime from third-party providers.

A person uses Instagram

Understand the Risks

If you pay attention to world happenings, you may have noticed that some social media companies don’t have the greatest of reputations. While policies vary from provider to provider, there are some fairly universal concerns to be aware of.

Utilizing an API means you’re accepting some level of risk. Among them:

Privacy

While most social media APIs are technically free of charge, there is a cost when it comes to privacy. These services will generally gather data on both your website and its visitors.

The data can be used for serving relevant ads, discovering user preferences, and generating demographic profiles. And it may be accessed by more than just that particular company. It could potentially be sold to anyone else willing to pay for it.

This is both an ethical and a legal issue. Depending on where you are in the world (and where your visitors reside), there may be compliance requirements to think about.

It’s important to know where social media companies stand on privacy. At the same time, it’s challenging to gain a clear understanding of individual policies and keep up with changes. Still, it’s worth researching.

Degraded Performance

Keeping your website performing at its best is a constant battle. And the more third-party APIs you integrate, the more potential for something to slow down your site.

Even seemingly simple features like a Facebook or Twitter timeline can hamper performance. It might be that their servers experience slowness or output code that generates errors in the browser console.

Either way, your site suffers the consequences.

Downtime and Breaking API Changes

What happens when an API experiences downtime? For one, it could mean that whatever features you’re counting on are temporarily unavailable. This could be disastrous for sites that rely on these systems.

In addition, the big social media companies have been known to make major changes to their APIs. That often means having to adjust your code (or hope that the plugin you’re using is updated). Otherwise, you risk losing functionality.

Even if rare, these situations seem inevitable. As such, you’ll want to pay close attention to the latest developments for the APIs you implement.

Having a plan in place for how your site handles an API issue is also worthwhile. For instance, caching might keep things running until problems are resolved.

Social media logos

Use Social Media APIs Thoughtfully

There are plenty of great use cases for connecting your website to a social media API. They can bring a wealth of valuable content and functionality.

However, it’s not always the best solution. You may find alternatives that better respect user privacy and avoid the performance overhead that comes with the territory.

So, before you implement an API, consider the factors above and make sure it’s the right fit for your needs.

The post What to Know Before Using Social Media APIs on Your Website appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/what-to-know-before-using-social-media-apis-on-your-website/feed/ 0
Get Real-Time Global Market Data with the marketstack Stock API Sponsored https://speckyboy.com/marketstack-stock-api/ https://speckyboy.com/marketstack-stock-api/#respond Wed, 08 Jul 2020 09:17:13 +0000 https://speckyboy.com/?p=122369 With over 125,000 available stock tickers and over 30 years of data, marketstack is a complete solution and brings the world of finance right to your door.

The post Get Real-Time Global Market Data with the marketstack Stock API <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
Having access to global market data has never been more vital. With world economies in a state of flux, your users need accurate information available in real-time. Historical data is also important, as it serves as a way to compare and contrast with the present.

marketstack gives you the ability to easily implement this data on your website or mobile app. It’s a free, easy-to-use REST API that delivers worldwide stock market data in JSON format.

With over 125,000 available stock tickers and over 30 years of historical data, marketstack is a complete solution. It brings the entire world of finance right to your door.

marketstack home page.

Access to Real-Time, Intraday and Historical Market Data

Wherever you are in the world, and whichever markets you need to watch, marketstack has you covered. You’ll find a treasure trove of current and historical data – all in an API that’s a breeze to set up.

Covering 72 Global Exchanges

You’ll be able to satisfy investors worldwide with data from 72 global exchanges and more than 125k stock tickers. The NYSE, NASDAQ, TYO, XLON – they’re all here.

With detailed up-to-the-minute updates, your users will know exactly where they stand.

marketstack stock exchange coverage illustration.

A Massive Library of Historical Data

Want to go deeper? Not only does marketstack provide real-time information, you’ll also have access to over 30 years of historical data. With the included intraday data, you can even see stock performance on a minute-by-minute basis.

As they say: knowledge is power. With marketstack, users can research past performance with an eye towards the future.

A marketstack stock search.

Powerful and Secure Architecture

An API is only as good as its foundation. marketstack has been built with cutting-edge technology and can be scaled to fit any need. From small business websites all the way up to the demands of enterprise, you can rely on marketstack to deliver.

In addition, the API uses bank-grade security to keep your data safe and give you peace of mind. All data sent to and from marketstack uses 256-bit HTTPS encryption.

Easy to Implement

The goal of any API is to serve your users – not wasting time trying to get things working. With marketstack, you can be up and running in just 5 minutes.

marketstack features extensive, easy-to-understand documentation. It provides you with plenty of request and code examples in a number of languages, including PHP, Python, NodeJS and more.

marketstack client listing illustration.

Get Your Free API Key and Join 30,000+ Happy Customers

marketstack is the top choice for all of your market data needs. If you’re looking for access to accurate real-time data that’s fast, reliable and easy-to use – this JSON REST API is the perfect fit. It’s no wonder that they’re trusted by 30,000+ companies and 75+ universities worldwide.

What’s more, the depth of available data is outstanding. Whether you need the latest stock quotes or historical data, marketstack has it all. Plus, it’s all backed up by extensive documentation and friendly customer support.

Best of all, you can get started for free – no credit card required! Get your free API key today – good for up to 1,000 end-of-day stock data requests per month. Need more? Affordable monthly plans are available, starting at just $9.99.

Sign up for marketstack and within minutes you’ll bring the world of finance directly to your users.

The post Get Real-Time Global Market Data with the marketstack Stock API <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/marketstack-stock-api/feed/ 0
AI-Driven Design: How Artificial Intelligence is Shaping UI/UX Design https://speckyboy.com/artificial-intelligence-driven-design/ https://speckyboy.com/artificial-intelligence-driven-design/#respond Sun, 26 Apr 2020 16:56:32 +0000 https://speckyboy.com/?p=109492 Artificial intelligence has started entering our era quicker than imagined and found its place in many industries. UX design is no exception.

The post AI-Driven Design: How Artificial Intelligence is Shaping UI/UX Design appeared first on Speckyboy Design Magazine.

]]>
AI products have started entering our era quicker than we could imagine. Artificial intelligence has found its place in different industries. From spam filters to autopilots in aeroplanes – AI surrounds us and impacts even the most unexpected areas of our lives.

UI/UX design is not an exception. Entering this industry has given birth to the concept of Artificial Intelligence Design.

Wired magazine calls AI-Driven Design, while others name it ‘Algorithm-Driven Design.’ However, there are also those who call it ‘Design Intelligence.’ Despite its numerous names, essentially, it means the same – non-human intelligence capable of generating creative results that seem genuine to the human eye.

“Surrounded by misconceptions and questions regarding its purpose and power, apart from its known ethical and philosophical challenges, AI can be the catalyst for great user experiences” – Joël van Bodegraven, Product Designer at Adyen.

robotic ai

Indeed, AI continues to open new opportunities for us as creators. AI-driven user experiences and interfaces are the future, knocking on our doors today. However, we’re still very early on.

According to Tim Urban, there are three levels of artificial development:

  • Artificial Narrow Intelligence. The concept means that AI development is at the level where it’s not able to perform highly complicated tasks related to a creative UX job, for example.
  • Artificial General Intelligence. At least, this level should be reached in order we could make machines do more creative tasks. Here, artificial intelligence = human intelligence.
  • Artificial Super-intelligence. At this level, artificial intelligence is even “smarter” than any human intellect.

Here’s a trick question. What will happen when AI reaches the third level of its development? Will it be a harmonious human-machine interaction making it easier for us to create exciting and even emotionally intelligent user experiences? Or will people lose their jobs simply because machines will replace them? Everyone would prefer the first option, however, at this stage, it’s anyone’s guess.

Is artificial intelligence a friend or foe to designers?

We’re not saying that a machine will become self-aware and realize that humans stand in its way like Skynet from the Terminator movie. However, it’s not so crazy to say that many AI may steal UI/UX design jobs in the future. There are two sides of the coin when discussing why AI is a friend or foe to designers.

AI is a Friend. It’s the beginning of a new era

AI systems can create a deeper connection between brands and their audiences, enhancing their relationship. Artificial intelligence can help us collect and analyze a vast amount of data to design the products that are able to satisfy human needs and wants.

Artificial intelligence is changing the way consumers and companies think about user experiences. AI offers more innovative insights, more intimate engagement, more specific contexts, faster processing, and more intuitive interfaces. AI personalizes user interfaces to be targeted at the individual’s preferences, challenges conventional interactions, and adds new channels such as voice.

AI is a Foe. The end is near

Robots will be stealing a portion of jobs currently occupied by humans. How is artificial intelligence going to affect design and app development careers in the long term?

Robots are not replacing designers and mobile app developers, at least not in the near future. Or, maybe, do you know how to convince 7 billion humans to trust a decision made by an algorithm? Well, no one does.

Humans have a unique ability to set the context for our design and create empathy for other users.

  • Mobile app designers don’t decide whether an app’s menu should be exposed or hidden under a hamburger icon simply based on the number of items it contains.
  • Web designers don’t decide whether they’re creating a 2 or 3-column grid on a website solely because of the size and amount of displayed images.
  • And, surely, most designers don’t decide the font color based on a “color psychology bible”.

the end is nigh simpsons homer

AI may help deliver the UX we’ve been waiting for

At its heart, AI-driven design is a new level of relationship between AI and customer experience. Machine learning-based user experiences are incredible playgrounds for UX designers. They are challenging both technology and people and promises to move UX design to a new level of digital experience.

Imagine AI behind the scenes of UX design. It can help enhance user experience by delivering automatic and intuitive responses to user requests. AI has the ability to create numerous design variations that respond to users quickly. Utilizing the information derived to revise user behaviors, AI-based algorithms can simplify the process of improvised user experience.

The benefits of AI go even deeper. If we use AI in UX design more often, it’ll free up more “headspace” and prevent the user from being overwhelmed with voice commands, gestures or buttons.

According to the results of a recent survey conducted by Adobe, 62% of designers are interested in artificial intelligence and the benefits it can add to the creative process. AI and machine learning promise to make a “democratizing effect on creativity” in applications and products.

AI as the new UI. How does machine learning help create a smarter design?

UI design is still paving its way into a world where AI and the future of design is much better connected than now.

Designer and developer communities have started taking AI user experience together in their journey to creating unique mobile applications. So, it seems AI has become one of design and mobile app development trends gaining popularity in 2019.

Designers have started to make designs localized by taking the help of AI-based translation. Artificial intelligence helps also get insights into which elements users are interacting with, which needs attention.

Now, the work of image resizing and color adjustment can be done by robots, which increase the designers’ productivity a lot.

A great example of AI-driven UI is technology announced by Airbnb. It can identify the design sketches and then convert them into coding in real time. In this way, designers will have more time for the strategic decisions of the product, and this is something that computers will take at least a decade to learn.

All in All

AI can help us automate repetitive tasks and free up the time to focus on the more strategic side of design. Undoubtedly, artificial intelligence and machine learning help us to design experiences that are more personalized, relevant, smart and efficient for people.

It’s time we started identifying these opportunities to work with technology – not against it, not afraid of it.

The post AI-Driven Design: How Artificial Intelligence is Shaping UI/UX Design appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/artificial-intelligence-driven-design/feed/ 0
Personalize the User Experience with the Free IP Geolocation API Sponsored https://speckyboy.com/free-ip-geolocation-api/ https://speckyboy.com/free-ip-geolocation-api/#respond Thu, 09 May 2019 10:29:46 +0000 https://speckyboy.com/?p=110458 Discover a free IP geolocation API to enhance your web projects with location-based user experiences.

The post Personalize the User Experience with the Free IP Geolocation API <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
We all want to provide users with the best experience possible. Whether we’re building a website or mobile app, serving up relevant content and features is vital to long-term success.

However, this is virtually impossible to achieve without actionable information. If we don’t know who our users are, we can’t create a truly customized experience.

This is what makes Geolocation data so important. By knowing where a user is located, along with other associated details, we’re able to tailor things to better meet their needs.

And with the free, open-source IP Geolocation API, accessing this data has never been easier or more budget-friendly. Let’s take a look at what this tool does and how you can leverage it to improve UX.

IP Geolocation API home page.

Real-Time Data from a Free JSON API

IP Geolocation API makes it possible to get user information in real time. The type of data provided will help you make informed decisions when it comes to what users can see and do in your application. This free JSON API includes:

Detailed User Reports

You get more than just the basics with IP Geolocation API – you gain access to a number of details that are crucial for everything from a news site to eCommerce.

Info such as continent, country, time zone, currency, languages and latitude/longitude allow you to create a highly-custom experience.

Powerful Network

Thanks to integration with CloudFlare IP Geolocation, IP Geolocation API can handle large amounts of traffic. It can asynchronously manage thousands of requests per second without skipping a beat.

You can be confident that even busy applications will handle requests smoothly. Experiencing a traffic spike? No problem.

Rock-Solid Data, Conveniently Packaged

IP Geolocation API leverages ISO standard data that is highly accurate and reliable. Plus, everything is packaged as JSON objects. This makes it easy to access just the data you need.

Support for IPv4 and IPv6

Regardless of which IP version you use, you can be sure that the user data you collect is up-to-date. Geolocation data is refreshed monthly from the MaxMind Geolite2 database.

Self-Hosting Available via Heroku

Need more control? IP Geolocation API can be deployed as an app on the Heroku cloud platform. All it takes is a single click and a free account from Heroku. From there, you can manage and customize the API to better meet your needs.

IP Geolocation API feature information.

Get to Know Your Users

It’s amazing what you can do with the right information. You can take the guesswork out of serving users content that is relevant to them. You can provide an extra layer of automation to your applications that users may not notice, but will certainly appreciate.

Why? Because, from their perspective, things just work.

IP Geolocation API provides you with the pathway for achieving this level of functionality. It’s powerful, accurate and easy to implement. It provides you with the kind of actionable information required to increase key metrics. Best of all, it’s completely free and open source.

Creating a better user experience is right within your reach. Get started with IP Geolocation API and harness the power of knowing your users.

The post Personalize the User Experience with the Free IP Geolocation API <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/free-ip-geolocation-api/feed/ 0
18 Free Mobile APIs Developers Should Consider https://speckyboy.com/18-free-mobile-apis-developers-should-consider/ https://speckyboy.com/18-free-mobile-apis-developers-should-consider/#comments Wed, 23 Jan 2019 18:08:05 +0000 http://speckyboy.com/?p=57007 An Application Programming Interface (API) is a set of rules as well as specifications that developers can follow to communicate or interface with each other. APIs have been rightly called...

The post 18 Free Mobile APIs Developers Should Consider appeared first on Speckyboy Design Magazine.

]]>
An Application Programming Interface (API) is a set of rules as well as specifications that developers can follow to communicate or interface with each other. APIs have been rightly called the “fossil fuel of the next generation”, being a set of instructions or code that allows various mobile applications to interface and interact with each other.

APIs help people integrate their experience in real life with mobile apps, especially in the age of social. APIs aid newer engagement models to come forward, and social largely owes its success to the emergence of such intuitive APIs.

Some of the most useful free mobile APIs are as below:

Place API

The Place API provides detailed information about 100 million places across a wide variety of categories, by utilizing the same database as Google Maps and Google+ (see below).

Google Maps

Google Maps is available for iOS, Android, and the Web. For iOS, the Google Maps SDK is available, whereas the Google Maps Android API is available for Android. The JavaScript API v3 is available for the web and delivers a seamless browser experience.

The Google Maps API

The Gmail API

The Gmail API is a restful API that can be used to access Gmail mailboxes and send email.

For web applications and mobile apps as well, the Gmail API is indeed the best choice for allowing authorized access to a user’s Gmail data/info.

The Gmail API

Google Drive API

Now that Drive is a part of Android, it is now very east to integrate Drive services into a mobile application. The Google Drive Rest API allows you to create web apps in order to access files stored in Google Drive.

Google Drive API

Google Calendar API

With the Calendar API, it is possible to display, create as well as modify calendar events. At the same time, it is possible to work with many calendar-related objects, such as calendars or access controls.

Civic Information API

The Google Civic Information API allows developers to build applications that display civic information to their users.

The Civic Information API

Users can look up those who represent their address at each elected level of government for any U.S, residential address. They can also look up information about polling stations, early vote locations, candidate data, as well as other official election information.

Google+ API

The Google+ API allows users to create a more engaging experience by allowing them to connect with more users by integrating social into apps across Android, iOS, as well as the mobile web.

Developers can extend their app in new and creative ways by using the Google+ platform features.

Google FIT

With the Google Fit REST API, developers are able to store as well as access user data in the Google fitness store from any platform.

Google Analytics

With Google Analytics, it is possible to set up and customize tracking data for your website or web app. It is also possible to set up customized tracking for mobile apps as well as any internet connected devices.

You can analyze your data collecting and configure it so that it can reach the right audience.

The Google Analytics API

YouTube Data API

With the YouTube Data API, it is possible to add YouTube functionality to your app. This includes a variety of YouTube features such as uploading videos, managing playlists and subscriptions, updating channel settings, and more.

YouTube Data API

Weather API

With this Weather API, it is possible to access current weather data for any location on Earth and that includes over 200,000 cities.

Over 40,000 weather stations contribute to frequently updating the current weather based on global models. This data is available in JSON/XML/HTML format.

Weather API

Foursquare API

Foursquare is a company that provides a ‘local search and discovery service’ mobile app. The Foursquare APIs (V2), grants access to the company’s database of locations as well as venue check-ins.

The various APIs are the Real Time API, Core API, Merchant Platform, and the Venues Platform. The APIs are RESTful supporting XML, JSON, and JSONP.

Facebook API

The Facebook API allows applications to use various top-end Facebook features so that developers can add social context to their applications. This API uses the RESTful protocol and the responses are in JSON format.

Instagram API

The Instagram API, which is the popular photo sharing app and service API, provides access to user authentication, friend connections, photos, as well as other elements, which includes uploading new media as well.

Instagram API

Twitter API

The Twitter API includes two RESTful APIs. These REST API methods allow developers to access core Twitter data, which includes Twitter features such as update timelines, status data, and user information.

The search API methods allow developers to interact with Twitter search and trends data. XML, JSON, and Atom syndication formats are supported. However, some of the methods allow only a subset of the above-mentioned formats.

Indian Railways API

The Indian Railway API defines a set of rules that retrieves information that is related to various Indian railway booking features, such as PNR status, Seat Availability, Station Codes etc.

This is a RESTful API, which means that you pass requests in the form of a URL, thereby obtaining JSON response.

Flickr API

The Flickr API provides developers with the ability to utilize this brilliant online photo management and sharing service. With this API, it is possible to view, manipulate, and use various features related to Flickr.

Yahoo Weather API

The Yahoo API provides up to date weather information for any location, such as 5 day forecast, wind, atmosphere, and a lot more.

It is a dynamically generated feed based on WOEID, city name, or latitude/longitude.

Conclusion

APIs are the bridge between users, their app usage habits and interaction with the apps, and the apps themselves. APIs have thus become a part of the users’ daily lives. Free APIs have become integral to us developers, and we are making really good use of them.

The post 18 Free Mobile APIs Developers Should Consider appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/18-free-mobile-apis-developers-should-consider/feed/ 4
ipapi Adds Real-Time Geolocation and IP Data to Your Projects Sponsored https://speckyboy.com/ipapi-real-time-geolocation-ip-data/ https://speckyboy.com/ipapi-real-time-geolocation-ip-data/#respond Wed, 17 Oct 2018 11:14:20 +0000 https://speckyboy.com/?p=103666 Companies are using IP Geolocation technology at ever-increasing rates. This data is crucial to providing users with a more personalized experience. And, it also serves as an important tool in...

The post ipapi Adds Real-Time Geolocation and IP Data to Your Projects <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
Companies are using IP Geolocation technology at ever-increasing rates. This data is crucial to providing users with a more personalized experience. And, it also serves as an important tool in the quest for security.

Thanks to ipapi, developers can add geolocation capabilities to their projects in mere minutes. This REST API has been built with a focus on reliability and ease of use. It brings a world of data to your website or mobile app.

Trusted by over 30,000 businesses worldwide, ipapi is a complete solution. Here’s a look at what this powerful tool can do for you.

ipapi home page

Get to Know Your Users

Through Geolocation, you can learn a lot about your users. For instance, knowing the country they’re browsing from allows you to tailor your content. Display your website in their native language or show pricing in local currency. These items help you to build a better relationship with your users, right from the start. ipapi provides you with the data to make it happen.

Accurate Data

You rely on IP data to create the best user experience. That’s why ipapi has taken steps to ensure the most accurate IP data possible. They’ve established relationships with ISPs worldwide. So, you can be confident that the IPv4 and IPv6 lookup data returned is of the highest quality.

Fully Scalable

As your needs change, ipapi has the capacity to grow along with your business. With a scalable cloud infrastructure that can handle millions of daily requests, even the busiest of applications will keep running smoothly.

High-Level Security

Data sent to and from ipapi is encrypted with bank-grade 256-bit SSL. This ensures that user data kept safe and that prying eyes are locked out.

Budget Friendly Pricing

ipapi offers you up to 10,000 monthly requests for free. From there, premium plans are available, starting at only $10 per month. No matter your size or budget, ipapi is an affordable solution.

Easy to Implement

While ipapi is an incredibly powerful JSON and XML API, it’s been designed for easy integration. Seriously, you can be up and running in as little as 10 minutes. Plus, everything is well documented and a dedicated support staff is always there to provide a helping hand.

ipapi feature listing

Get the Data That Matters Most

Having the right information makes all the difference. With ipapi, you’ll have access to the IP data that is most relevant to you. From there, you can build applications that suit both your needs and those of your customers.

All told, there are more than 45 unique data points returned for each IP, including Location, Time Zone, Currency and Connection/Security data. Pinpoint a user’s location down to their zip code and geocoordinates. Determine their current time zone and which currency they’re using.

You’ll also have access to important information you can use to better secure your application. Detect crawlers, proxies and TOR instances. In addition, ipapi reports each user’s ISP, ASN and offers a threat evaluation. This means that you won’t be in the dark when it comes to security.

ipapi has also built their system to perform incredibly quickly and reliably. You’ll have the best data available in a consistent manner. That’s peace of mind.

ipapi data point listing

Start Using ipapi for Free

If you want to really know who your users are, you need to go beyond the basics. Utilizing ipapi will allow you to dig deeper in order to gain that competitive advantage. You’ll have everything you need in one easy-to-use package. And, it’s all backed by a top-notch team.

What are you waiting for? Sign up for your free API Key today and gain access to the most complete IP data available.

The post ipapi Adds Real-Time Geolocation and IP Data to Your Projects <span class="sponsored_text">Sponsored</span> appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/ipapi-real-time-geolocation-ip-data/feed/ 0
Building a Simple Reddit API Webapp Using jQuery https://speckyboy.com/building-simple-reddit-api-webapp-using-jquery/ https://speckyboy.com/building-simple-reddit-api-webapp-using-jquery/#comments Wed, 22 Jan 2014 15:40:31 +0000 http://speckyboy.com/?p=46011 The growing number of 3rd party APIs has created a tremendous group of enthusiastic developers. But without time to research documentation, this leaves some people curious without any means to...

The post Building a Simple Reddit API Webapp Using jQuery appeared first on Speckyboy Design Magazine.

]]>
The growing number of 3rd party APIs has created a tremendous group of enthusiastic developers. But without time to research documentation, this leaves some people curious without any means to actually build anything. I like toying around with these APIs because most are quite simple and easy to follow once you understand the basics.

For this tutorial, I want to go into the process of creating a Reddit domain search web app using jQuery. You simply enter the root-level domain of any website(ex: speckyboy.com), and it will display the latest 25 submissions in Reddit. This could even be extended into a WordPress plugin to showcase the latest Reddit submissions right from your own website.

reddit json api domain search custom tutorial screenshot

Building the Webpage

First, I’ll be downloading a local copy of jQuery to include in my document header. I’ve also created two empty files named styles.css and redditjson.js. Since this is more geared toward API access, I’ll skip over the stylesheet because it contains fairly rudimentary code.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Reddit API Webapp Demo - Speckyboy</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="https://speckyboy.com/wp-content/themes/speckyboy_responsive_v0.7/favicon.ico">
  <link rel="icon" href="https://speckyboy.com/wp-content/themes/speckyboy_responsive_v0.7/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/redditjson.js"></script>
</head>

The page itself is very barren since all the content will be loaded dynamically via jQuery/JSON. When first loading the page, you’ll notice a cute Reddit alien logo, which I customized from a freebie vector graphic on Dribbble. The search field itself is a standard text input that doesn’t typically use a submit button.

Hitting the ‘Enter’ key will trigger the form submission, which is then tied to a jQuery event handler. The final page object is an empty div with the ID #content, and this contains all the internal HTML data. I’m pulling results via JSON and looping through each entry on Reddit to provide a dynamically-loaded list of links on the page.

<div id="logo">
      <h1>Reddit API Domain Search</h1>
    </div>
    
    <p>Enter a domain without <code>https://www.</code> to browse recent submissions in Reddit.</p>
    
    <div id="searchfield">
      <form id="domainform" name="domainform">
        <input type="text" class="search" id="s" name="s" placeholder="ex: youtube.com">
      </form>
    </div>
    
    <div id="content"></div>

So now let’s jump right over into redditjson.js to see how the script runs.

Submit Event Trigger

I’m connecting an event handler onto the search field #domainform and preventing the submission event from unfolding. event.preventDefault() is the most common method to use. Right, when this happens, we know the user is looking for search results, so during the JSON request, I’ve appended a small loader gif to let users know something is happening in the background.

$(function(){
  $('#domainform').on('submit', function(event){
    event.preventDefault();
    $('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
    
    var domain = $('#s').val();
    var newdomain = domain.replace(/\//g, ''); // remove all slashes
    var requrl = "https://www.reddit.com/domain/";
    
    var fullurl = requrl + domain + ".json";

Then I need to pull out some variables which will get passed into the request. The contextual notice indicates that users should omit the first piece of any domain(ex: https://www) and just use the latter segment. JavaScript has a string method called replace() so we can remove any unnecessary slashes. Now the actual request URL is simply the full Reddit permalink with an additional .json at the end.

So the domain search for speckyboy.com can be pieced together by removing the final trailing slash and instead connecting to the local JSON file at this URL.

 $.getJSON(fullurl, function(json){
    var listing = json.data.children;
    var html = '<ul class="linklist">\n';

Using the prototypical getJSON() method we can remotely access these files and pull out API data without using any special API key. To authenticate accounts, you will need to create extra settings for your web app, but for a basic JSON response, we don’t need anything. The return data is passed into a callback function, and we access the full dataset with the variable json.data.

If you want to see all the possible options write some code like console.log(json.data) and see what appears in the console window. To save time, I’ve broken down the variable into child elements, each one representing a submitted link in Reddit. Each search page returns 25 results, so I figured that’s the easiest number to stick with for this demo.

Looping through JSON

Before calling the loop, I’ve created the return variable called html. This will eventually replace the small loading gif inside our content div, and each link will be truncated into one big string. My variable “listing” holds each JSON object inside json.data.children.

for(var i=0, l=listing.length; i<l; i++) {
    var obj = listing[i].data;

    var votes     = obj.score;
    var title     = obj.title;
    var subtime   = obj.created_utc;
    var thumb     = obj.thumbnail;
    var subrdt    = "/r/"+obj.subreddit;
    var redditurl = "https://www.reddit.com"+obj.permalink;
    var subrdturl = "https://www.reddit.com/r/"+obj.subreddit+"/";
    var exturl    = obj.url;
    
    var timeago = timeSince(subtime);

    if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
      thumb = 'img/default-thumb.png';
  
    html += '<li class="clearfix">\n';
    html += '<img src="'+thumb+'" class="thumbimg">\n';
    html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
    html += '<p class="subrdt">posted to <a href="'+subrdturl+'" target="_blank">'+subrdt+'</a> '+timeago+'</p>';
    html += '<p><a href="'+exturl+'" class="blubtn" target="_blank">visit link</a> - <a href="'+redditurl+'" class="blubtn" target="_blank">view on reddit</a></p>';
    html += '</div></li>\n';
  } // end for{} loop
  htmlOutput(html);

  }); // end getJSON()
}); // end .on(submit) listener

So, within each loop, we pass through the links one by one pulling out specific information that needs to be displayed on the page. Each object can be accessed through listing[n] with n being the current digit(0-24). The data inside will contain natural key-value pairs for the total number of votes, the link URL, the subreddit name, and even the thumbnail image.

You may notice there is a small if{} logic statement checking against the thumbnail URL. If there isn’t any photo or if it’s NSFW, then I’m using a default thumbnail image saved directly from Reddit. All these variables are then concatenated into the same HTML string, and this reaches the bottom we loop over into the next item. When there are no more items, this huge HTML string is applied to a function called htmlOutput().

  function htmlOutput(html) {
    html += '</ul>';
    
    $('#content').html(html);
    //console.log(html);
  }

Pretty simple, huh? I created the unordered list outside of the loop, and we finally closed it with this function call. I left a commented line of code relating to the console that you may find intriguing for testing purposes.

Formatting Time Intervals

If you noticed in the loop, there is one variable called timeago, which references a unique function timeSince(). The Reddit API pulls out submission times in Unix, and I want it to display in the format “xx times ago.”

While browsing Stack Overflow I came upon this beautiful solution which I tweaked ever-so-slightly to work in this tutorial. You don’t need to completely understand this function, but it doesn’t hurt to skim through and try digesting some stuff.

  /**
   * Return time since the link was posted
   * https://stackoverflow.com/a/3177838/477958
  **/
  function timeSince(date) {
    var seconds = Math.floor(((new Date().getTime()/1000) - date))

    var interval = Math.floor(seconds / 31536000);

    if (interval >= 1) {
      if(interval == 1) return interval + " year ago";
      else 
        return interval + " years ago";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval >= 1) {
      if(interval == 1) return interval + " month ago";
      else
        return interval + " months ago";
    }
    interval = Math.floor(seconds / 86400);
    if (interval >= 1) {
      if(interval == 1) return interval + " day ago";
      else
        return interval + " days ago";
    }
    interval = Math.floor(seconds / 3600);
    if (interval >= 1) {
      if(interval == 1) return interval + " hour ago";
      else
        return interval + " hours ago";
    }
    interval = Math.floor(seconds / 60);
    if (interval >= 1) {
      if(interval == 1) return interval + " minute ago";
      else
        return interval + " minutes ago";
    }
    return Math.floor(seconds) + " seconds ago";
  }

Basically, the whole timestamp is coded from the Unix standard January 1st, 1970. These numbers continue rising as each day passes along. The function itself will break this number down into smaller segments of months, days, minutes, etc.

It will also check for singular items to ensure 1 minute/2 minutes display in the correct syntax. This probably wasn’t necessary, but it does add some creative insight to each submission. It helps to know if a story was just posted two days ago or two months ago(or even two years ago!).

If we get this far with no results, then the HTML variable will simply replace the loading gif with empty space. It’s not a perfect solution, but if you spend time looking over the JSON response data, you can really customize this API to behave in any way you’d like. Take a peek at my live demo, and feel free to download a copy of the tutorial codes.

reddit json api domain search custom tutorial screenshot

Closing

With Digg selling off to Betaworks, Reddit has taken over as the most prominent social news website. There are thousands if not hundreds of thousands, of new links submitted every day. The Reddit API can access user data, comments, and a whole lot more! It is my hope that this tutorial can get you started down the path of customizable API web development.

The post Building a Simple Reddit API Webapp Using jQuery appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/building-simple-reddit-api-webapp-using-jquery/feed/ 3
Using WordPress as a REST API for a Mobile App https://speckyboy.com/using-wordpress-as-an-rest-api-for-a-mobile-app/ https://speckyboy.com/using-wordpress-as-an-rest-api-for-a-mobile-app/#comments Wed, 06 Feb 2013 17:20:53 +0000 http://speckyboy.com/?p=28444 Often when making mobile apps you will need your app to get the latest content from your website, or if there is not a website already with content some way...

The post Using WordPress as a REST API for a Mobile App appeared first on Speckyboy Design Magazine.

]]>
Often when making mobile apps you will need your app to get the latest content from your website, or if there is not a website already with content some way of putting new or timely content into the mobile app.

Of course you do not want to have to update your app via iTunes, the Play Store or whatever, as you have to wait on people to upgrade before they see new content. You want to setup your mobile app to call the server and ask for the latest stuff by itself.

Using a REST API and JSON to deliver the content has to be the easiest way to do this.

Why use JSON/REST API and not AJAX?

Inherently within the design of AJAX the problem that you would face is that AJAX calls can only be against the domain that the current page is being delivered. Well, as you are using a mobile app there may be no domain, and thus you can’t use AJAX. This is known as Same Origin Policy, and is a security safeguard imposed on developers.

Yet if you use JSON (JavaScript Object Notation) properly and not an AJAX call it is possible to get around this. Making a JSON call to the API is using the same technology that you would use when loading a Javascript file from another domain. Many people do this by using the Google CDN version of jQuery, they load jQuery from Googles domain and not from their own.

When we make a JSON call, all that we are doing is loading a new script from the server. Here is the code as a function that you would use on your mobile phone app:

function loadJSON(url) {
  var headID = document.getElementsByTagName("head")[0];
  var newScript = document.createElement('script');
      newScript.type = 'text/javascript';
      newScript.src = url;       
  headID.appendChild(newScript);
}

I’ve used Javascript as the language here, which many of the development tools use (Phone gap, Appcelerrator, Appfurnace, etc). All that it does is take a URL as the input and create a new script tag in the head that loads the URL as a Javascript file

JSONP and JSON, what’s the difference?

JSONP and JSON are more of less the same beast. There is only one small difference, JSON only replies with the data, JSONP replies with the data and a callback process encapsulating it. Here are two example URL’s using facebooks open graph to reply with JSON and JSONP. The only difference in the two URL’s is the use of the GET variable callback=

https://graph.facebook.com/?id=https://speckyboy.com

{
   "id": "https://speckyboy.com",
   "shares": 608
}

https://graph.facebook.com/?id=https://speckyboy.com&callback=doThisFunction

/**/ doThisFunction({
   "id": "https://speckyboy.com",
   "shares": 608
});

As you can see, I’ve told facebook to reply with a JSONP request, using a callback and asking it to make that callback “doThisFunction”.

What this means is that when the reply comes back from the server, it will send the data to the function called doThisFunction()

function doThisFunction(data){
  alert('the page ' + data.id + ' has been shared ' + data.shares + ' times');
}

The above function would take the data (the JSON object) as sent to it via the callback, and then it would make an alert that shows some text, the page url and the share count.

The important part to notice here is the use of JSON dot notation. Dot Notation is the method that is used to access the data inside the JSON object. In this case data.id shows the url (the contents of the id object), and data.shares shows the share count (the contents of the shares object).

If your interested in seeing this in action, click here.

Now on with WordPress

WordPress is great, I love it. As I have said before, my mum, grandmother and girlfriend can use it without asking me every 5 seconds what to do, so it is definitley easy to use. With that in mind it’s the perfect administration platform for saving data. It’s quite easy to turn this around and make it a REST api also.

It must be said that if I was going to make a world class enterprise ready REST API, I would not use WordPress as the front end, maybe yes for the back end CMS administration, but not the front end. It’s doing far too much to get such a specific set of data, and in all honesty PHP is not the fastest language in the World. However all that said, for providing an API method for blogs to give access to the latest posts via API does not come under that umbrella. If your interested in what I would use in a world class enterprise situation, I would most likely use node.js, or maybe Python, but that is a whole other story.

OK, with the preamble out of the way, I am going to make a very simple way of performing a REST reply that gives out the 10 latest posts as a JSON object. Instead of writing a plugin to manage this (which I would normally do), I’m just going to write a very simple page template called “REST Blog Listing”. I am choosing to write a page template so I can control to a great degree what gets loaded.

For this we will need the following functions:

  • A way of reading the URL and checking the GET variables
    function check_url_vars()
  • Sanatize the variables so that when we save them we know we are not letting nasty things in the door
    functions save_url_vars() and function sanatize_vars()
  • Checking if the request is for a JSON object or JSONP object and replying with the right stuff
    function save_url_vars()
  • Making a call to the WordPress database for the latest published blog posts
    function make_the_loop()
  • Using the constructor function to automate the process
    function __construt()
  • Using the destructor function to clean up after
    function __destruct()
  • Some sort of method of handling errors
    function error()
  • Sending the output back to the client and GZIP’ing it where possible
    function send_output()

If you know your PHP you will already know that we’re going to use a class to mange this. We’re going to put this directly into the page template just to make it easy, but this could just as easily be transferred in with a WordPress plugin.

<?php

/**
 * Template Name: REST Blog Listing
 * @package WordPress
 * 
 */

// Notice that there is no request to get_header();  it is not needed


/*
* REST Class from speckyboy
*
*/

// check if the class exists already as we don't want it to fail
if(!class_exists('speckyboyREST')){
  class speckyboyREST{
    // define class variabels
    protected $_callback;
    protected $_count;
    protected $_output; 
    protected $_format;         
  
  // automate everything
  public function __construct(){
            $this->_output = array(); // setup the output as an array, needed for json
            $this->_count = 10; // define the blog count shown as default
            $this->_callback = false;  // set callback to false just incase a jsonp callback request is not made                      
            $this->_format = 'json'; // default to json replies, will be changed if callback used
      if( $this->check_url_vars() ){
        $this->save_url_vars();
      }
      $this->make_the_loop();
      $this->send_output();
        }      
        
        protected function check_url_vars(){
          if(!empty($_GET)){ // check to see if the GET variables are set at all, this could more specific if wanted. 
            return true;
          }else{
            return false;
          }
        }
        
        protected function sanatize_vars($var){ // stop nasties by removing them from the possible URL vars
                return strip_tags(html_entity_decode(urldecode($var)));        
        }
        
        protected function save_url_vars(){
                if(isset($_GET['callback']) ){
                        $this->_format = 'jsonp'; // as there is a callback, setting the output to be jsonp
                        $this->_callback = $this->sanatize_vars($_GET['callback']); // defining the output
                }
                if(isset($_GET['count']) ){
                        $this->_count = $this->sanatize_vars($_GET['count']); // could use is_numeric here if wanted
                }

        }
        
        protected function error($type, $errorMessage){
          $this->_output['status'] = $type; // define the error message value
          $this->_output['data'] = $errorMessage; // define the error message text
          $this->_format = 'jsonp'; // setting to jsonp so that we can force a callback to a error handler
          $this->_callback = 'errorReply';  // will send errors back to errorReply function.
        }
        
        
        protected function make_the_loop(){
          $query = array(
            'post_type' => 'post',        // get only posts  
                  'post_status' => 'publish',   // only published stuff        
                  'posts_per_page'=>$this->_count, // with the page count wanted  count = -1 means everything
          );
          $loop = get_transient('restget'.$this->_count); // get the transient of the loop to make things faster
          if($loop === false){                
                    $loop = new WP_Query($query);  // make loop query
                    set_transient('restget'.$this->_count, $loop, 60 * 60);  // set the transient for the loop for 1 hour
                }
          $array_out = array();  // setup an array to save the results          
          if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();  // do the loop
                        if(function_exists('has_post_thumbnail') && has_post_thumbnail()){   // check for a post thumnail                      
                          $image =  get_the_post_thumbnail($page->ID, 'thumbnail');  
                        }else{
                            $image = null;  // set image to null is there is not one.
                        }
                        $array_out[] = array(   // add a new array set
                            'title' => get_the_title(), // the title
                            'permalink'  => get_permalink(), // the link back to the main site
                            'excerpt' =>  get_the_excerpt(), // the post excerpt    
                            'image'=> $image
                         
                        );              
                        
          endwhile; // finsh the loop and then save the data
          $this->_output['status'] = '200'; // set a good status
                $this->_output['data'] = $array_out; // add the array to the data ready to json encode
          else:
                $this->error('400','no data returned'); // no data error
            endif;
        }
        
  protected function send_output(){
      $time = time() + 60 * 60;  // setup a 1 hour cache on the output
            $expire = date ( "D, d M Y H:i:s e", $time ); // define the expire time       
            header("Expires: " . $expire );  // set expire header for 1 hour
            header("Content-type: application/json"); // set content type to be json    
            if(function_exists('ob_gzhandler')){  // setup GZIP compression if available
                ob_start('ob_gzhandler'); //start gzipped buffer
            }
            else{ 
                ob_start(); // start output buffer
            }            
            switch($this->_format){
            case 'json':
                echo json_encode($this->_output);  // if json, echo json encoded data to buffer
                break;
            case 'jsonp':
                echo $this->_callback."(".json_encode($this->_output).");";    // if jsonp, echo json encode with callback to buffer            
                break;
            }
            ob_end_flush(); // flush the buffer sendin the output to the client
        }
        
        public function __desctuct(){
          unset($this); // kill all the things that have been made, clean up behind.
        }

  }
}

// Start the class on load and get reply
$restapi = new speckyboyREST();

// notice no request for get_sidebar() or get_footer(); it is not needed as we are not sending HTML, just JSON

?>

To use the above code, you can either cut and paste it in a page template file inside your theme or you can use the one in this zip file. If you want to see it in action you can see it here, but do be aware that I’ve disabled the count from being more than 20 posts long.

Finishing off the callback

Unless you are using server to server communications to make the JSON data request, you will want to use the callback variable. To make this part of it work correctly it’s back to using JSON dot notation again. What we need to do is to loop through the content of the data object using the for loop and then create the HTML to display it on screen.

function callbackFunction(data){
  values = data.data;
  var output = '<ul>';
  for (var i = 0; i < values.length; i++) {
    output += "<li style='clear:left'>";
      if( values[i].image != null) { 
        output += "<div style='float:left; margin-right:10px'>"
          output += values[i].image;
        output += "</div>"  
      }
      output += "<h2><a href='"+ values[i].permalink +"'>" + values[i].title + "</a></h2>";
      output += "<p>" + values[i].excerpt + "</p>";
    output += "</li>";    
  }
  output += '</ul>';
  document.getElementById('output').innerHTML = output;
}

Looking at the code you can see I have chosen to use inline styles, which you may not want to, this is because the mobile app may not allow for a CSS file. You can rip this out if you want. The other important thing to notice is the use use of value[i], this is to get to the exact object in the loop, the [i] represents the relevant data set

If you want to see this code in action, check out this page.

Dealing with errors

To deal with errors there will also need to be a function called errorReply() created

function errorReply(data){
  alert('there has been a problem. ' + data.data);
}

I’m just taking the simple approach here by showing the error message in a popup alert. It could be much more complex.

What could be done better/differently

There is always things that can be done better or differently, and before you get too critical of this how-to, please remember that it’s just a post and not a book I am writing. All that said, there are many things that could be done better or differently.

  • Use the transients to store the JSON output and not just the loop.
  • There could be an option to deal with the output from the REST API as XML.
  • This could be setup as a plugin and then extend classes to make other rest api’s available.
  • Could setup the WordPress url rewrite re-write API to collect the vars from the url and not GET vars.
  • Could setup a separate api subdomain with the wp-config.php setup not to allow cookies on that domain.
  • Much better error handling could be employed client-side, and maybe also at the class-side of things. For example we could read the status and perform the right function based on that

No doubt you have thought of a few other possibilities. Anyhow, feel free to take the code and make it work for yourself.

The post Using WordPress as a REST API for a Mobile App appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/using-wordpress-as-an-rest-api-for-a-mobile-app/feed/ 9
Coding a Vimeo API Instant Search App with jQuery https://speckyboy.com/coding-a-vimeo-api-instant-search-app-with-jquery/ https://speckyboy.com/coding-a-vimeo-api-instant-search-app-with-jquery/#comments Wed, 31 Oct 2012 07:29:56 +0000 http://speckyboy.com/?p=29181 In this tutorial, we show you how to build a small Vimeo API instant search web app, creating the front-end with jQuery and the backend on PHP.

The post Coding a Vimeo API Instant Search App with jQuery appeared first on Speckyboy Design Magazine.

]]>
Web developers and Internet enthusiasts alike are very fond of online video services. One social video website Vimeo is a great example of how HD content can be stored and streamed across the planet. I love the quality you find with Vimeo uploads, and the user base is extremely knowledgeable on a wide variety of topics.

For this tutorial, I want to explain how we can build a small Vimeo API instant search web app. I’ll be creating the front end with jQuery and the back end with PHP. There is actually a full developer’s API with references for programmers. I’ll stick to explaining the more convoluted ideas so that you can follow along with my source code.

Instant Vimeo API with PHP and Ajax tutorial preview

Initial Document Concept

I will first explain how we can put together the HTML document so it runs our frontend Ajax functions. Let’s include a reference to the most recent jQuery library, which is used for Ajax calls. I’m also using another file v.js, for our custom API commands.

Inside the body, I have an input field used for search queries. The #results div will contain all the HTML output directly into our webpage. The whole index document is actually very small in comparison to the scripts. I’ve copied over the exact code below:


<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Vimeo Instant Search</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="stylesheet" type="text/css" href="style.css">
  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=McLaren">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script type="text/javascript" src="v.js"></script>
<!--[if lt IE 9]>
  <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

<body>
  <div id="w">
    <div id="top" class="clearfix">
      <h2>Vimeo Instant Search</h2>
      <input type="text" name="s" id="s" class="sbox" tabindex="1" placeholder="Search videos...">
    </div>
    
    <div id="results" class="clearfix"></div>

  </div><!-- /#w -->

</body>
</html>

Inside the results div we will include smaller divs with video content. This would make reference to the video title, thumbnail image, and the uploader’s name. The CSS styles are super easy to follow and read quickly. I have also included a few CSS resets and these other blocks added into my style.css file.

/** results **/
#results { display: block; }

#results .v { display: block; float: left; position: relative; width: 225px; margin-right: 12px; margin-bottom: 22px; padding-bottom: 10px; }

#results .v a.wrapping { display: block; width: 225px; }

#results .v .details { display: block; }

#results .v .details img.userpic { float: left; position: relative; padding: 2px; background: #fff; top: -2px; left: -7px; }

#results .v .details h3 { display: block; position: relative; font-size: 1.55em; white-space: nowrap; overflow: hidden; left: -6px; margin-bottom: 2px; color: #737373; }
#results .v .details .user { display: block; font-size: 1.1em; color: #333; left: -4px; white-space: nowrap; overflow: hidden; }
#results .v .details .user a { font-weight: bold; }

Backend API Dev in PHP

Let’s jump now into the backend coding in PHP. Afterward, we can tie in both frontend and backend interfaces to make our Ajaxified web app. To start off, I’m going to download a copy of the official Vimeo API wrapper in PHP.

We can simply include this file in our backend PHP document, which I’ve named ajax.php. Any call we make on the backend will require an API public key and secret key. These are just long string hashes to authenticate your web app. Head over to Vimeo’s developer page and sign up for a new application. The process is quick and shouldn’t take more than a couple of minutes to complete.

Now, we can start building the custom PHP file for Ajax response data. We’re going to be passing JSON content because this is the easiest output to loop through inside jQuery. Here are the first couple of lines inside ajax.php:

header('Content-type: application/json');

require_once('vimeo.php');

$key = "PUBLICKEY";
$secret = "SECRETKEY";

$query = $_POST['q'];
$limit = 12; // number of videos to display for each search

The header() function is necessary to determine what type of output we’re providing. Also, the $query variable isn’t defined just yet, but we’ll be creating this inside JavaScript. It will contain the search string a user has entered into the form field.

$vimeo = new phpVimeo($key, $secret);
$response = $vimeo->call('vimeo.videos.search', array('per_page' => $limit, 'query' => $query, 'sort' => 'relevant'));

$jarray = array();

Now we’re getting into the more complex PHP logic cycle. phpVimeo is referencing the class file we included from Github. This makes data access a whole lot easier, and we can save hours of development time. The $jarray variable is simply an empty array for now. It will eventually contain data on 12 full videos from the search query, then get passed into JSON.

Looping Through Return Data

With all the main PHP stuff setup, we can move into the return content. Since we are working with multiple results, this requires a foreach loop to quickly pass through all the related data. We will set up array keys inside the $jarray variable, which will be repeated for each new entry.

foreach($response->videos->video as $v){
  $videoinfo = $vimeo->call('vimeo.videos.getInfo', array('video_id' => $v->id));
  
  $jarray[] = array(
  "thumbnail" => $videoinfo->video[0]->thumbnails->thumbnail[1]->_content,
  "url" => $videoinfo->video[0]->urls->url[0]->_content,
  "title" => $videoinfo->video[0]->title,
  "username" => $videoinfo->video[0]->owner->display_name,
  "userurl" => $videoinfo->video[0]->owner->profileurl,
  "userpic" => $videoinfo->video[0]->owner->portraits->portrait[0]->_content
  );
}

print_r(str_replace('\\/', '/', json_encode($jarray)));
die();

This code will work by pulling from our >$response data earlier. Each $response->videos->video object holds internal data which we need to pull out and save. This data specifically includes a video thumbnail, URL, and title, along with the uploader’s username, profile URL & photo.

The last print_r() function outputs all our data onto the page in JSON format. We need to remove escaped slashes from the output so it’s cleaner and easier to sort through. Then finally, the PHP script calls die() to let Ajax know we are done using the asynchronous connection.

Custom jQuery Instant Search

So, with the front and backend complete, let’s tie everything together through JavaScript. I’m writing my code inside an external file, v.js which begins like any typical jQuery document.

$(document).ready(function(){
  var s = $("#s"); // search input field
  var c = $("#results"); // results container
  var t; // timer 
  
  $("#s").keydown(function(e){
    clearTimeout(t);
    if (!args) { var args = []; }
    
    if (e.which === 65 && (e.ctrlKey || e.metaKey)) {
        // allow the user to ctrl+a or cmd+a to select text
        // without calling a new search function
    } else {
      t = setTimeout(function(){ vimeoSearch() }, 400);     
    }
  });

The first few variables are shorthand for targeting the input search field, results div, and a numerical timer. Since people can often take extra time when typing, we need to give a delay before calling the API search. This is the purpose of a timer variable coupled with the JavaScript setTimeout() method.

Targeting the search field, I have set up a new event listener for any .keydown() event. Each time the user enters a new key, we will clear the previous timer to start fresh and run a simple if/else clause. If the user has entered CTRL+A or CMD+A, then we do not run any search. This is associated with selecting all the text inside a search input and generally doesn’t constitute a new search query.

Otherwise, the user has entered some new text, and we’re pausing for 400 milliseconds, then calling a new function vimeoSearch().

Ajax Results Display

Inside my vimeoSearch() function, we are performing a couple of tasks. First, empty out the contents div in case there are still previous search results displaying. Then we create a variable for the query string and append a loader gif to the page while we await results.

function vimeoSearch() {
  c.empty();
  var q = s.val();
  
  c.html('<img src="images/loader.gif" alt="loading..." id="loader">');
    
  $.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: "q="+q,
    success: function(data){
        
      $.each(data, function(i, item) {
        var code = '<div class="v"> <span class="details"><img src="'+data[i].userpic+'" class="userpic"> <h3>'+data[i].title+'</h3> <span class="user">uploaded by <a href="'+data[i].userurl+'" target="_blank">'+data[i].username+'</a></span></span> <a href="'+data[i].url+'" target="_blank" class="wrapping"><img src="'+data[i].thumbnail+'" alt="'+data[i].title+' video thumbnail" class="thumbnail"></a> </div>';
          
        $("#loader").remove();
        c.append(code);
      }); // end each loop
    },
    error: function(xhr, type, exception) { 
      c.html("Vimeo Error: " + type); 
    }}); // end ajax call
} // end vimeoSearch() function

The whole function looks really long, but there aren’t a lot of moving parts. The longest segment is inside the .ajax() method where we define some parameters and set up a success/failure callback function. If we access ajax.php and get a successful result, then we need to loop through each of the JSON values.

This can be accomplished through jQuery’s .each() loop placed on the return data. After generating the full code, we can remove the loader image and append all our new data. Otherwise, we display a parse error on the page for any failed search queries. Most of the code is fairly straightforward and should be easy enough to follow.

Instant Vimeo Search API with PHP and Ajax tutorial preview

Final Thoughts

I hope this tutorial is a good introduction to using Vimeo’s API. Backend web development is powerful and gaining more attention from mainstream programmers. With open APIs on nearly any website, it’s becoming even easier to build complex web applications right inside your browser.

If you are unfamiliar with PHP, then much of this code will seem foreign. But if you have the ability to scan each document, you may learn a few neat tricks. Additionally, you can download a copy of my source code and work with it on your own server. If you have any further comments or questions, feel free to post in the discussion area below.

The post Coding a Vimeo API Instant Search App with jQuery appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/coding-a-vimeo-api-instant-search-app-with-jquery/feed/ 6