Chapterبەش 11 · Lectureوانە 11.1
Web APIs and JSONAPIـی وێب و JSON
What an API is, the examples and benefits from the course notes, and how PHP sends requests to a web API and reads its JSON response with json_encode(), json_decode(), file_get_contents() and cURL. You also build a small JSON API of your own and meet the REST style.
چییە، نموونە و سوودەکانی لە تێبینییەکانی کۆرسەکەدا و PHP چۆن بۆ وێب دەنێرێت و JSONـەکەی بە json_encode()، json_decode()، file_get_contents() و cURL دەخوێنێتەوە. هەروەها بچووکی JSONـی خۆت دروست دەکەیت و شێوازی دەناسیت.
What you will learnچی فێر دەبیت
- Explain the name Application Programming Interface part by part, and define an API in your own words.
- Give real examples of APIs and name their five benefits.
- Describe a web API request and response: method, endpoint, headers, status code and JSON body.
- Read and write JSON, and convert between JSON and PHP with
json_encode()andjson_decode(). - Build a small JSON API in PHP and call it with
file_get_contents()and cURL. - Use APIs safely: secret keys, HTTPS, timeouts, error checks and escaping.
- ناوی Application Programming Interface بەش بە بەش ڕوون بکەیتەوە و بە زمانی خۆت پێناسەی بکەیت.
- نموونەی ڕاستەقینەی بهێنیتەوە و پێنج سوودەکەی ناو ببەیت.
- و وێب وەسف بکەیت: ، ، ، و لاشەی JSON.
- JSON بخوێنیتەوە و بینووسیت و بە
json_encode()وjson_decode()لە نێوان JSON و PHPـدا بگۆڕیت. - بچووکی JSON بە PHP دروست بکەیت و بە
file_get_contents()و cURL بانگی بکەیت. - بە سەلامەتی بەکاربهێنیت: کلیلی نهێنی، ، ماوەی چاوەڕوانی، پشکنینی و پارێزراوکردنی .
Why APIs matterبۆچی API گرنگە؟
Think about the apps you use every day. A taxi app shows you a map. A news website shows today's weather in Slemani. A shop lets you press Log in with Google instead of making a new password. None of these companies drew its own maps, built its own weather station or wrote Google's login system. They asked another program for what they needed, and they asked through an .
بیر لەو ئەپانە بکەرەوە کە ڕۆژانە بەکاریان دەهێنیت. تەکسی نەخشەیەکت پیشان دەدات. هەواڵ کەشوهەوای ئەمڕۆی سلێمانی پیشان دەدات. فرۆشگایەک ڕێگەت دەدات دوگمەی Log in with Google دابگریت لە جیاتی ئەوەی نوێ دروست بکەیت. هیچ کام لەم کۆمپانیایانە نەخشەی خۆی نەکێشاوە، وێستگەی کەشوهەوای خۆی دروست نەکردووە و سیستەمی Google-ی نەنووسیوەتەوە. ئەوان ئەوەی پێویستیان بوو لە تر داوایان کرد و لە ڕێگەی داوایان کرد.
Today almost every modern website and phone app uses APIs. When you know how APIs work, your PHP pages can use maps, weather, translations, payments and much more, and other programs can use the data that your site offers.
ئەمڕۆ نزیکەی هەموو و مۆبایلی نوێ بەکاردەهێنێت. کاتێک بزانیت چۆن کار دەکات، پەڕە PHPیەکانت دەتوانن نەخشە، کەشوهەوا، وەرگێڕان، پارەدان و زۆر شتی تر بەکاربهێنن و تریش دەتوانن ئەو دراوانە بەکاربهێنن کە تۆ پێشکەشی دەکات.
Imagine a tea house (چایخانە). You sit at a table and you do not walk into the kitchen. You tell the waiter what you want from the menu, and the waiter brings it back. You do not need to know how the kitchen works. The waiter is the : the only door between you and the kitchen. The menu is the API's documentation: the list of things you are allowed to ask for.
چایخانەیەک بهێنە پێش چاوت. لەسەر مێزێک دادەنیشیت و ناچیتە ناو چێشتخانەکە. بە چایچییەکە دەڵێیت چیت دەوێت لە لیستی خواردنەکان و ئەویش بۆت دەهێنێت. پێویست ناکات بزانیت چێشتخانەکە چۆن کار دەکات. چایچییەکە : تاکە دەرگای نێوان تۆ و چێشتخانەکە. لیستی خواردنەکانیش : ئەو شتانەی ڕێگەت پێدراوە داوایان بکەیت.
Where the analogy stops workingسنووری ئەم نموونەیە
A waiter can guess what you mean if you speak unclearly. An API cannot: your request must follow the documented format exactly, or you get an error. An API also answers in milliseconds, and many APIs serve you only if you show a secret key.
چایچی دەتوانێت تێبگات مەبەستت چییە ئەگەر ناڕوون قسە بکەیت. ناتوانێت: دەبێت ڕێک بەو شێوەیە بێت کە لە نووسراوە، ئەگینا وەردەگریت. هەروەها لە چەند میلیچرکەیەکدا وەڵام دەداتەوە و زۆر تەنها ئەو کاتە خزمەتت دەکات کە کلیلێکی نهێنی پیشان بدەیت.
What does “API” mean?واتای «API» چییە؟
API is short for Application Programming Interface. The course notes explain the name by splitting it into two parts: application programming and interface.
Application Programming Interfaceـە. تێبینییەکانی کۆرسەکە ناوەکە بە دابەشکردنی بۆ دوو بەش ڕوون دەکەنەوە: ئەپڵیکەیشن (Application Programming) و (Interface).
| Part of the nameبەشی ناوەکە | Meaning in the course notesواتا لە تێبینییەکانی کۆرسەکەدا | Exampleنموونە |
|---|---|---|
| Application programming ئەپڵیکەیشن | The work of creating application programs with one or more programming languages.کاری دروستکردنی ئەپڵیکەیشن بە یەک یان چەند . | Writing a chat app in PHP and JavaScript.نووسینی چات بە PHP و JavaScript. |
| Application program ئەپڵیکەیشن | A complete program, written in one or more programming languages, that does a particular job directly for the user. تەواوە، بە یەک یان چەند نووسراوە و کارێکی دیاریکراو ڕاستەوخۆ بۆ دەکات. | Media players and web browsers. و . |
| Interface / | A point where two things meet and interact.خاڵێکە کە دوو شت تێیدا بەیەک دەگەن و کار لە یەکتر دەکەن. | A door is where people meet the house: they use it to enter.دەرگا شوێنی بەیەکگەیشتنی مرۆڤ و خانووە: بەکاری دەهێنن بۆ چوونە ژوورەوە. |
The place where two things meet and work together. A user interface is what a person sees and touches; an is an interface between two programs; a hardware interface, such as USB or SATA, is the connector and rules that join a device to a computer.
ئەو شوێنەیە کە دوو شت تێیدا بەیەک دەگەن و پێکەوە کار دەکەن. ڕووکاری بەکارهێنەر ئەوەیە کە مرۆڤ دەیبینێت و دەستی لێ دەدات؛ ڕووکارێکە لە نێوان دوو ؛ ڕووکاری ، وەک USB یان SATA، سەرە پەیوەندی و یاساکانە کە ئامێرێک بە دەبەستن.
Put the parts together: an API is an interface for programs. It is the door that one application opens so that other programs — not people — can use its features and data. A web page has a user interface for humans (buttons, menus, forms). An API is the interface the same service offers to programmers.
بەشەکان پێکەوە دابنێ: بۆ . ئەو دەرگایەیە کە ئەپڵیکەیشنێک دەیکاتەوە تا تر — نەک مرۆڤ — بتوانن تواناکان و بەکاربهێنن. بۆ مرۆڤ هەیە (دوگمە، لیست، ). ئەو کە هەمان خزمەتگوزاری پێشکەشی دەکات.
In Kurdish (Sorani): what an API is and why programs use APIs to talk to each other.
بە کوردیی سۆرانی: چییە و بۆچی بەکاردەهێنن بۆ ئەوەی پێکەوە قسە بکەن.
Kurdish (Sorani) explanation of what an API is and why it is used.
ڕوونکردنەوەیەک بە کوردیی سۆرانی: چییە و بۆچی بەکاردێت.
What does “API” mean?واتای «API» چییە؟
Four ways to define an APIچوار پێناسە بۆ API
The course notes give four definitions. They say the same thing in different words, so read all four and keep the one you can explain best.
تێبینییەکانی کۆرسەکە چوار پێناسە دەدەن. هەموویان هەمان شت بە وشەی جیاواز دەڵێن، بۆیە هەر چواریان بخوێنەوە و ئەوەیان هەڵبگرە کە باشتر دەتوانیت ڕوونی بکەیتەوە.
- An API is a software intermediary (a program in the middle) that allows two applications to talk to each other.
- An API is simply an interface to interact with an application for programming. The API of an application is a set of programming code that allows other third-party systems to interact with that application.
- An API defines the methods, protocols and rules that applications use to interact with each other. It lets one application access and use the functions, data or services of another application without needing to know how they are implemented inside.
- An API is an intermediary software that acts as an interface between two applications, so that they can interact.
- ناوەندگیرێکی ( لە ناوەڕاستدا) کە ڕێگە بە دوو ئەپڵیکەیشن دەدات قسە لەگەڵ یەکتر بکەن.
- بە سادەیی بۆ کارلێکردن لەگەڵ ئەپڵیکەیشنێک بە . ئەپڵیکەیشنێک کۆمەڵێک کۆدی کە ڕێگە بە سیستەمەکانی تری لایەنی سێیەم دەدات کار لەگەڵ ئەو ئەپڵیکەیشنە بکەن.
- ئەو ڕێگا، و یاسایانە دیاری دەکات کە ئەپڵیکەیشنەکان بۆ کارلێکردن لەگەڵ یەکتر بەکاریان دەهێنن. ڕێگە بە ئەپڵیکەیشنێک دەدات دەستی بگاتە ، یان خزمەتگوزارییەکانی ئەپڵیکەیشنێکی تر و بەکاریان بهێنێت، بەبێ ئەوەی پێویست بێت بزانێت لە ناوەوە چۆن دروست کراون.
- ناوەندگیرە کە وەک لە نێوان دوو ئەپڵیکەیشندا کار دەکات، تا بتوانن کارلێک بکەن.
“Third party” means someone else: not you (the first party) and not your user (the second party). When your website uses Google Maps, Google is the third party.
«لایەنی سێیەم» واتە کەسێکی تر: نە تۆ (لایەنی یەکەم) و نە (لایەنی دووەم). کاتێک Google Maps بەکاردەهێنێت، Google لایەنی سێیەمە.
A set of rules that lets one program use another program's features or data without knowing how it works inside. On the Web, an API answers requests, usually with .
کۆمەڵێک یاسایە کە ڕێگە بە بەرنامەیەک دەدات تایبەتمەندێتی یان دراوەکانی بەرنامەیەکی تر بەکار بهێنێت، بەبێ ئەوەی بزانێت لە ناوەوە چۆن کار دەکات. لەسەر وێب، API وەڵامی داواکارییەکانی دەداتەوە، زۆرجار بە .
Examples of APIsنموونەکانی API
The course notes name four well-known kinds of API:
تێبینییەکانی کۆرسەکە چوار جۆری ناسراوی ناو دەبەن:
- Google Maps API — helps websites show maps and search for exact places. When you look for a place on a website that uses it, the Google Maps API gets the data from Google and returns the result (the location) to that website.
- Twitter API (now the X API) — lets programs read and publish posts. It is used, for example, by bots: programs that post automatically, such as a bot that posts the exchange rate every morning.
- Weather APIs — send the current weather and the forecast for a city. News sites and phone apps show this data instead of measuring the weather themselves.
- Social login APIs — buttons such as Log in with Google or Log in with Facebook. The website asks Google or Facebook to confirm who you are, so you do not need a new username and password for every site.
- Google Maps API — یارمەتی دەدات نەخشە پیشان بدەن و بەدوای شوێنی ورددا بگەڕێن. کاتێک لە کە بەکاری دەهێنێت بەدوای شوێنێکدا دەگەڕێیت، Google Maps API لە Google وەردەگرێت و ئەنجامەکە (شوێنەکە) بۆ ئەو دەگەڕێنێتەوە.
- Twitter API (ئێستا X API) — ڕێگە بە دەدات پۆست بخوێننەوە و بڵاوی بکەنەوە. بۆ نموونە بۆتەکان بەکاری دەهێنن: واتە کە بە شێوەی خۆکار پۆست دەکەن، وەک بۆتێک کە هەموو بەیانییەک نرخی دراو پۆست دەکات.
- APIکانی کەشوهەوا — کەشوهەوای ئێستا و پێشبینیی شارێک دەنێرن. هەواڵ و مۆبایل ئەم پیشان دەدەن لە جیاتی ئەوەی خۆیان کەشوهەوا بپێون.
- APIکانی بە — دوگمەی وەک Log in with Google یان Log in with Facebook. داوا لە Google یان Facebook دەکات بیسەلمێنێت تۆ کێیت، بۆیە پێویستت بە و نوێ نییە بۆ هەر .
Why companies use APIs: five benefitsبۆچی کۆمپانیاکان API بەکاردەهێنن: پێنج سوود
The course notes list five benefits of APIs. Here is what each one means in practice:
تێبینییەکانی کۆرسەکە پێنج سوودی دەژمێرن. ئەمە واتای هەر یەکەیانە لە کاری ڕاستەقینەدا:
| Benefitسوود | What it meansواتاکەی | Exampleنموونە |
|---|---|---|
| 1. Cost-saving1. کەمکردنەوەی تێچوون | You reuse a ready service instead of building and paying for everything yourself.خزمەتگوزارییەکی ئامادە بەکاردەهێنیتەوە لە جیاتی ئەوەی هەموو شتێک خۆت دروست بکەیت و پارەی بدەیت. | A small shop shows a map API instead of drawing its own maps.فرۆشگایەکی بچووک نەخشە پیشان دەدات لە جیاتی کێشانی نەخشەی خۆی. |
| 2. Increased productivity2. زیادبوونی بەرهەمداری | Developers finish faster and spend their time on their own idea. خێراتر تەواو دەکەن و کاتەکەیان بۆ بیرۆکەی خۆیان دادەنێن. | Login with Google takes minutes, not weeks of work. بە Google چەند خولەکێکی دەوێت، نەک چەند هەفتەیەک کار. |
| 3. Improved connection3. باشترکردنی پەیوەندی | Different systems — a website, a phone app, other companies — can connect and share data.سیستەمی جیاواز — ، مۆبایل، کۆمپانیای تر — دەتوانن پێکەوە ببەسترێن و ئاڵوگۆڕ بکەن. | A university website and its phone app read the same timetable from one API. زانکۆیەک و مۆبایلەکەی هەمان خشتەی وانەکان لە یەک دەخوێننەوە. |
| 4. Improved customer experience4. باشترکردنی ئەزموونی کڕیار | Users get useful features without leaving the site.بەکارهێنەران تایبەتمەندیی بەسوود وەردەگرن بەبێ ئەوەی جێبهێڵن. | A delivery site shows a live map of your order. گەیاندن نەخشەیەکی ڕاستەوخۆی داواکراوەکەت پیشان دەدات. |
| 5. Promoting marketing activities5. بەهێزکردنی چالاکیی بازاڕکردن | Companies share their services through APIs, so their products appear in many other places.کۆمپانیاکان خزمەتگوزارییەکانیان لە ڕێگەی بڵاو دەکەنەوە، بۆیە بەرهەمەکانیان لە زۆر شوێنی تردا دەردەکەون. | A shop posts every new product to social media automatically through the social network's API.فرۆشگایەک هەر بەرهەمێکی نوێ بە شێوەی خۆکار لە ڕێگەی تۆڕە کۆمەڵایەتییەکەوە پۆست دەکات. |
Web APIs: requests and responsesAPIی وێب: داواکاری و وەڵام
A web API is an API that you use over the web with — the same protocol your browser uses to load pages (see HTTP and the request cycle). The difference is who asks and what comes back: a browser asks for an HTML page for a person to read; your PHP program asks for data for a program to use, usually as .
وێب ئەو کە لە ڕێگەی وێبەوە بە بەکاری دەهێنیت — هەمان ئەو بۆ هێنانی پەڕەکان بەکاری دەهێنێت (بڕوانە HTTP و سووڕی داواکاری). جیاوازییەکە لەوەدایە کێ داوا دەکات و چی دەگەڕێتەوە: داوای پەڕەیەکی HTML دەکات بۆ ئەوەی مرۆڤ بیخوێنێتەوە؛ PHPیەکەت داوای دەکات بۆ ئەوەی بەکاری بهێنێت، زۆرجار وەک .
A program on a that other programs use over the network with : they send requests and get data back, often as . A web API is offered by a web service.
بەرنامەیەکە لەسەر کە بەرنامەکانی تر لە ڕێگەی ڕایەڵەوە و بە بەکاری دەهێنن: داواکاری دەنێرن و دراوە وەردەگرنەوە، زۆرجار بە شێوەی . APIـی وێب لەلایەن خزمەتگوزارییەکی وێبەوە پێشکەش دەکرێت.
A web API is a list of endpoints. Each endpoint is one that does one job. In this lecture we build and use this small API on XAMPP:
وێب لیستێکە لە . هەر یەک کە یەک کار دەکات. لەم وانەیەدا ئەم بچووکە لەسەر XAMPP دروست دەکەین و بەکاری دەهێنین:
| Method | Endpoint | What it doesچی دەکات |
|---|---|---|
GET | /api/students.php | Sends the list of all studentsلیستی هەموو خوێندکاران دەنێرێت |
GET | /api/students.php?id=2 | Sends one student (number 2)یەک خوێندکار دەنێرێت (ژمارە 2) |
POST | /api/add-student.php | Receives a new student as JSONخوێندکارێکی نوێ وەک JSON وەردەگرێت |
One of an that does one job, such as GET /api/students/5 to read student 5. An API is a collection of endpoints.
یەک کە یەک کار دەکات، وەک GET /api/students/5 بۆ خوێندنەوەی خوێندکاری ژمارە ٥. هەر APIـیەک لە کۆمەڵێک خاڵی کۆتایی پێکدێت.
Web APIs: requests and responsesAPIی وێب: داواکاری و وەڵام
A web API call, step by stepبانگکردنی APIـی وێب، هەنگاو بە هەنگاو
- The user opens your pageبەکارهێنەر پەڕەکەت دەکاتەوە
The browser sends a normal request for
client.phpto your server.ئاسایی بۆ
client.phpدەنێرێت بۆ . - PHP asks the APIPHP داوا لە API دەکات
While
client.phpruns, PHP itself sends an HTTP request to the API's endpoint, for example with cURL.لە کاتی کارکردنی
client.phpدا، خودی PHP HTTP بۆ دەنێرێت، بۆ نموونە بە cURL. - The API answersAPI وەڵام دەداتەوە
The API sends back a response: a status code (
200 OK) and a body with JSON data.دەگەڕێنێتەوە: (
200 OK) و لاشەیەک کە JSONی تێدایە. - PHP decodes the JSONPHP JSON دەگۆڕێت بۆ ڕیزەک
json_decode()turns the JSON text into a PHP array that your code can use.json_decode()دەقی JSON دەکات بە PHP کە کۆدەکەت دەتوانێت بەکاری بهێنێت. - Your page answers the browserپەڕەکەت وەڵامی تۆڕگەڕ دەداتەوە
Your page builds normal HTML from the data and sends it to the browser. The user never sees the JSON.
پەڕەکەت لە HTMLی ئاسایی دروست دەکات و دەینێرێت بۆ . هەرگیز JSONـەکە نابینێت.
Web APIs: requests and responsesAPIی وێب: داواکاری و وەڵام
What is inside an API request and response?ناوەڕۆکی داواکاری و وەڵامی API چییە؟
- Method — what you want to do:
GETreads data,POSTsends new data (you know both from forms). - URL — the endpoint, sometimes with a query string such as
?id=2. - Headers — extra information, for example
Accept: application/json(“please answer in JSON”) or a secret API key. - Body — the data you send with
POST, often JSON.
- — دەتەوێت چی بکەیت:
GETدەخوێنێتەوە،POSTنوێ دەنێرێت (هەردووکیانت لە دەناسیت). - — ، هەندێک جار لەگەڵ وەک
?id=2. - — زانیاریی زیادە، بۆ نموونە
Accept: application/json(«تکایە بە JSON وەڵام بدەرەوە») یان نهێنی. - لاشە — ئەو دراوەیەی بە
POSTدەینێریت، زۆرجار JSON.
GET /api/students.php?id=2 HTTP/1.1
Host: localhost
Accept: application/jsonHTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{"id":2,"name":"Shilan","department":"IT"}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
The status line: version, status code
200and the reasonOK.دێڕی دۆخ: وەشان،
200و هۆکاریOK.- Lineدێڕی 2
This header says the body is JSON, not HTML.
ئەم دەڵێت لاشەکە JSONـە، نەک HTML.
- Lineدێڕی 4
The body: the data itself.
لاشە: خودی .
Web APIs: requests and responsesAPIی وێب: داواکاری و وەڵام
Status codesکۆدەکانی دۆخ
| Status code | Meaningواتا | When an API sends it کەی دەینێرێت |
|---|---|---|
200 OK | Everything worked.هەموو شتێک سەرکەوتوو بوو. | You read data successfully. بە سەرکەوتوویی خوێندەوە. |
201 Created | Something new was created.شتێکی نوێ دروست کرا. | After a successful POST that added a record.دوای POSTـێکی سەرکەوتوو کە زیاد کرد. |
400 Bad Request | Your request is wrong. هەڵەیە. | A required field is missing or the JSON is broken. نییە یان JSONـەکە تێکچووە. |
401 Unauthorized | The API does not know who you are. نازانێت تۆ کێیت. | The API key is missing or wrong. نییە یان هەڵەیە. |
404 Not Found | The thing you asked for does not exist.ئەو شتەی داوات کرد بوونی نییە. | Student number 9 is not in the list.خوێندکاری ژمارە 9 لە لیستەکەدا نییە. |
405 Method Not Allowed | Wrong method for this endpoint. هەڵەیە بۆ ئەم . | You used GET where the API wants POST.GETـت بەکارهێنا لە شوێنێک کە POST دەوێت. |
429 Too Many Requests | You asked too often.زۆر جار داوات کرد. | You passed the limit of your plan; wait and try later.سنووری پلانەکەت تێپەڕاند؛ چاوەڕێ بکە و دواتر هەوڵ بدەرەوە. |
500 Internal Server Error | The API itself has a problem.خودی کێشەی هەیە. | A bug in the API's code; not your fault. لە کۆدی ؛ هەڵەی تۆ نییە. |
JSON: the language of APIsJSON: زمانی API
Most web APIs answer in JSON (JavaScript Object Notation). JSON is plain text, so it is easy to send over the internet and easy to read for people and programs. It was born in JavaScript, but today every language — PHP, Python, Java, C# — can read and write it. (Python's JSON tools are shown in JSON: the safer text format.)
زۆربەی وێب بە (JavaScript Object Notation) وەڵام دەدەنەوە. JSON دەقی سادەیە، بۆیە ئاسانە بە بنێردرێت و ئاسانە بۆ مرۆڤ و بیخوێننەوە. لە JavaScriptـدا لەدایک بوو، بەڵام ئەمڕۆ هەموو زمانێک — PHP، Python، Java، C# — دەتوانێت بیخوێنێتەوە و بینووسێت. (ئامرازەکانی JSON لە لە JSON: جۆرە دەقییە بێمەترسیترەکە پیشان دراون.)
A simple text format for data, made of { } objects with name–value pairs and [ ] lists. Almost every API uses it; PHP converts data with json_encode() and json_decode().
شێوازێکی دەقیی سادەیە بۆ دراوە، کە لە ئۆبجێکتی { } بە جووتە ناو و نرخەوە و لیستی [ ] پێکدێت. نزیکەی هەموو APIـیەک بەکاری دەهێنێت؛ PHP بە json_encode() و json_decode() دراوە دەگۆڕێت.
{
"id": 2,
"name": "Shilan",
"department": "IT",
"average": 87.5,
"graduated": false,
"phone": null,
"courses": ["PHP", "HTML", "SQL"]
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
{ }is a JSON object: a list of name–value pairs, like an associative array.{ }لە JSONـدا : لیستێک لە جووتی ناو و ، وەک .- Lineدێڕی 2-7
Each line is
"name": value, separated by commas. Values can be numbers, strings,true/falseornull.هەر دێڕێک
"name": valueـە و بە کۆما جیا کراونەتەوە. دەتوانن ژمارە، ،true/falseیانnullبن.- Lineدێڕی 8
[ ]is a JSON array: a list of values, like an indexed array. No comma after the last item.[ ]لە JSONـدا : لیستێک لە ، وەک . دوای کۆتا کۆما دانانرێت.
The rules of JSON
یاساکانی JSON
- Objects use curly braces
{ }; arrays use square brackets[ ]. - Names (keys) are always strings in double quotes:
"name". - Strings use double quotes only. Single quotes
'...'are not allowed. - Values can be: string, number,
true,false,null, an object or an array. - Items are separated by commas, with no comma after the last item.
- No comments are allowed inside JSON.
- کەوانەی
{ }بەکاردەهێنن؛ کەوانەی چوارگۆشە[ ]. - ناوەکان () هەمیشە لە نێوان جووتەگوتەدا:
"name". - تەنها جووتەگوتە بەکاردەهێنن. تاکەگوتە
'...'ڕێگەپێدراو نییە. - دەتوانن ئەمانە بن: ، ژمارە،
true،false،null، یان . - بە کۆما لە یەکتر جیا دەکرێنەوە و دوای کۆتا کۆما نییە.
- لە ناو JSONـدا ڕێگەپێدراو نین.
| JSON | PHP after json_decode($json, true)PHP دوای json_decode($json, true) | PHP after json_decode($json)PHP دوای json_decode($json) |
|---|---|---|
object {"a": 1} {"a": 1} | associative array ["a" => 1] ["a" => 1] | object of class stdClass: $obj->a stdClass: $obj->a |
array [1, 2] [1, 2] | indexed array [1, 2] [1, 2] | indexed array [1, 2] [1, 2] |
string "Aram" "Aram" | string | string |
number 21 / 87.5ژمارە 21 / 87.5 | int / floatint / float | int / floatint / float |
true / false | boolbool | boolbool |
null | null | null |
json_encode() and json_decode() are the two bridges between PHP and JSON.json_encode() و json_decode() دوو پردەکەی نێوان PHP و JSONـن.CêITThe JSON data types and the rules of JSON syntax, with objects, arrays and many small examples.
و یاساکانی ، لەگەڵ ، و زۆر نموونەی بچووک.
Plays only the chapters on JSON data types and JSON syntax (1:45-6:24).
تەنها بەشەکانی و پیشان دەدات (1:45 تا 6:24).
JSON in PHP: json_encode() and json_decode()JSON لە PHPـدا: json_encode() و json_decode()
PHP has two built-in functions for JSON. You never need to build JSON text by hand.
PHP دوو بۆ JSON هەیە. هەرگیز پێویست ناکات دەقی JSON بە دەست دروست بکەیت.
json_encode($value)turns a PHP value (usually an array) into a JSON string.json_decode($json)turns a JSON string back into PHP values.
json_encode($value)PHP (زۆرجار ) دەکات بە JSON.json_decode($json)JSON دەکاتەوە بە PHP.
JSON in PHP: json_encode() and json_decode()JSON لە PHPـدا: json_encode() و json_decode()
From PHP to JSON: json_encode()لە PHPـەوە بۆ JSON: json_encode()
<?php
$student = [
"name" => "Shilan",
"age" => 20,
"average" => 87.5,
"passed" => true,
"phone" => null,
"courses" => ["PHP", "HTML", "SQL"],
];
$json = json_encode($student);
echo $json;{"name":"Shilan","age":20,"average":87.5,"passed":true,"phone":null,"courses":["PHP","HTML","SQL"]}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-9
An associative array with six different kinds of value.
بە شەش جۆری جیاوازی .
- Lineدێڕی 11
json_encode()returns one string. Nothing is printed yet.json_encode()یەک دەگەڕێنێتەوە. هێشتا هیچ چاپ نەکراوە.- Lineدێڕی 12
Now the JSON text is printed. Look at
true,nulland the array[...]in the output.ئێستا دەقی JSON چاپ دەکرێت. سەیری
true،nullو[...]بکە لە .
These three flags (options) make JSON easier to read. To use more than one, put | between them:
ئەم سێ ئاڵایە (هەڵبژاردە) JSON ئاسانتر دەکەن بۆ خوێندنەوە. بۆ بەکارهێنانی زیاتر لە یەکێکیان، | بخەرە نێوانیانەوە:
JSON_PRETTY_PRINT— new lines and indentation, so people can read it.JSON_UNESCAPED_UNICODE— keeps Kurdish (and other non-English) letters as they are. Without it, every Kurdish letter becomes a code such as\u0628.JSON_UNESCAPED_SLASHES— writes/instead of\/in URLs.
JSON_PRETTY_PRINT— دێڕی نوێ و لە سەرەتای دێڕەکان، تا مرۆڤ بتوانێت بیخوێنێتەوە.JSON_UNESCAPED_UNICODE— پیتە کوردییەکان (و پیتی هەر زمانێکی تر جگە لە ئینگلیزی) وەک خۆیان دەهێڵێتەوە. بەبێ ئەمە، هەر پیتێکی کوردی دەبێتە کۆدێک وەک\u0628.JSON_UNESCAPED_SLASHES— لە/دەنووسێت لە جیاتی\/.
<?php
$message = [
"city" => "Hewlêr",
"greeting" => "بەخێربێیت",
"url" => "https://example.com/api",
];
echo json_encode($message);
echo "\n\n";
echo json_encode($message, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);{"city":"Hewl\u00ear","greeting":"\u0628\u06d5\u062e\u06ce\u0631\u0628\u06ce\u06cc\u062a","url":"https:\/\/example.com\/api"}
{
"city": "Hewlêr",
"greeting": "بەخێربێیت",
"url": "https://example.com/api"
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
Without flags: Kurdish letters become
\u...codes and/becomes\/.بەبێ ئاڵا: پیتە کوردییەکان دەبنە کۆدی
\u...و/دەبێتە\/.- Lineدێڕی 10
With the three flags: readable lines, real Kurdish letters, normal slashes.
بە هەر سێ ئاڵاکە: دێڕی خوێندراو، پیتی کوردیی ڕاستەقینە و هێڵی لاری ئاسایی.
Be careful with indexed arrays whose keys do not start at 0. JSON arrays have no keys, so PHP turns such an array into a JSON object. array_values() renumbers the keys from 0:
ئاگاداربە: ئەگەر لە 0ـەوە دەست پێنەکات، PHP ئەو دەکات بە JSON، چونکە JSON نییە. array_values() لە 0ـەوە دووبارە ژمارە دەکاتەوە:
<?php
$names = [1 => "Aram", 2 => "Shilan"]; // keys do not start at 0
echo json_encode($names) . "\n"; // becomes a JSON object
echo json_encode(array_values($names)) . "\n"; // keys 0, 1 ... becomes a JSON array{"1":"Aram","2":"Shilan"}
["Aram","Shilan"]
JSON in PHP: json_encode() and json_decode()JSON لە PHPـدا: json_encode() و json_decode()
From JSON to PHP: json_decode()لە JSONـەوە بۆ PHP: json_decode()
json_decode() has a second argument that you should remember. Without it you get an object, and you read its parts with ->. With true you get an associative array, and you read it with ["..."] as you learned in Arrays. Most beginners prefer arrays.
json_decode() دووەمی هەیە کە دەبێت لەبیرت بێت. بەبێ ئەو وەردەگریت و بەشەکانی بە -> دەخوێنیتەوە. بە true وەردەگریت و بە ["..."] دەیخوێنیتەوە وەک لە ڕیزەکەکان فێر بوویت. زۆربەی سەرەتاکاران پێ باشترە.
<?php
$json = '{"name": "Karwan", "city": "Duhok", "marks": [90, 85, 77]}';
// 1. Without true: you get an object
$obj = json_decode($json);
echo $obj->name . "\n";
echo $obj->marks[0] . "\n";
// 2. With true: you get an associative array
$arr = json_decode($json, true);
echo $arr["city"] . "\n";
echo count($arr["marks"]) . " marks, average " . array_sum($arr["marks"]) / count($arr["marks"]);Karwan 90 Duhok 3 marks, average 84
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
The JSON text is inside single quotes, so the double quotes inside it need no backslash in front of them.
دەقی JSON لە ناو تاکەگوتەدایە، بۆیە جووتەگوتەکانی ناوەوەی پێویستیان بە (backslash) نییە لە پێشیانەوە.
- Lineدێڕی 5-7
Without
true: an object.$obj->namereads the name;$obj->marksis still a normal array.بەبێ
true: .$obj->nameناوەکە دەخوێنێتەوە؛$obj->marksهێشتا ئاساییە.- Lineدێڕی 10-12
With
true: an associative array, socount()andarray_sum()work as usual. 252 / 3 = 84.بە
true: ، بۆیەcount()وarray_sum()وەک هەمیشە کار دەکەن. 252 / 3 = 84.
JSON in PHP: json_encode() and json_decode()JSON لە PHPـدا: json_encode() و json_decode()
When the JSON is brokenکاتێک JSONـەکە تێکچووە
If the text is not valid JSON, json_decode() does not stop your script. It quietly returns null. So always check the result. There are three ways:
ئەگەر دەقەکە JSONـی دروست نەبێت، json_decode() ڕاناگرێت. بە بێدەنگی null دەگەڕێنێتەوە. بۆیە هەمیشە ئەنجامەکە بپشکنە. سێ ڕێگا هەیە:
<?php
$bad = "{'name': 'Hana',}"; // single quotes and a trailing comma: NOT valid JSON
// Way 1: check for null, then ask why
$data = json_decode($bad, true);
var_dump($data);
echo json_last_error_msg() . "\n";
// Way 2: let PHP throw an exception
try {
$data = json_decode($bad, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "Bad JSON: " . $e->getMessage() . "\n";
}
// Way 3 (PHP 8.3+): only check, do not decode
var_dump(json_validate('{"name": "Hana"}'));
var_dump(json_validate($bad));NULL Syntax error Bad JSON: Syntax error bool(true) bool(false)
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Two mistakes: single quotes and a comma after the last item.
دوو هەڵەی تێدایە: تاکەگوتە و کۆمایەک دوای کۆتا .
- Lineدێڕی 5-7
Way 1: the result is
NULL;json_last_error_msg()explains why.ڕێگای 1: ئەنجامەکە
NULLـە؛json_last_error_msg()هۆکارەکەی ڕوون دەکاتەوە.- Lineدێڕی 10-14
Way 2: with
JSON_THROW_ON_ERROR, bad JSON throws aJsonExceptionthat you catch withtry/catch.ڕێگای 2: بە
JSON_THROW_ON_ERROR، JSONـی خراپJsonExceptionفڕێ دەدات کە بەtry/catchدەیگریت.- Lineدێڕی 17-18
Way 3:
json_validate()(PHP 8.3 and newer) only answers true or false.ڕێگای 3:
json_validate()(PHP 8.3 و نوێتر) تەنها true یان false دەگەڕێنێتەوە.
Build your own JSON API in PHPAPIـیەکی JSONـی خۆت بە PHP دروست بکە
Any PHP page can be an API. Instead of printing HTML for people, it prints JSON for programs and says so in a header. Save this file as C:\xampp\htdocs\api\students.php:
هەر پەڕەیەکی PHP دەتوانێت بێت. لە جیاتی چاپکردنی HTML بۆ مرۆڤ، JSON بۆ چاپ دەکات و لە ئەمە ڕادەگەیەنێت. ئەم بە ناوی C:\xampp\htdocs\api\students.php پاشەکەوت بکە:
<?php
// api/students.php - a tiny read-only JSON API
header("Content-Type: application/json; charset=utf-8");
// In a real project these rows would come from a database.
$students = [
1 => ["id" => 1, "name" => "Aram", "department" => "IT"],
2 => ["id" => 2, "name" => "Shilan", "department" => "IT"],
3 => ["id" => 3, "name" => "Rezan", "department" => "Networks"],
];
// No id in the URL: send the whole list
if (!isset($_GET["id"])) {
echo json_encode(array_values($students));
exit;
}
$id = (int) $_GET["id"];
// Unknown id: answer with status 404 and an error message
if (!isset($students[$id])) {
http_response_code(404);
echo json_encode(["error" => "Student not found"]);
exit;
}
echo json_encode($students[$id]);Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Tell the client that the body is JSON. Like every
header(), it must come before any output.بە بڵێ لاشەکە JSONـە. وەک هەموو
header()ـێک، دەبێت پێش هەر بێت.- Lineدێڕی 6-10
The data. Here it is a fixed array; in a real project you would
SELECTit from the database.. لێرەدا جێگیرە؛ لە پڕۆژەیەکی ڕاستەقینەدا لە بە
SELECTدەیهێنیت.- Lineدێڕی 13-16
No
idin the URL: send the whole list.array_values()makes sure it becomes a JSON array[...].هیچ
idـێک لە نییە: هەموو لیستەکە بنێرە.array_values()دڵنیا دەبێتەوە کە دەبێتە JSON[...].- Lineدێڕی 18
(int)turns the text from the URL into a whole number, so strange input such as2abccannot cause trouble.(int)دەقەکەی دەکات بە ، بۆیە نێوخستەی سەیر وەک2abcناتوانێت کێشە دروست بکات.- Lineدێڕی 21-25
Unknown id: status
404and a JSON error message, then stop.id-ـی نەناسراو: دۆخی
404و پەیامێکی JSON، پاشان بوەستە.- Lineدێڕی 27
Found: send that one student.
دۆزرایەوە: تەنها ئەو خوێندکارە بنێرە.
Start Apache in XAMPP and open these three URLs in your browser. This is what each one returns:
Apache لە XAMPPـدا دەست پێبکە و ئەم سێ لە بکەرەوە. ئەمە ئەوەیە کە هەر یەکەیان دەیگەڕێنێتەوە:
[{"id":1,"name":"Aram","department":"IT"},{"id":2,"name":"Shilan","department":"IT"},{"id":3,"name":"Rezan","department":"Networks"}]Status 200: the whole list as a JSON array.
دۆخی 200: هەموو لیستەکە وەک JSON.
{"id":2,"name":"Shilan","department":"IT"}Status 200: one JSON object.
دۆخی 200: یەک JSON.
{"error":"Student not found"}Status 404: an error message as JSON.
دۆخی 404: پەیامی وەک JSON.
Build your own JSON API in PHPAPIـیەکی JSONـی خۆت بە PHP دروست بکە
Receiving JSON with POSTوەرگرتنی JSON بە POST
An API can also receive data. A client sends JSON in the body of a POST request. This is different from a normal form: the data is not in $_POST. You read the raw body with file_get_contents("php://input") and decode it yourself:
دەتوانێت وەربگرێت. JSON لە لاشەی POSTـدا دەنێرێت. ئەمە جیاوازە لە ئاسایی: لە $_POSTـدا نییە. لاشە خاوەکە بە file_get_contents("php://input") دەخوێنیتەوە و خۆت دەیکەیتەوە (decode):
<?php
// api/add-student.php - receives a new student as JSON (POST)
header("Content-Type: application/json; charset=utf-8");
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
http_response_code(405); // 405 = Method Not Allowed
echo json_encode(["error" => "Use POST"]);
exit;
}
$raw = file_get_contents("php://input"); // the raw request body
$data = json_decode($raw, true);
// Read each field, then remove extra spaces (like form data)
$name = trim($data["name"] ?? "");
$department = trim($data["department"] ?? "");
if ($name === "" || $department === "") {
http_response_code(400); // 400 = Bad Request
echo json_encode(["error" => "name and department are required"]);
exit;
}
// (Here you would INSERT the student with a prepared statement.)
$newId = 4;
http_response_code(201); // 201 = Created
echo json_encode(["id" => $newId, "name" => $name, "department" => $department]);Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-9
This endpoint accepts only
POST. Anything else gets405 Method Not Allowed.ئەم تەنها
POSTوەردەگرێت. هەر شتێکی تر405 Method Not Allowedوەردەگرێت.- Lineدێڕی 11
php://inputis the raw body of the request — here, the JSON text.php://inputلاشە خاوەکەی — لێرەدا، دەقی JSONـەکە.- Lineدێڕی 14-16
Read each field with
?? ""(empty text when it is missing or the JSON is broken), then remove extra spaces withtrim(), as you do with form data.هەر خانەیەک بە
?? ""بخوێنەوە ( بەتاڵ ئەگەر نەبێت یان JSONـەکە تێکچووبێت)، پاشان بەtrim()زیادەکان لاببە، وەک ئەوەی لەگەڵ دەیکەیت.- Lineدێڕی 18-22
Treat API input like form input: check it, and answer
400 Bad Requestwhen something is missing. Becausetrim()ran first, a name made only of spaces is refused too.مامەڵە لەگەڵ نێوخستەی بکە وەک : بیپشکنە و ئەگەر شتێک کەم بوو بە
400 Bad Requestوەڵام بدەرەوە. چونکە سەرەتاtrim()جێبەجێ کرا، ناوێک کە تەنها بێت ڕەتیش دەکرێتەوە.- Lineدێڕی 24-25
In a real API you would save the student here with a prepared statement (see Database security).
لە ڕاستەقینەدا لێرەدا خوێندکارەکە بە پاشەکەوت دەکەیت (بڕوانە ئاسایشی بنکەدراوە).
- Lineدێڕی 27-28
Success:
201 Createdand the new student as JSON.سەرکەوتن:
201 Createdو خوێندکارە نوێیەکە وەک JSON.
| Request body sent by the clientلاشەی کە دەینێرێت | Statusدۆخ | Response bodyلاشەی |
|---|---|---|
{"name": " Dilan ", "department": "IT"} | 201 | {"id":4,"name":"Dilan","department":"IT"} |
{"name": "Dilan"} | 400 | {"error":"name and department are required"} |
{"name": " ", "department": "IT"} | 400 | {"error":"name and department are required"} |
a GET request (no body) GET (بێ لاشە) | 405 | {"error":"Use POST"} |
Calling an API from PHPبانگکردنی API لە PHPـەوە
Now let a second page use the API. PHP has two common ways to send an HTTP request: the simple file_get_contents() and the more powerful cURL extension. Both run on the server, so the user's browser never sees the API or its key.
ئێستا با پەڕەیەکی دووەم بەکاربهێنێت. PHP دوو ڕێگای باوی هەیە بۆ ناردنی HTTP: file_get_contents()ـی سادە و cURLـی بەهێزتر. هەردووکیان لەسەر کار دەکەن، بۆیە هەرگیز یان کلیلەکەی نابینێت.
How PHP sends a request to a web API, first with file_get_contents() and then with cURL, using a free test API.
چۆن بۆ وێب دەنێرێت، سەرەتا بە file_get_contents() و پاشان بە cURL، بە بەکارهێنانی خۆڕایی بۆ تاقیکردنەوە.
Plays only the file_get_contents() and cURL chapters (0:38-14:22); Guzzle and SDKs are skipped.
تەنها بەشەکانی file_get_contents() و cURL پیشان دەدات (0:38 تا 14:22)؛ Guzzle و SDK بەجێ دەهێڵرێن.
Calling an API from PHPبانگکردنی API لە PHPـەوە
The simple way: file_get_contents()ڕێگای سادە: file_get_contents()
file_get_contents() reads a whole file into a string. Give it a URL instead of a file name, and it downloads that URL. This needs the php.ini setting allow_url_fopen = On, which is the default in XAMPP.
file_get_contents() هەموو دەخوێنێتەوە بۆ ناو . ئەگەر بدەیتێ لە جیاتی ناوی ، ئەو دادەبەزێنێت. ئەمە پێویستی بە allow_url_fopen = On لە php.iniـدا هەیە، کە لە XAMPPـدا بە شێوەی بنەڕەتی هەڵکراوە.
<?php
// client.php - asks our API for student 2
$url = "http://localhost/api/students.php?id=2";
// Wait at most 10 seconds for the answer
$context = stream_context_create(["http" => ["timeout" => 10]]);
$json = file_get_contents($url, false, $context);
if ($json === false) {
exit("Could not reach the API.");
}
$student = json_decode($json, true);
if (!is_array($student)) {
exit("The API did not send valid JSON.");
}
echo "<p>" . htmlspecialchars($student["name"]) . " studies in the "
. htmlspecialchars($student["department"]) . " department.</p>";Shilan studies in the IT department.
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<p>Shilan studies in the IT department.</p>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5-6
A timeout: wait at most 10 seconds, so your page does not hang if the API is slow.
ماوەی چاوەڕوانی: زۆرترین 10 چرکە چاوەڕێ بکە، تا پەڕەکەت ڕانەوەستێت ئەگەر خاو بوو.
- Lineدێڕی 7
Send the request and get the whole body as a string.
بنێرە و هەموو لاشەکە وەک وەربگرە.
- Lineدێڕی 9-11
falsemeans the API could not be reached (or it answered with an error status).falseواتە نەتوانرا بگەیتە (یان بە دۆخێکی وەڵامی دایەوە).- Lineدێڕی 13-16
Decode and check that you really got an array.
بیکەرەوە (decode) و دڵنیابە کە بە ڕاستی وەرگرتووە.
- Lineدێڕی 18-19
Data from an API is input from outside. Escape it with
htmlspecialchars()before you put it in HTML.نێوخستەیە لە دەرەوە. پێش ئەوەی بیخەیتە ناو HTML بە
htmlspecialchars()پارێزراوی بکە.
Calling an API from PHPبانگکردنی API لە PHPـەوە
The full way: cURLڕێگای تەواو: cURL
cURL (“client URL”) is a PHP extension for talking to servers. It lets you set a timeout, send headers and a body, and read the status code. In XAMPP it is normally switched on (extension=curl in php.ini). The pattern is always the same: init → set options → exec → check.
cURL («client URL») PHPـیە بۆ قسەکردن لەگەڵ . ڕێگەت دەدات ماوەی چاوەڕوانی دیاری بکەیت، و لاشە بنێریت و بخوێنیتەوە. لە XAMPPـدا زۆرجار هەڵکراوە (extension=curl لە php.iniـدا). شێوازەکە هەمیشە هەمانە: init ← دانانی هەڵبژاردەکان ← exec ← پشکنین.
<?php
// client-curl.php - the same request with cURL
$url = "http://localhost/api/students.php?id=2";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the body as a string
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // give up after 10 seconds
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Accept: application/json"]);
$body = curl_exec($ch);
if ($body === false) {
exit("Request failed: " . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
exit("The API answered with status $status.");
}
$student = json_decode($body, true);
echo "<p>" . htmlspecialchars($student["name"]) . " studies in the "
. htmlspecialchars($student["department"]) . " department.</p>";Shilan studies in the IT department.
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<p>Shilan studies in the IT department.</p>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
curl_init()creates a cURL handle for one URL.curl_init()دەستکەوتێکی (handle) cURL بۆ یەک دروست دەکات.- Lineدێڕی 6
Without
CURLOPT_RETURNTRANSFER, cURL would print the body directly. With it,curl_exec()returns the body as a string.بەبێ
CURLOPT_RETURNTRANSFER، cURL لاشەکە ڕاستەوخۆ چاپ دەکات. بە ئەمە،curl_exec()لاشەکە وەک دەگەڕێنێتەوە.- Lineدێڕی 7
Give up after 10 seconds.
دوای 10 چرکە واز بهێنە.
- Lineدێڕی 8
Send a header: we would like JSON.
بنێرە: JSONمان دەوێت.
- Lineدێڕی 10
Send the request now.
ئێستا بنێرە.
- Lineدێڕی 12-14
falsemeans a network problem (no connection, timeout).curl_error()tells you what happened.falseواتە کێشەی (پەیوەندی نییە، کات تەواو بوو).curl_error()پێت دەڵێت چی ڕوویدا.- Lineدێڕی 16-19
The API answered, but maybe not with 200. Check the status code before you trust the body.
وەڵامی دایەوە، بەڵام لەوانەیە بە 200 نەبێت. پێش ئەوەی متمانە بە لاشەکە بکەیت بپشکنە.
Calling an API from PHPبانگکردنی API لە PHPـەوە
Sending JSON with cURLناردنی JSON بە cURL
To send data, add three options: CURLOPT_POST, the JSON body in CURLOPT_POSTFIELDS, and a Content-Type header that says the body is JSON. This client talks to add-student.php from above:
بۆ ناردنی ، سێ هەڵبژاردە زیاد بکە: CURLOPT_POST، لاشەی JSON لە CURLOPT_POSTFIELDSـدا و Content-Type کە دەڵێت لاشەکە JSONـە. ئەم لەگەڵ add-student.phpـی سەرەوە قسە دەکات:
<?php
// Send a new student to the API as JSON
$newStudent = ["name" => "Dilan", "department" => "IT"];
$ch = curl_init("http://localhost/api/add-student.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($newStudent));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false) {
exit("Request failed: " . curl_error($ch));
}
echo "Status: $status\n";
echo "Answer: $body\n";Status: 201
Answer: {"id":4,"name":"Dilan","department":"IT"}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
A normal PHP array…
ئاسایی PHP…
- Lineدێڕی 9
…becomes the JSON body with
json_encode().…بە
json_encode()دەبێتە لاشەی JSON.- Lineدێڕی 10
Tell the API what kind of body it receives.
بە بڵێ چ جۆرە لاشەیەک وەردەگرێت.
Calling an API from PHPبانگکردنی API لە PHPـەوە
API keysکلیلەکانی API
Most public APIs want to know who is calling, so they give you an API key when you sign up on their website. You send the key with every request. The API's documentation tells you where: usually in a header (for example Authorization: Bearer YOUR_KEY or X-API-Key: YOUR_KEY) and sometimes in the URL (?key=YOUR_KEY).
زۆربەی گشتییەکان دەیانەوێت بزانن کێ بانگیان دەکات، بۆیە کاتێک لە خۆت تۆمار دەکەیت دەدەنێ. کلیلەکە لەگەڵ هەموو دەنێریت. پێت دەڵێت لە کوێ: زۆرجار لە (بۆ نموونە Authorization: Bearer YOUR_KEY یان X-API-Key: YOUR_KEY) و هەندێک جار لە (?key=YOUR_KEY).
A long secret code that an gives you. You send it with every so the API knows who is asking. Keep it on the : never put it in HTML, JavaScript or a public code repository.
کۆدێکی نهێنیی درێژە کە پێت دەدات. لەگەڵ هەموو دەینێریت تا API بزانێت کێ داوا دەکات. لەسەر بیهێڵەرەوە: هەرگیز مەیخە ناو HTML، JavaScript یان کۆگایەکی گشتیی کۆد.
<?php
// config.php - keep this file OUTSIDE htdocs and out of Git
const WEATHER_API_KEY = "paste-your-own-key-here";<?php
// weather.php - calls an API that needs a key
require __DIR__ . "/../config.php"; // config.php is one folder ABOVE htdocs
$ch = curl_init("https://api.example.com/v1/weather?city=Slemani");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Accept: application/json",
"Authorization: Bearer " . WEATHER_API_KEY,
]);
$body = curl_exec($ch);Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Load the key from a file that is not inside
htdocs, so nobody can open it in a browser.کلیلەکە لە بهێنە کە لە ناو
htdocsـدا نییە، تا کەس نەتوانێت لە بیکاتەوە.- Lineدێڕی 5
api.example.comis only an example name: use the real address from your API's documentation.api.example.comناوێکی نموونەییە: ناونیشانە ڕاستەقینەکە لە وەربگرە.- Lineدێڕی 10
The key travels in a header, on the server, over HTTPS.
کلیلەکە لە دەڕوات، لەسەر ، بە .
Using APIs safelyبەکارهێنانی API بە سەلامەتی
APIs connect your site to the outside world, so the security rules you learned for forms and databases apply here too.
بە جیهانی دەرەوە دەبەستێتەوە، بۆیە ئەو یاسایانەی کە بۆ و فێریان بوویت، لێرەش جێبەجێ دەبن.
- Keep API keys secret. Use them only in PHP on the server. Never put a key in HTML or JavaScript (anyone can read the page source), and never upload it to GitHub. If a key leaks, delete it in the API's dashboard and make a new one.
- Use HTTPS for real APIs, so the data and your key are encrypted on the way. (
http://localhostis only for practice on your own computer.) - Expect failure. Set a timeout, check for
false, check the status code, and show a friendly message when the API is down. When you get429 Too Many Requests, wait before you try again. - Do not trust API data. Treat it like user input: check it, and escape it with
htmlspecialchars()before printing (see Form security). A hacked or buggy API could send HTML or JavaScript. - In your own API: validate every input, use prepared statements for the database (see Database security), send the right status codes, and never send passwords or private data.
- Respect the rules of the API: its terms of use and its limits. Send personal data to an API only when it is really needed.
- بە نهێنی بهێڵەرەوە. تەنها لە PHPـدا لەسەر بەکاریان بهێنە. هەرگیز کلیل مەخەرە ناو HTML یان JavaScript (هەر کەسێک دەتوانێت پەڕەکە بخوێنێتەوە) و هەرگیز بۆ GitHub بەرزی مەکەرەوە. ئەگەر کلیلێک ئاشکرا بوو، لە داشبۆردی بیسڕەوە و یەکێکی نوێ دروست بکە.
- بەکاربهێنە بۆ ڕاستەقینە، تا و کلیلەکەت لە ڕێگادا بە بپارێزرێن. (
http://localhostتەنها بۆ ڕاهێنانە لەسەر کۆمپیوتەرەکەی خۆت.) - چاوەڕێی شکست بکە. ماوەی چاوەڕوانی دابنێ،
falseبپشکنە، بپشکنە و کاتێک کار ناکات پەیامێکی دۆستانە پیشان بدە. کاتێک429 Too Many Requestsوەردەگریت، پێش هەوڵدانەوە چاوەڕێ بکە. - متمانە بە مەکە. وەک مامەڵەی لەگەڵ بکە: بیپشکنە و پێش چاپکردن بە
htmlspecialchars()پارێزراوی بکە (بڕوانە ئاسایشی فۆرم). هاککراو یان پڕ لە دەتوانێت HTML یان JavaScript بنێرێت. - لە خۆتدا: هەموو نێوخستەیەک بکە، بۆ بەکاربهێنە (بڕوانە ئاسایشی بنکەدراوە)، دروست بنێرە و هەرگیز یان تایبەتی مەنێرە.
- ڕێز لە یاساکانی بگرە: مەرجەکانی بەکارهێنان و سنوورەکانی. کەسی تەنها کاتێک بۆ بنێرە کە بە ڕاستی پێویست بێت.
Extra: REST APIsزیادە: APIی REST
Common mistakesهەڵە باوەکان
1. Using an object as if it were an array
1. بەکارهێنانی ئۆبجێکت وەک ئەوەی ڕیزەک بێت
Without true, json_decode() returns an object. Square brackets then stop the script:
بەبێ true، json_decode() دەگەڕێنێتەوە. ئەوکات کەوانەی چوارگۆشە دەوەستێنێت:
<?php
$data = json_decode('{"name": "Soran"}'); // no true: $data is an object
echo $data["name"];
Fatal error: Uncaught Error: Cannot use object of type stdClass as array in C:\xampp\htdocs\object-as-array.php:3
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\object-as-array.php on line 3
Fix: write json_decode($json, true) and use $data["name"], or keep the object and write $data->name.
چارەسەر: json_decode($json, true) بنووسە و $data["name"] بەکاربهێنە، یان بهێڵەرەوە و $data->name بنووسە.
2. More mistakes to avoid
2. هەڵەی تر کە دەبێت خۆتیان لێ بپارێزیت
- Writing JSON by hand. Single quotes, a missing quote or an extra comma make it invalid, and
json_decode()returnsnull. Build a PHP array and calljson_encode()instead. - Printing an array with
echo.echo $students;prints only the wordArrayand a warning (try it in the output challenge). Useecho json_encode($students);. - Output before the JSON. HTML, empty lines before
<?phpor a PHP warning in your API break the JSON for the client, andheader()fails with “headers already sent”. - Not checking the answer. Always check for
false(no connection), the status code andnull(bad JSON) before you use the data. - Kurdish text turns into
\u06d5.... That is still correct JSON, but people cannot read it. AddJSON_UNESCAPED_UNICODE. - Putting the API key in JavaScript or in a public repository. Anyone can copy it and use your account. Keep it in PHP on the server.
- نووسینی JSON بە دەست. تاکەگوتە، گوتەیەکی کەم یان کۆمایەکی زیادە نادروستی دەکەن و
json_decode()nullدەگەڕێنێتەوە. لە جیاتی ئەوە PHP دروست بکە وjson_encode()بانگ بکە. - چاپکردنی بە
echo.echo $students;تەنها وشەیArrayو چاپ دەکات (لە تەحەدای دەرخستەدا تاقی بکەرەوە).echo json_encode($students);بەکاربهێنە. - پێش JSONـەکە. HTML، دێڕی بەتاڵ پێش
<?phpیان PHP لە JSONـەکە بۆ تێکدەدەن وheader()بە «headers already sent» شکست دەهێنێت. - نەپشکنینی وەڵامدانەوەکە. هەمیشە پێش بەکارهێنانی
false(پەیوەندی نییە)، وnull(JSONـی خراپ) بپشکنە. - دەقی کوردی دەبێتە
\u06d5.... ئەمە هێشتا JSONـی دروستە، بەڵام مرۆڤ ناتوانێت بیخوێنێتەوە.JSON_UNESCAPED_UNICODEزیاد بکە. - دانانی لە JavaScriptـدا یان لە کۆگایەکی گشتیدا. هەر کەسێک دەتوانێت کۆپی بکات و هەژمارەکەت بەکاربهێنێت. لە PHPـدا لەسەر بیهێڵەرەوە.
Exercisesڕاهێنانەکان
Make an array of three products. Each product has a name, a price (in dinars) and inStock (true or false). Print the array as readable JSON.
بە سێ بەرهەمەوە دروست بکە. هەر بەرهەمێک name، price (بە دینار) و inStock (true یان false)ـی هەیە. وەک JSONـی خوێندراو چاپ بکە.
Hintئاماژە
Use an indexed array of associative arrays, then json_encode($products, JSON_PRETTY_PRINT).
لە بەکاربهێنە، پاشان json_encode($products, JSON_PRETTY_PRINT).
Show answerوەڵامەکە پیشان بدە
<?php
$products = [
["name" => "Notebook", "price" => 1500, "inStock" => true],
["name" => "Pen", "price" => 250, "inStock" => true],
["name" => "Bag", "price" => 12000, "inStock" => false],
];
echo json_encode($products, JSON_PRETTY_PRINT);[
{
"name": "Notebook",
"price": 1500,
"inStock": true
},
{
"name": "Pen",
"price": 250,
"inStock": true
},
{
"name": "Bag",
"price": 12000,
"inStock": false
}
]JSON_PRETTY_PRINT adds the new lines. Notice that true/false stay booleans, not strings.
JSON_PRETTY_PRINT دێڕە نوێیەکان زیاد دەکات. سەرنج بدە کە true/false وەک دەمێننەوە، نەک .
You receive this JSON from an API: a list of cities, each with a name and a province. Decode it and print an HTML list (<ul>) with one <li> per city, for example Slemani (Sulaymaniyah). Stop with a message if the JSON is invalid.
ئەم JSONـە لە وەردەگریت: لیستێک لە شارەکان، هەر یەکەیان name و provinceـی هەیە. بیکەرەوە (decode) و لیستێکی HTML (<ul>) چاپ بکە بە یەک <li> بۆ هەر شارێک، بۆ نموونە Slemani (Sulaymaniyah). ئەگەر JSONـەکە نادروست بوو بە پەیامێک بوەستە.
[
{"name": "Slemani", "province": "Sulaymaniyah"},
{"name": "Hewlêr", "province": "Erbil"},
{"name": "Duhok", "province": "Duhok"}
]Show answerوەڵامەکە پیشان بدە
<?php
$json = '[
{"name": "Slemani", "province": "Sulaymaniyah"},
{"name": "Hewlêr", "province": "Erbil"},
{"name": "Duhok", "province": "Duhok"}
]';
$cities = json_decode($json, true);
if (!is_array($cities)) {
exit("Invalid JSON");
}
echo "<ul>\n";
foreach ($cities as $city) {
echo " <li>" . htmlspecialchars($city["name"]) . " ("
. htmlspecialchars($city["province"]) . ")</li>\n";
}
echo "</ul>";• Slemani (Sulaymaniyah) • Hewlêr (Erbil) • Duhok (Duhok)
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<ul>
<li>Slemani (Sulaymaniyah)</li>
<li>Hewlêr (Erbil)</li>
<li>Duhok (Duhok)</li>
</ul>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
true: we want arrays.true: دەوێت.- Lineدێڕی 10-12
Stop if decoding failed.
ئەگەر کردنەوەکە شکستی هێنا بوەستە.
- Lineدێڕی 16-17
Escape every value from outside before printing.
هەر لە دەرەوە هاتبێت پێش چاپکردن پارێزراوی بکە.
Change students.php so that students.php?department=IT returns only the students of that department. Without the parameter it returns everybody. An unknown department returns an empty JSON array [].
students.php بگۆڕە بە شێوەیەک کە students.php?department=IT تەنها خوێندکارانی ئەو بەشە بگەڕێنێتەوە. بەبێ هەمووان دەگەڕێنێتەوە. بەشێکی نەناسراو بەتاڵی JSON [] دەگەڕێنێتەوە.
Hintئاماژە
Loop over the students and copy the matching ones into a new array.
بە بەسەر خوێندکاراندا بڕۆ و ئەوانەی یەک دەگرنەوە کۆپی بکە بۆ نوێ.
Show answerوەڵامەکە پیشان بدە
<?php
// api/students.php with a department filter: students.php?department=IT
header("Content-Type: application/json; charset=utf-8");
$students = [
["id" => 1, "name" => "Aram", "department" => "IT"],
["id" => 2, "name" => "Shilan", "department" => "IT"],
["id" => 3, "name" => "Rezan", "department" => "Networks"],
];
if (isset($_GET["department"])) {
$wanted = $_GET["department"];
$result = [];
foreach ($students as $s) {
if ($s["department"] === $wanted) {
$result[] = $s;
}
}
echo json_encode($result);
} else {
echo json_encode($students);
}[{"id":1,"name":"Aram","department":"IT"},{"id":2,"name":"Shilan","department":"IT"}][]
Exercisesڕاهێنانەکان
More exercisesڕاهێنانی زیاتر
Write table.php. It calls http://localhost/api/students.php with cURL and shows all students in an HTML table with the columns ID, Name and Department.
table.php بنووسە. بە cURL http://localhost/api/students.php بانگ دەکات و هەموو خوێندکاران لە پیشان دەدات بە ID، Name و Department.
Show answerوەڵامەکە پیشان بدە
<?php
// table.php - shows all students from our API in an HTML table
$ch = curl_init("http://localhost/api/students.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$body = curl_exec($ch);
if ($body === false) {
exit("Request failed: " . curl_error($ch));
}
$students = json_decode($body, true);
if (!is_array($students)) {
exit("The API did not send valid JSON.");
}
echo "<table border=\"1\">\n";
echo "<tr><th>ID</th><th>Name</th><th>Department</th></tr>\n";
foreach ($students as $s) {
echo "<tr><td>" . (int) $s["id"] . "</td><td>" . htmlspecialchars($s["name"])
. "</td><td>" . htmlspecialchars($s["department"]) . "</td></tr>\n";
}
echo "</table>";ID | Name | Department 1 | Aram | IT 2 | Shilan | IT 3 | Rezan | Networks
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<table border="1">
<tr><th>ID</th><th>Name</th><th>Department</th></tr>
<tr><td>1</td><td>Aram</td><td>IT</td></tr>
<tr><td>2</td><td>Shilan</td><td>IT</td></tr>
<tr><td>3</td><td>Rezan</td><td>Networks</td></tr>
</table>For each situation, say which HTTP method the client uses and which status code a good API answers with: (a) read product 7, which exists; (b) add a new product; (c) read product 999, which does not exist; (d) a request without the required API key; (e) a script sends 1000 requests in one minute and passes the limit.
بۆ هەر دۆخێک، بڵێ کام بەکاردەهێنێت و باش بە کام وەڵام دەداتەوە: (أ) خوێندنەوەی بەرهەمی 7، کە هەیە؛ (ب) زیادکردنی بەرهەمێکی نوێ؛ (ج) خوێندنەوەی بەرهەمی 999، کە نییە؛ (د) بەبێ پێویست؛ (هـ) لە یەک خولەکدا 1000 دەنێرێت و سنوورەکە تێدەپەڕێنێت.
Show answerوەڵامەکە پیشان بدە
| Situationدۆخ | Method | Status code |
|---|---|---|
| (a) | GET | 200 OK |
| (b) | POST | 201 Created |
| (c) | GET | 404 Not Found |
| (d) | the method of that request (for example GET) ئەو (بۆ نموونە GET) | 401 Unauthorized |
| (e) | anyهەر کامێک | 429 Too Many Requests |
Without looking at your notes: (a) explain the two parts of the name Application Programming Interface; (b) give one definition of an API; (c) name the four API examples from the course notes; (d) name the five benefits of APIs.
بەبێ سەیرکردنی تێبینییەکانت: (أ) دوو بەشەکەی ناوی Application Programming Interface ڕوون بکەرەوە؛ (ب) یەک پێناسە بۆ بدە؛ (ج) ئەو چوار نموونەیەی ناو ببە کە لە تێبینییەکانی کۆرسەکەدان؛ (د) پێنج سوودەکەی ناو ببە.
Show answerوەڵامەکە پیشان بدە
- (a) Application programming is creating application programs with programming languages (an application program does a job directly for the user, such as a media player or a browser). An interface is a point where two things meet and interact, like a door.
- (b) For example: an API is a software intermediary that allows two applications to talk to each other, without one needing to know how the other works inside.
- (c) Google Maps API, the Twitter (now X) API, weather APIs and social login APIs.
- (d) Cost-saving, increased productivity, improved connection, improved customer experience, and promoting marketing activities.
- (أ) ئەپڵیکەیشن دروستکردنی ئەپڵیکەیشنە بە ( ئەپڵیکەیشن کارێک ڕاستەوخۆ بۆ دەکات، وەک یان ). خاڵێکە کە دوو شت تێیدا بەیەک دەگەن و کار لە یەکتر دەکەن، وەک دەرگا.
- (ب) بۆ نموونە: ناوەندگیرێکی کە ڕێگە بە دوو ئەپڵیکەیشن دەدات قسە لەگەڵ یەکتر بکەن، بەبێ ئەوەی یەکێکیان پێویست بێت بزانێت ئەوی تر لە ناوەوە چۆن کار دەکات.
- (ج) Google Maps API، APIی Twitter (ئێستا X)، کەشوهەوا و بە .
- (د) کەمکردنەوەی تێچوون، زیادبوونی بەرهەمداری، باشترکردنی پەیوەندی، باشترکردنی ئەزموونی کڕیار و بەهێزکردنی چالاکیی بازاڕکردن.
Exercisesڕاهێنانەکان
Quick checkپشکنینی خێرا
Summary and reviewکورتە و پێداچوونەوە
- API = Application Programming Interface: the door one application opens so other programs can use its features and data without knowing how it works inside.
- Examples: Google Maps, the X (Twitter) API, weather APIs and social login. Benefits: cost-saving, productivity, connection, customer experience and marketing.
- A web API works over HTTP: a request (method, endpoint URL, headers, body) and a response (status code, headers, usually a JSON body).
json_encode()turns PHP arrays into JSON;json_decode($json, true)turns JSON into arrays. Check fornullor useJSON_THROW_ON_ERROR.- A PHP page becomes an API with
header("Content-Type: application/json"),echo json_encode(...)andhttp_response_code(). - Call APIs with
file_get_contents()(simple) or cURL (timeouts, headers, status codes). Keep keys secret, use HTTPS, and escape API data before printing it.
- API = Application Programming Interface: ئەو دەرگایەی ئەپڵیکەیشنێک دەیکاتەوە تا تر تواناکان و بەکاربهێنن بەبێ ئەوەی بزانن لە ناوەوە چۆن کار دەکات.
- نموونەکان: Google Maps، APIی X (Twitter)، کەشوهەوا و بە . سوودەکان: کەمکردنەوەی تێچوون، بەرهەمداری، پەیوەندی، ئەزموونی کڕیار و بازاڕکردن.
- وێب بە HTTP کار دەکات: (، ، ، لاشە) و (، ، زۆرجار لاشەیەکی JSON).
json_encode()PHP دەکات بە JSON؛json_decode($json, true)JSON دەکات بە .nullبپشکنە یانJSON_THROW_ON_ERRORبەکاربهێنە.- پەڕەیەکی PHP بە
header("Content-Type: application/json")،echo json_encode(...)وhttp_response_code()دەبێتە . - بە
file_get_contents()(سادە) یان cURL (ماوەی چاوەڕوانی، ، ) بانگ بکە. کلیلەکان بە نهێنی بهێڵەرەوە، بەکاربهێنە و پێش چاپکردن پارێزراو بکە.
What are the two parts of the name “API”, according to the course notes?بەپێی تێبینییەکانی کۆرسەکە، دوو بەشەکەی ناوی «API» چین؟
Application programming (creating application programs with programming languages) and interface (a point where two things meet and interact, like a door).
ئەپڵیکەیشن (دروستکردنی ئەپڵیکەیشن بە ) و (خاڵێک کە دوو شت تێیدا بەیەک دەگەن و کار لە یەکتر دەکەن، وەک دەرگا).
What does an API let one application do with another, and what does it hide?API ڕێگە بە ئەپڵیکەیشنێک دەدات چی لەگەڵ ئەپڵیکەیشنێکی تر بکات و چی دەشارێتەوە؟
It lets it use the other application's functions, data or services. It hides how they are implemented inside.
ڕێگەی دەدات ، یان خزمەتگوزارییەکانی ئەپڵیکەیشنەکەی تر بەکاربهێنێت. ئەوە دەشارێتەوە کە لە ناوەوە چۆن دروست کراون.
Name the five benefits of APIs from the course notes.پێنج سوودەکەی API لە تێبینییەکانی کۆرسەکەدا ناو ببە.
Cost-saving, increased productivity, improved connection, improved customer experience and promoting marketing activities.
کەمکردنەوەی تێچوون، زیادبوونی بەرهەمداری، باشترکردنی پەیوەندی، باشترکردنی ئەزموونی کڕیار و بەهێزکردنی چالاکیی بازاڕکردن.
What is an endpoint?خاڵی کۆتایی چییە؟
One URL of an API that does one job, for example GET /api/students.php?id=2.
یەک کە یەک کار دەکات، بۆ نموونە GET /api/students.php?id=2.
What is the difference between json_decode($json) and json_decode($json, true)?جیاوازیی نێوان json_decode($json) و json_decode($json, true) چییە؟
The first returns an object ($obj->name); the second returns an associative array ($arr["name"]).
یەکەمیان دەگەڕێنێتەوە ($obj->name)؛ دووەمیان ($arr["name"]).
Which header tells the client that a response is JSON?کام سەردێڕی HTTP بە ڕاژەخواز دەڵێت وەڵامێک JSONـە؟
Content-Type: application/json (sent in PHP with header() before any output).
Content-Type: application/json (لە PHPـدا بە header() پێش هەر دەنێردرێت).
Why does CURLOPT_RETURNTRANSFER matter?بۆچی CURLOPT_RETURNTRANSFER گرنگە؟
With it, curl_exec() returns the response body as a string you can decode. Without it, cURL prints the body directly.
بە ئەمە، curl_exec() لاشەی وەک دەگەڕێنێتەوە کە دەتوانیت بیکەیتەوە (decode). بەبێ ئەمە، cURL لاشەکە ڕاستەوخۆ چاپ دەکات.
Give three rules for using APIs safely.سێ یاسا بۆ بەکارهێنانی API بە سەلامەتی بڵێ.
Keep API keys on the server and out of Git; use HTTPS and timeouts and check every answer; escape API data with htmlspecialchars() before printing.
لەسەر و لە دەرەوەی Git بهێڵەرەوە؛ و ماوەی چاوەڕوانی بەکاربهێنە و هەموو وەڵامدانەوەیەک بپشکنە؛ پێش چاپکردن بە htmlspecialchars() پارێزراو بکە.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
A short, clear picture of what an API is, a restaurant example, and how a web API request and response work.
ڕوونکردنەوەیەکی کورت و ئاشکرا: چییە، نموونەیەک لە چێشتخانەوە و و وێب چۆن کار دەکەن.
Watch first: a 4-minute overview of APIs and of web API requests and responses.
سەرەتا ئەمە سەیر بکە: ناساندنێکی 4 خولەکی بۆ و و وێب.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Course review and practiceپێداچوونەوە و ڕاهێنانی کۆرسەکە
Related lecturesوانە پەیوەندیدارەکان
- PHP Superglobalsسووپەرگلۆباڵەکانی PHP
- Form Handling with GET and POSTمامەڵەکردن لەگەڵ فۆرم بە GET و POST
- Form Security and Sticky Formsئاسایشی فۆرم و فۆرمە لکاوەکان
- Securing Data in PHP and MySQLپاراستنی دراوە لە PHP و MySQL
- Building a CRUD Application with PHP and MySQLدروستکردنی بەرنامەیەکی CRUD بە PHP و MySQL
- Redirects: Sending the Browser Somewhere Elseئاڕاستەکردنەوە: ناردنی تۆڕگەڕ بۆ شوێنێکی تر
- Course review and practiceپێداچوونەوە و ڕاهێنانی کۆرسەکە
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- PHP Manual: JSON
- PHP Manual: json_encode()
- PHP Manual: json_decode()
- PHP Manual: json_validate()
- PHP Manual: cURL
- PHP Manual: curl_setopt()
- PHP Manual: file_get_contents()
- PHP Manual: http_response_code()
- PHP Manual: php:// wrappers (php://input)
- MDN Glossary: API
- MDN Glossary: JSON
- MDN Glossary: REST
- MDN: HTTP response status codes
- Introducing JSON (json.org)
- RFC 8259: The JSON Data Interchange Format
- Open-Meteo weather API documentation
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.