- what is API web services, how do you create them and why? [closed]
- 5 Answers 5
- API vs Web Service: What’s the Difference?
- What is an API?
- What is a Web Service?
- KEY DIFFERENCE
- Types of Web Services
- Features of Web API
- Features of Web Services
- Difference between API and Web Services
- Advantages of API Services
- Advantages of Web Services
- Disadvantages of API
- Disadvantages of Web Services
- Введение в REST API — RESTful веб-сервисы
- Вы изучите:
- Что такое REST?
- Краткий обзор HTTP
- Протокол HTTP
- HTTP и RESTful веб-сервисы
- Ресурс
- URI ресурса
- REST и Ресурсы
- Компоненты HTTP
- Методы HTTP-запроса
- Код статуса ответа HTTP
- Резюме
what is API web services, how do you create them and why? [closed]
what is the purpose of web services?
i mean isn’t all web applications a web service ?
also why do people create API web services? is it to let developer’s use the website’s functions? kinda like facebook and youtube ?
is it possible to make a API for web service where you can use C++ or VB to use the functions? therefore, someone could make a desktop application based on your web application’s API ?
how do you create a web service API and a web service ?
5 Answers 5
Allow the easy consumption of a service using web technologies? I mean, you can potentially code your application to do what the browser does ( that’s how many applications for stackoverflow have been done in the past )
The problems are:
it is much harder than using an API
Since there is no API, changes in the website do crash your application ( while responsible API’s will allow you to use your old version )
i mean isn’t all web applications a web service ?
Not at all. A web app is an specific application designed to be used by a webbrowser ( firefox, chrome, etc ) While a webservice is meant to be consumed by other application.
You can consume a webservice in pretty much any programming language out there.
also why do people create API web services? is it to let developer’s use the website’s functions? kinda like facebook and youtube ?
Not the website functionality but to allow them to create own applications that use some functionality of that website.
For instance YouTube allow you to upload videos with it’s API, otherwise you’ll have to «simultate» the HTTP post which can be problematic.
That way, some tools offer the capability of «uploading» your video directly from the app.
is it possible to make a API for web service where you can use C++ or VB to use the functions?
That’s the point, among other programming languages.
therefore, someone could make a desktop application based on your web application’s API ?
Here’s an example of the Object-C application I use for Twitter ( tweetie http://www.atebits.com/tweetie-mac/ )
how do you create a web service API and a web service ?*
It is not much different from creating a API for an internal fremework/product/library.
You have to define what are you going to offer ( your public interface, your services that is )
Create a list of in/out parameters and interchange formats ( XML, json, text/plain, YAML, whatever )
And finally provide and endpoint in the web ( or why not intranet )
Webservices could are harder to control than regular APIs, you have to check security concerns, work load etc.
To see a working API refer to that mentioned by Nathan here
There are basically two different types of webservices, one that is SOAP-based and the other is REST-based.
Either can be accessed by desktop applications. I have written applications, such as screensavers, that will interact with the server through both of these types of webservices.
An API is useful so that people can write applications, as you mentioned, to use these services, as, without applications using them, these webservices are pretty useless.
A SOAP-based webservice is basically just a web application that sends and receives using an xml message format that follows a standard.
A REST-based webservice is the cgi-based application that is similar to using an html form element, generally using GET, but, if you are doing anything that can be destructive, or change databases, you will want to use POST.
You can write applications using these APIs in any language, which is the advantage, as you can then choose which language is best for the server-side, and that has no impact on what you do on the client-side.
How to create a webservice will depend on which of the two main types you want to create, and which language you choose to use.
API vs Web Service: What’s the Difference?
What is an API?
API is the acronym for Application Programming Interface. It is a software interface that allows two applications to interact with each other without any user intervention.
APIs provides product or service to communicate with other products and services without having to know how they’re implemented.
What is a Web Service?
A Web service is a collection of open protocols and standards which are widely used for exchanging data between systems or applications.
Software applications are written using various programming languages and running on multiple platforms. It allows you to use web services to exchange data over computer networks.
KEY DIFFERENCE
- Web service is a collection of open source protocols and standards used for exchanging data between systems or applications whereas API is a software interface that allows two applications to interact with each other without any user involvement.
- Web service is used for REST, SOAP and XML-RPC for communication while API is used for any style of communication.
- Web service supports only HTTP protocol whereas API supports HTTP/HTTPS protocol.
- Web service supports XML while API supports XML and JSON.
- All Web services are APIs but all APIs are not web services.
Types of Web Services
Web services should be implemented in various ways. The two types of widely used web services are SOAP and RESTful web services.
SOAP – SOAP is a protocol which was designed before REST came into the picture. The main idea behind creating SOAP was to ensure that programs built on different platforms and programming languages could securely exchange data.
REST – This was designed specifically for working with components such as media components, files, or even objects on a particular hardware device. Any web service which is defined on the principles of REST can be called a RESTful web service. REST uses the normal HTTP verbs of GET, POST, PUT and DELETE for working with the required components.
Features of Web API
Here are some essential features of API:
- Efficiency
- Wider reach
- Customizable
- Personalization
- Data ownership
- Easy integration with GUI
- Time effective
- Language-independent
Features of Web Services
Here are some essential features of web services:
- Loosely coupled
- Synchronous or asynchronous functionality
- Ability to support remote procedure calls
- Supports document exchange
Difference between API and Web Services
Here are important differences between Web services and API.
Web Service | API |
All web services are APIs. | All APIs are not web services. |
It supports XML. | Responses are formatted using Web API’s MediaTypeFormatter into XML, JSON, or any other given format. |
You need a SOAP protocol to send or receive and data over the network. Therefore it does not have light-weight architecture. | API has a light-weight architecture. |
It can be used by any client who understands XML. | It can be used by a client who understands JSON or XML. |
Web service uses three styles: REST, SOAP, and XML-RPC for communication. | API can be used for any style of communication. |
It provides supports only for the HTTP protocol. | It provides support for the HTTP/s protocol: URL Request/Response Headers, etc. |
Advantages of API Services
Here are pros/benefits of using API:
- API supports traditional CRUD (Create Read Update Delete) actions as it works with HTTP verbs GET, PUT, POST, and DELETE.
- API helps you to expose service data to the browser
- It is based on HTTP, which is easy to define, expose in REST-full way.
Advantages of Web Services
Here are the important pros/benefits of using web services:
- Offers faster communications within and across organizations
- Each service exists independently of other services.
- Interoperability has the highest priority.
- Using Web services, your application helps you to publish its message or function to the rest of the world.
- Web services help solve interoperability issues by giving different applications a way to link their data.
- Web services help you to exchange data between different applications and different platforms.
- It allows applications to communicate, exchange data, and shared services among themselves.
- Web services are specifically designed to be used as a web page request and help you to receive data.
- It serves as building blocks which makes it easy to reuse web service components in other services. Web Services are deployed on internet standards such as standard Apache, and Axis2. It provides WSDL, HTTP, driven services.
Disadvantages of API
Here are important drawbacks/cons of using API services:
- Creating API is a very time-consuming process
- A fixed scale is necessary
- Imprecise boundary delineation
- To create API, programming knowledge is necessary
- Maintenance cost is very high
- It can crash when testing API
Disadvantages of Web Services
Drawbacks/cons of using Web services:
- It does not access from browser
- Not leverage emerging Web developments (Semantic Web, AJAX XMLHttpRequest, etc.)
- Some web services are simple to use, but there are some flaws of using it.
- Any time one creates a service to handle a variety of customers, there is a demand for specialized machine requirements.
- The HTTP protocol is not reliable, so it does not offer any guarantee of delivery of the response.
Введение в REST API — RESTful веб-сервисы
Эта статья начинает серию постов о разработке REST API:
Intro to RESTful Web Services
REST означает REpresentational State Transfer (Википедия: «передача состояния представления»). Это популярный архитектурный подход для создания API в современном мире.
Вы изучите:
Что такое REST?
REST расшифровывается как REpresentational State Transfer. Это был термин, первоначально введен Роем Филдингом (Roy Fielding), который также был одним из создателей протокола HTTP. Отличительной особенностью сервисов REST является то, что они позволяют наилучшим образом использовать протокол HTTP. Теперь давайте кратко рассмотрим HTTP.
Краткий обзор HTTP
Давайте сначала откроем браузер и зайдем на веб-страницу:
А затем щелкните на одной из страниц результатов:
Далее мы можем нажать на ссылку на странице, на которой мы оказались:
И перейти на другую страницу:
Вот как мы обычно просматриваем веб страницы.
Когда мы просматриваем страницы в Интернете, за кулисами происходит много вещей. Ниже приведено упрощенное представление о том, что происходит между браузером и серверами, работающими на посещаемых веб-сайтах:
Протокол HTTP
Когда вы вводите в браузере URL-адрес, например www.google.com, на сервер отправляется запрос на веб-сайт, идентифицированный URL-адресом.
Затем этот сервер формирует и выдает ответ. Важным является формат этих запросов и ответов. Эти форматы определяются протоколом HTTP — Hyper Text Transfer Protocol.
Когда вы набираете URL в браузере, он отправляет запрос GET на указанный сервер. Затем сервер отвечает HTTP-ответом, который содержит данные в формате HTML — Hyper Text Markup Language. Затем браузер получает этот HTML-код и отображает его на экране.
Допустим, вы заполняете форму, присутствующую на веб-странице, со списком элементов. В таком случае, когда вы нажимаете кнопку «Submit» (Отправить), HTTP-запрос POST отправляется на сервер.
HTTP и RESTful веб-сервисы
HTTP обеспечивает базовый уровень для создания веб-сервисов. Поэтому важно понимать HTTP. Вот несколько ключевых абстракций.
Ресурс
Ресурс — это ключевая абстракция, на которой концентрируется протокол HTTP. Ресурс — это все, что вы хотите показать внешнему миру через ваше приложение. Например, если мы пишем приложение для управления задачами, экземпляры ресурсов будут следующие:
- Конкретный пользователь
- Конкретная задача
- Список задач
URI ресурса
Когда вы разрабатываете RESTful сервисы, вы должны сосредоточить свое внимание на ресурсах приложения. Способ, которым мы идентифицируем ресурс для предоставления, состоит в том, чтобы назначить ему URI — универсальный идентификатор ресурса. Например:
- Создать пользователя: POST /users
- Удалить пользователя: DELETE /users/1
- Получить всех пользователей: GET /users
- Получить одного пользователя: GET /users/1
REST и Ресурсы
Важно отметить, что с REST вам нужно думать о приложении с точки зрения ресурсов:
Определите, какие ресурсы вы хотите открыть для внешнего мира
Используйте глаголы, уже определенные протоколом HTTP, для выполнения операций с этими ресурсами.
Вот как обычно реализуется служба REST:
- Формат обмена данными: здесь нет никаких ограничений. JSON — очень популярный формат, хотя можно использовать и другие, такие как XML
- Транспорт: всегда HTTP. REST полностью построен на основе HTTP.
- Определение сервиса: не существует стандарта для этого, а REST является гибким. Это может быть недостатком в некоторых сценариях, поскольку потребляющему приложению может быть необходимо понимать форматы запросов и ответов. Однако широко используются такие языки определения веб-приложений, как WADL (Web Application Definition Language) и Swagger.
REST фокусируется на ресурсах и на том, насколько эффективно вы выполняете операции с ними, используя HTTP.
Компоненты HTTP
HTTP определяет следующую структуру запроса:
- строка запроса (request line) — определяет тип сообщения
- заголовки запроса (header fields) — характеризуют тело сообщения, параметры передачи и прочие сведения
- тело сообщения (body) — необязательное
HTTP определяет следующую структуру ответного сообщения (response):
- строка состояния (status line), включающая код состояния и сообщение о причине
- поля заголовка ответа (header fields)
- дополнительное тело сообщения (body)
Методы HTTP-запроса
Метод, используемый в HTTP-запросе, указывает, какое действие вы хотите выполнить с этим запросом. Важные примеры:
- GET: получить подробную информацию о ресурсе
- POST: создать новый ресурс
- PUT: обновить существующий ресурс
- DELETE: Удалить ресурс
Код статуса ответа HTTP
Код состояния всегда присутствует в ответе HTTP. Типичные примеры:
- 200 — успех
- 404 — cтраница не найдена
По этому вопросу имеется авторское видео.
Резюме
В статье приведен на верхнем уровне обзор архитектурного стиля REST. Подчеркивается тот факт, что HTTP является основным строительным блоком REST сервисов. HTTP — это протокол, который используется для определения структуры запросов и ответов браузера. Мы видели, что HTTP имеет дело главным образом с ресурсами, доступными на веб-серверах. Ресурсы идентифицируются с помощью URI, а операции над этими ресурсами выполняются с использованием глаголов, определенных протоколом HTTP.
Наконец, мы рассмотрели, как службы REST наилучшим образом используют функции, предлагаемые HTTP, для предоставления ресурсов внешнему миру. REST не накладывает никаких ограничений на форматы представления ресурсов или на определение сервиса.